U
    yhP                     @  s   d dl mZ d dlmZ d dlmZmZmZmZm	Z	m
Z
 d dlmZ d dlmZ d dlmZmZmZ ddd	d
gZdZdZdZdZdZdZdZdZdZeG dd
 d
ZG dd	 d	ZG dd dZG dd dZ dS )    )annotations)	dataclass)AnyDictListOptionalTupleType)QConfigMapping)BackendConfig)	QuantType_quant_type_from_str_get_quant_type_to_strConvertCustomConfigFuseCustomConfigPrepareCustomConfigStandaloneModuleConfigEntryZstandalone_module_nameZstandalone_module_classZ%float_to_observed_custom_module_classZ)observed_to_quantized_custom_module_classZnon_traceable_module_nameZnon_traceable_module_classZinput_quantized_idxsZoutput_quantized_idxspreserved_attributesc                   @  s.   e Zd ZU ded< ded< ded< ded< d	S )
r   Optional[QConfigMapping]qconfig_mappingTuple[Any, ...]example_inputsOptional[PrepareCustomConfig]prepare_custom_configOptional[BackendConfig]backend_configN)__name__
__module____qualname____annotations__ r    r    X/var/www/html/venv/lib/python3.8/site-packages/torch/ao/quantization/fx/custom_config.pyr      s   
c                   @  s   e Zd ZdZdd Zdd Zdddd	d
d dddZdddd	d
d dddZej	fdddd dddZ
dd dddZdd dddZdd dd d!Zdd dd"d#Zdd d$d%d&Zed'd d(d)d*Zd'd+d,d-Zd.S )/r   a  
    Custom configuration for :func:`~torch.ao.quantization.quantize_fx.prepare_fx` and
    :func:`~torch.ao.quantization.quantize_fx.prepare_qat_fx`.

    Example usage::

        prepare_custom_config = PrepareCustomConfig()             .set_standalone_module_name("module1", qconfig_mapping, example_inputs,                 child_prepare_custom_config, backend_config)             .set_standalone_module_class(MyStandaloneModule, qconfig_mapping, example_inputs,                 child_prepare_custom_config, backend_config)             .set_float_to_observed_mapping(FloatCustomModule, ObservedCustomModule)             .set_non_traceable_module_names(["module2", "module3"])             .set_non_traceable_module_classes([NonTraceableModule1, NonTraceableModule2])             .set_input_quantized_indexes([0])             .set_output_quantized_indexes([0])             .set_preserved_attributes(["attr1", "attr2"])
    c                 C  s4   i | _ i | _i | _g | _g | _g | _g | _g | _d S N)standalone_module_namesstandalone_module_classesfloat_to_observed_mappingnon_traceable_module_namesnon_traceable_module_classesinput_quantized_indexesoutput_quantized_indexesr   selfr    r    r!   __init__<   s    zPrepareCustomConfig.__init__c                 C  s    dd | j  D }d| dS )Nc                 S  s"   i | ]\}}t |d kr||qS r   len.0kvr    r    r!   
<dictcomp>G   s    z0PrepareCustomConfig.__repr__.<locals>.<dictcomp>zPrepareCustomConfig()__dict__itemsr+   Zdict_nonemptyr    r    r!   __repr__F   s    zPrepareCustomConfig.__repr__strr   r   r   r   )module_namer   r   r   r   returnc                 C  s   t ||||| j|< | S )a|  
        Set the configuration for running a standalone module identified by ``module_name``.

        If ``qconfig_mapping`` is None, the parent ``qconfig_mapping`` will be used instead.
        If ``prepare_custom_config`` is None, an empty ``PrepareCustomConfig`` will be used.
        If ``backend_config`` is None, the parent ``backend_config`` will be used instead.
        )r   r#   )r+   r<   r   r   r   r   r    r    r!   set_standalone_module_nameM   s    z.PrepareCustomConfig.set_standalone_module_namer	   )module_classr   r   r   r   r=   c                 C  s   t ||||| j|< | S )a}  
        Set the configuration for running a standalone module identified by ``module_class``.

        If ``qconfig_mapping`` is None, the parent ``qconfig_mapping`` will be used instead.
        If ``prepare_custom_config`` is None, an empty ``PrepareCustomConfig`` will be used.
        If ``backend_config`` is None, the parent ``backend_config`` will be used instead.
        )r   r$   )r+   r?   r   r   r   r   r    r    r!   set_standalone_module_class_   s    z/PrepareCustomConfig.set_standalone_module_classr   )float_classobserved_class
