o
    di-+                     @   s   d Z ddlZddlmZ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mZmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZ erPddlmZ eeZdZ G dd deZ!G dd deZ"dS )zBase exporters config.    N)ABCabstractmethod)TYPE_CHECKINGAnyDictListOptionalUnion)is_torch_available   )DEFAULT_DUMMY_SHAPESDummyInputGeneratorlogging)TORCH_MINIMUM_VERSION)TRANSFORMERS_MINIMUM_VERSION)add_dynamic_docstring)is_torch_versionis_transformers_version)PretrainedConfiga)  
        Generates the dummy inputs necessary for tracing the model. If not explicitely specified, default input shapes are used.

        Args:
            framework (`str`, defaults to `"pt"`):
                The framework for which to create the dummy inputs.
            batch_size (`int`, defaults to {batch_size}):
                The batch size to use in the dummy inputs.
            sequence_length (`int`, defaults to {sequence_length}):
                The sequence length to use in the dummy inputs.
            num_choices (`int`, defaults to {num_choices}):
                The number of candidate answers provided for multiple choice task.
            image_width (`int`, defaults to {width}):
                The width to use in the dummy inputs for vision tasks.
            image_height (`int`, defaults to {height}):
                The height to use in the dummy inputs for vision tasks.
            num_channels (`int`, defaults to {num_channels}):
                The number of channels to use in the dummpy inputs for vision tasks.
            feature_size (`int`, defaults to {feature_size}):
                The number of features to use in the dummpy inputs for audio tasks in case it is not raw audio.
                This is for example the number of STFT bins or MEL bins.
            nb_max_frames (`int`, defaults to {nb_max_frames}):
                The number of frames to use in the dummpy inputs for audio tasks in case the input is not raw audio.
            audio_sequence_length (`int`, defaults to {audio_sequence_length}):
                The number of frames to use in the dummpy inputs for audio tasks in case the input is raw audio.

        Returns:
            `Dict[str, [tf.Tensor, torch.Tensor]]`: A dictionary mapping the input names to dummy tensors in the proper framework format.
c                       s   e Zd Z fddZ  ZS )ExportConfigc                    s    t  jdi | td d S )NztThe `ExportConfig` class is deprecated and will be removed in a future version. Please use `ExporterConfig` instead. )super__init_subclass__loggerwarning)clskwargs	__class__r   d/lsinfo/ai/hellotax_ai/llm_service/venv_embed/lib/python3.10/site-packages/optimum/exporters/base.pyr   H   s   zExportConfig.__init_subclass__)__name__
__module____qualname__r   __classcell__r   r   r   r   r   G   s    r   c                   @   s  e Zd ZU dZdZdZdZeee	e
ef f ed< eZeZi ddgddgd	dgd
dgddgddgddgddgddgddgddgddgddgddgddgdddgdddgdgdgdgdgdgdgdgg dg d d!	Z	"	#d=d$d%d&e
d'e
d(e
fd)d*Zd+ee fd,d-Zeed+e	e
e	ee
f f fd.d/Zed+e	e
e	ee
f f fd0d1Zed+ee	e
ef  fd2d3Zed+efd4d5Zed+efd6d7Ze e!e"d8d>d:e
d+e	fd;d<Z#dS )?ExporterConfiga:  
    Base class describing metadata on how to export the model.

    Class attributes:

    - NORMALIZED_CONFIG_CLASS (`Type`) -- A class derived from [`~optimum.utils.NormalizedConfig`] specifying how to
    normalize the model config.
    - DUMMY_INPUT_GENERATOR_CLASSES (`Tuple[Type]`) -- A tuple of classes derived from
    [`~optimum.utils.DummyInputGenerator`] specifying how to create dummy inputs.
    - ATOL_FOR_VALIDATION (`Union[float, Dict[str, float]]`) -- A float or a dictionary mapping task names to float,
    where the float values represent the absolute tolerance value to use during model conversion validation.
    - MIN_TORCH_VERSION (`packaging.version.Version`, defaults to [`~optimum.exporters.utils.TORCH_MINIMUM_VERSION`]) -- The
    minimum torch version supporting the export of the model.
    - MIN_TRANSFORMERS_VERSION (`packaging.version.Version`, defaults to
    [`~optimum.exporters.utils.TRANSFORMERS_MINIMUM_VERSION`] -- The minimum transformers version supporting the
    export of the model. Not always up-to-date or accurate. This is more for internal use.
    - PATCHING_SPECS (`Optional[List[PatchingSpec]]`, defaults to `None`) -- Specify which operators / modules should be
    patched before performing the export, and how. This is useful when some operator is not supported for instance.

    Args:
        config (`transformers.PretrainedConfig`):
            The model configuration.
        task (`str`, defaults to `"feature-extraction"`):
            The task the model should be exported for.
        int_dtype (`str`, defaults to `"int64"`):
            The data type of integer tensors, could be ["int64", "int32", "int8"], default to "int64".
        float_dtype (`str`, defaults to `"fp32"`):
            The data type of float tensors, could be ["fp32", "fp16", "bf16"], default to "fp32".
    Nr   gh㈵>ATOL_FOR_VALIDATIONzaudio-classificationlogitszaudio-frame-classificationzautomatic-speech-recognitionzaudio-xvectorzdepth-estimationpredicted_depthzdocument-question-answeringzfeature-extractionlast_hidden_statez	fill-maskzimage-classificationzimage-segmentationzimage-to-textzimage-to-imagereconstructionzmask-generationz	masked-imzmultiple-choicezobject-detection
pred_boxeszquestion-answeringstart_logits
end_logitsprediction_outputs)logits_per_imagelogits_per_texttext_embedsimage_embeds)r&   r*   r0   r1   )	zsemantic-segmentationztext2text-generationztext-classificationztext-generationztime-series-forecastingztoken-classificationzvisual-question-answeringzzero-shot-image-classificationzzero-shot-object-detectionint64fp32configr   task	int_dtypefloat_dtypec                 C   s*   || _ || _| | j| _|| _|| _d S )N)r5   _configNORMALIZED_CONFIG_CLASS_normalized_configr6   r7   )selfr4   r5   r6   r7   r   r   r   __init__   s
   