quant_typer=   c                 C  s8   |t jkrtd|| jkr&i | j|< || j| |< | S )a5  
        Set the mapping from a custom float module class to a custom observed module class.

        The observed module class must have a ``from_float`` class method that converts the float module class
        to the observed module class. This is currently only supported for static quantization.
        zQset_float_to_observed_mapping is currently only supported for static quantization)r   STATIC
ValueErrorr%   )r+   rA   rB   rC   r    r    r!   set_float_to_observed_mappingq   s    


z1PrepareCustomConfig.set_float_to_observed_mapping	List[str])module_namesr=   c                 C  s
   || _ | S )zZ
        Set the modules that are not symbolically traceable, identified by name.
        )r&   )r+   rH   r    r    r!   set_non_traceable_module_names   s    z2PrepareCustomConfig.set_non_traceable_module_namesz
List[Type])module_classesr=   c                 C  s
   || _ | S )z[
        Set the modules that are not symbolically traceable, identified by class.
        )r'   )r+   rJ   r    r    r!    set_non_traceable_module_classes   s    z4PrepareCustomConfig.set_non_traceable_module_classesz	List[int])indexesr=   c                 C  s
   || _ | S )z
        Set the indexes of the inputs of the graph that should be quantized.
        Inputs are otherwise assumed to be in fp32 by default instead.
        )r(   r+   rL   r    r    r!   set_input_quantized_indexes   s    z/PrepareCustomConfig.set_input_quantized_indexesc                 C  s
   || _ | S )z
        Set the indexes of the outputs of the graph that should be quantized.
        Outputs are otherwise assumed to be in fp32 by default instead.
        )r)   rM   r    r    r!   set_output_quantized_indexes   s    z0PrepareCustomConfig.set_output_quantized_indexes
attributesr=   c                 C  s
   || _ | S z
        Set the names of the attributes that will persist in the graph module even if they are not used in
        the model's ``forward`` method.
        r   r+   rQ   r    r    r!   set_preserved_attributes   s    z,PrepareCustomConfig.set_preserved_attributesDict[str, Any])prepare_custom_config_dictr=   c                 C  st  dddddd}dddddd	}ddd
ddd}|  }| tg D ]>\}}}}	}
||t}||	t}||
t}|||||| qH| tg D ]>\}}}}	}
||t}||	t}||
t}|||||| q| ti  D ]0\}}t|}| D ]\}}|||| qq|	| t
g  || tg  || tg  || tg  || tg  |S )a  
        Create a ``PrepareCustomConfig`` from a dictionary with the following items:

            "standalone_module_name": a list of (module_name, qconfig_mapping, example_inputs,
            child_prepare_custom_config, backend_config) tuples

            "standalone_module_class" a list of (module_class, qconfig_mapping, example_inputs,
            child_prepare_custom_config, backend_config) tuples

            "float_to_observed_custom_module_class": a nested dictionary mapping from quantization
            mode to an inner mapping from float module classes to observed module classes, e.g.
            {"static": {FloatCustomModule: ObservedCustomModule}}

            "non_traceable_module_name": a list of modules names that are not symbolically traceable
            "non_traceable_module_class": a list of module classes that are not symbolically traceable
            "input_quantized_idxs": a list of indexes of graph inputs that should be quantized
            "output_quantized_idxs": a list of indexes of graph outputs that should be quantized
            "preserved_attributes": a list of attributes that persist even if they are not used in ``forward``

        This function is primarily for backward compatibility and may be removed in the future.
        r   r;   r   )objdict_keyr=   c                 S  sH   t | ts| dkr| S t | tr*t| S td| dt|  ddS )zn
            Convert the given object into a QConfigMapping if possible, else throw an exception.
            Nz7Expected QConfigMapping in prepare_custom_config_dict["	"], got '')
isinstancer
   r   	from_dictrE   typerX   rY   r    r    r!   _get_qconfig_mapping   s
    

z;PrepareCustomConfig.from_dict.<locals>._get_qconfig_mappingr   c                 S  sH   t | ts| dkr| S t | tr*t| S td| dt|  ddS )zs
            Convert the given object into a PrepareCustomConfig if possible, else throw an exception.
            Nz<Expected PrepareCustomConfig in prepare_custom_config_dict["rZ   r[   )r\   r   r   r]   rE   r^   r_   r    r    r!   _get_prepare_custom_config   s
    

zAPrepareCustomConfig.from_dict.<locals>._get_prepare_custom_configr   c                 S  sH   t | ts| dkr| S t | tr*t| S td| dt|  ddS )zm
            Convert the given object into a BackendConfig if possible, else throw an exception.
            Nz6Expected BackendConfig in prepare_custom_config_dict["rZ   r[   )r\   r   r   r]   rE   r^   r_   r    r    r!   _get_backend_config   s
    

z:PrepareCustomConfig.from_dict.<locals>._get_backend_config)getSTANDALONE_MODULE_NAME_DICT_KEYr>    STANDALONE_MODULE_CLASS_DICT_KEYr@   FLOAT_TO_OBSERVED_DICT_KEYr8   r   rF   rI   "NON_TRACEABLE_MODULE_NAME_DICT_KEYrK   #NON_TRACEABLE_MODULE_CLASS_DICT_KEYrN    INPUT_QUANTIZED_INDEXES_DICT_KEYrO   !OUTPUT_QUANTIZED_INDEXES_DICT_KEYrU   PRESERVED_ATTRIBUTES_DICT_KEY)clsrW   r`   ra   rb   confr<   qconfig_dictr   Z_prepare_custom_config_dictZbackend_config_dictr   r   r   r?   quant_type_namecustom_module_mappingrC   rA   rB   r    r    r!   r]      sL    






    



    zPrepareCustomConfig.from_dictr=   c                 C  s:  ddddd}i }| j  D ],\}}t|kr6g |t< |t ||| q| j D ],\}}t|krng |t< |t ||| qV| j D ](\}}t|kri |t< ||t t|< qt	| j
dkr| j
|t< t	| jdkr| j|t< t	| jdkr| j|t< t	| jdkr| j|t< t	| jdkr6| j|t< |S )z
        Convert this ``PrepareCustomConfig`` to a dictionary with the items described in
        :func:`~torch.ao.quantization.fx.custom_config.PrepareCustomConfig.from_dict`.
        r   r   )keyec                 S  s:   |j r|j  nd }|jr$|j nd }| ||j||jfS r"   )r   to_dictr   r   r   )rr   rs   rn   rW   r    r    r!   _make_tuple   s    z0PrepareCustomConfig.to_dict.<locals>._make_tupler   )r#   r8   rd   appendr$   re   r%   rf   r   r/   r&   rg   r'   rh   r(   ri   r)   rj   r   rk   )r+   ru   dr<   Zsm_config_entryr?   rC   r%   r    r    r!   rt      s2    




zPrepareCustomConfig.to_dictN)r   r   r   __doc__r,   r:   r>   r@   r   rD   rF   rI   rK   rN   rO   rU   classmethodr]   rt   r    r    r    r!   r   )   s   
	Nc                   @  sl   e Zd ZdZdd Zdd Zejfdddd dd	d