zExporterConfig.__init__returnc                    s    fddj D S )a{  
        Instantiates the dummy input generators from `self.DUMMY_INPUT_GENERATOR_CLASSES`.
        Each dummy input generator is independent, so this method instantiates the first generator, and
        forces the other generators to use the same batch size, meaning they will all produce inputs of the same batch
        size. Override this method for custom behavior.
        c                    s"   g | ]}|j jfi  qS r   )r5   r:   ).0cls_r   r;   r   r   
<listcomp>   s   " zHExporterConfig._create_dummy_input_generator_classes.<locals>.<listcomp>)DUMMY_INPUT_GENERATOR_CLASSES)r;   r   r   r@   r   %_create_dummy_input_generator_classes   s   z4ExporterConfig._create_dummy_input_generator_classesc                 C   s   t  )z
        Dict containing the axis definition of the input tensors to provide to the model.

        Returns:
            `Dict[str, Dict[int, str]]`: A mapping of each input name to a mapping of axis position to the axes symbolic name.
        )NotImplementedErrorr;   r   r   r   inputs   s   	zExporterConfig.inputsc                 C   s   | j | j }t|S )z
        Dict containing the axis definition of the output tensors to provide to the model.

        Returns:
            `Dict[str, Dict[int, str]]`: A mapping of each output name to a mapping of axis position to the axes symbolic name.
        )_TASK_TO_COMMON_OUTPUTSr5   copydeepcopy)r;   common_outputsr   r   r   outputs   s   
zExporterConfig.outputsc                 C   s   t | jdr
ddiS dS )z
        Dictionary of keys to override in the model's config before exporting.

        Returns:
            `Optional[Dict[str, Any]]`: A dictionary specifying the configuration items to override.
        	use_cacheFN)hasattrr8   rE   r   r   r   values_override   s   zExporterConfig.values_overridec                 C   s   t d| jjS )z
        Whether the installed version of Transformers allows the export.

        Returns:
            `bool`: Whether the install version of Transformers is compatible with the model.

        >=)r   MIN_TRANSFORMERS_VERSIONbase_versionrE   r   r   r   !is_transformers_support_available   s   	z0ExporterConfig.is_transformers_support_availablec                 C   s   t  r
td| jjS dS )z
        Whether the installed version of PyTorch allows the export.

        Returns:
            `bool`: Whether the installed version of PyTorch is compatible with the model.
        rO   F)r
   r   MIN_TORCH_VERSIONrQ   rE   r   r   r   is_torch_support_available   s   z)ExporterConfig.is_torch_support_available)textdynamic_elementspt	frameworkc                 K   sr   | j di |}i }| jD ])}d}|D ]}||r+|j||| j| jd||< d} nq|s6td| dq|S )NF)rX   r6   r7   Tz$Could not generate dummy input for "zK". Try adding a proper dummy input generator to the model exporters config.r   )rC   rF   supports_inputgenerater6   r7   RuntimeError)r;   rX   r   dummy_inputs_generatorsdummy_inputs
input_nameinput_was_inserteddummy_input_genr   r   r   generate_dummy_inputs   s$   



z$ExporterConfig.generate_dummy_inputs)r2   r3   )rW   )$r    r!   r"   __doc__r9   rB   r%   r	   floatr   str__annotations__GLOBAL_MIN_TORCH_VERSIONrS   GLOBAL_MIN_TRANSFORMERS_VERSIONrP   rG   r<   r   r   rC   propertyr   intrF   rK   r   r   rN   boolrR   rT   r   GENERATE_DUMMY_DOCSTRINGr   ra   r   r   r   r   r$   P   s   
 	
!
	"	 


r$   )#rb   rH   abcr   r   typingr   r   r   r   r   r	   transformers.utilsr
   utilsr   r   r   r   rf   r   rg   	utils.docr   utils.import_utilsr   r   transformersr   
get_loggerr    r   rk   r   r$   r   r   r   r   <module>   s     
	