Zdd dddZ	e
dd dddZddddZdS )r   a;  
    Custom configuration for :func:`~torch.ao.quantization.quantize_fx.convert_fx`.

    Example usage::

        convert_custom_config = ConvertCustomConfig()             .set_observed_to_quantized_mapping(ObservedCustomModule, QuantizedCustomModule)             .set_preserved_attributes(["attr1", "attr2"])
    c                 C  s   i | _ g | _d S r"   )observed_to_quantized_mappingr   r*   r    r    r!   r,   (  s    zConvertCustomConfig.__init__c                 C  s    dd | j  D }d| dS )Nc                 S  s"   i | ]\}}t |d kr||qS r-   r.   r0   r    r    r!   r4   -  s    z0ConvertCustomConfig.__repr__.<locals>.<dictcomp>zConvertCustomConfig(r5   r6   r9   r    r    r!   r:   ,  s    zConvertCustomConfig.__repr__r	   r   )rB   quantized_classrC   r=   c                 C  s&   || j kri | j |< || j | |< | S )a  
        Set the mapping from a custom observed module class to a custom quantized module class.

        The quantized module class must have a ``from_observed`` class method that converts the observed module class
        to the quantized module class.
        )rz   )r+   rB   r{   rC   r    r    r!   !set_observed_to_quantized_mapping3  s    

z5ConvertCustomConfig.set_observed_to_quantized_mappingrG   rP   c                 C  s
   || _ | S rR   rS   rT   r    r    r!   rU   C  s    z,ConvertCustomConfig.set_preserved_attributesrV   )convert_custom_config_dictr=   c                 C  s^   |  }| ti  D ]0\}}t|}| D ]\}}|||| q.q|| tg  |S )a  
        Create a ``ConvertCustomConfig`` from a dictionary with the following items:

            "observed_to_quantized_custom_module_class": a nested dictionary mapping from quantization
            mode to an inner mapping from observed module classes to quantized module classes, e.g.::
            {
            "static": {FloatCustomModule: ObservedCustomModule},
            "dynamic": {FloatCustomModule: ObservedCustomModule},
            "weight_only": {FloatCustomModule: ObservedCustomModule}
            }
            "preserved_attributes": a list of attributes that persist even if they are not used in ``forward``

        This function is primarily for backward compatibility and may be removed in the future.
        )rc   OBSERVED_TO_QUANTIZED_DICT_KEYr8   r   r|   rU   rk   )rl   r}   rm   ro   rp   rC   rB   r{   r    r    r!   r]   L  s    zConvertCustomConfig.from_dictrq   c                 C  sT   i }| j  D ](\}}t|kr&i |t< ||t t|< qt| jdkrP| j|t< |S )z
        Convert this ``ConvertCustomConfig`` to a dictionary with the items described in
        :func:`~torch.ao.quantization.fx.custom_config.ConvertCustomConfig.from_dict`.
        r   )rz   r8   r~   r   r/   r   rk   )r+   rw   rC   rz   r    r    r!   rt   d  s    
zConvertCustomConfig.to_dictN)r   r   r   rx   r,   r:   r   rD   r|   rU   ry   r]   rt   r    r    r    r!   r     s   
	c                   @  sR   e Zd ZdZdd Zdd Zdd ddd	Zed
d dddZd
dddZ	dS )r   z
    Custom configuration for :func:`~torch.ao.quantization.quantize_fx.fuse_fx`.

    Example usage::

        fuse_custom_config = FuseCustomConfig().set_preserved_attributes(["attr1", "attr2"])
    c                 C  s
   g | _ d S r"   rS   r*   r    r    r!   r,   |  s    zFuseCustomConfig.__init__c                 C  s    dd | j  D }d| dS )Nc                 S  s"   i | ]\}}t |d kr||qS r-   r.   r0   r    r    r!   r4     s    z-FuseCustomConfig.__repr__.<locals>.<dictcomp>zFuseCustomConfig(r5   r6   r9   r    r    r!   r:     s    zFuseCustomConfig.__repr__rG   rP   c                 C  s
   || _ | S rR   rS   rT   r    r    r!   rU     s    z)FuseCustomConfig.set_preserved_attributesrV   )fuse_custom_config_dictr=   c                 C  s   |  }| |tg  |S )a/  
        Create a ``ConvertCustomConfig`` from a dictionary with the following items:

            "preserved_attributes": a list of attributes that persist even if they are not used in ``forward``

        This function is primarily for backward compatibility and may be removed in the future.
        )rU   rc   rk   )rl   r   rm   r    r    r!   r]     s    	zFuseCustomConfig.from_dictrq   c                 C  s    i }t | jdkr| j|t< |S )z
        Convert this ``FuseCustomConfig`` to a dictionary with the items described in
        :func:`~torch.ao.quantization.fx.custom_config.ConvertCustomConfig.from_dict`.
        r   )r/   r   rk   )r+   rw   r    r    r!   rt     s    
zFuseCustomConfig.to_dictN)
r   r   r   rx   r,   r:   rU   ry   r]   rt   r    r    r    r!   r   s  s   	N)!
__future__r   dataclassesr   typingr   r   r   r   r   r	   Ztorch.ao.quantizationr
   Z$torch.ao.quantization.backend_configr   Z torch.ao.quantization.quant_typer   r   r   __all__rd   re   rf   r~   rg   rh   ri   rj   rk   r   r   r   r   r    r    r    r!   <module>   s2    		 uV