
    $HJj                        d Z ddlmZ ddl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 d	d
lmZ d	dl
mZ  ej$                  e      Ze	r e       rddlZddlmZ ddlmZ  G d de      Zy)z3Abstract base class for all Transformers exporters.    )annotations)ABCabstractmethod)MutableMapping)TYPE_CHECKING   )logging)_is_package_availableis_torch_available   )ExportConfigMixin)decompose_for_generationN)Cache)PreTrainedModelc                  p    e Zd ZU dZg Zded<   i Zded<   d Zd Ze		 	 	 	 	 	 dd       Z
	 	 	 	 	 	 	 	 dd	Zy
)
HfExporterz
    Abstract base class for all Transformers exporters.

    Subclass and implement [`~HfExporter.export`] to add a new export backend.
    z	list[str]required_packageszdict[str, str]tested_versionsc                $    | j                          y )N)validate_environment)selfs    e/Users/ahmed/devFolder/claude-voice/.venv/lib/python3.12/site-packages/transformers/exporters/base.py__init__zHfExporter.__init__2   s    !!#    c                Z    g g }} j                   D ]  }t        |d      \  }}|s|j                  |       ' j                  j	                  |      }|E|dk7  sK|j                  dd      d   }	|j                  dd      d   }
|	|
k7  s{|j                  ||	|
f        |r>dj                   fd	|D              }t        d
t               j                   d|       |rGdj                  d |D              }t        j                  t               j                   d| d       yy)zYCheck `required_packages` are installed and warn on version drift from `tested_versions`.T)return_versionNzN/A+r   r   z, c              3  f   K   | ](  }|j                   v r| d j                   |    n| * yw)z==N)r   ).0pkgr   s     r   	<genexpr>z2HfExporter.validate_environment.<locals>.<genexpr>I   sA      ipbe@T@T9T3%r$..s345Z]]ips   .1zTo use z-, please install the following dependencies: c              3  8   K   | ]  \  }}}| d | d|   yw)z: installed z	, tested N )r   r    gotwants       r   r!   z2HfExporter.validate_environment.<locals>.<genexpr>O   s,     e_d^SRUW[3%|C5	$ H_ds   u~    is experimental and patches many backend internals; behaviour may differ from what was validated. Version drift detected — z-. If you hit issues, try the tested versions.)r   r
   appendr   getsplitjoinImportErrortype__name__loggerwarning)r   argskwargsmissingdriftr    exists	installedtestedinstalled_basetested_basespecsdetailss   `            r   r   zHfExporter.validate_environment5   sA    R))C 5c$ OFIs#))--c2F!i5&8!*a!8!;$ll3215![0LL#~{!CD * II ip E T
(;(;'<<ijoipqrriie_deeGNN:&&' (\\c[d e>? r   c                D    t        t        |       j                   d      )u  
        Export the model and return the backend-specific program object.

        Args:
            model ([`PreTrainedModel`]):
                The model to export.
            sample_inputs (`dict[str, torch.Tensor | Cache]`):
                **Forward** kwargs — what you'd pass to `model(**sample_inputs)`. These are used
                directly as the example inputs during tracing. For an autoregressive decode-step
                export, this means you need to include `past_key_values`, `cache_position`, etc.
                If you only have generation-style inputs, use [`~HfExporter.export_for_generation`]
                instead — it runs `model.generate` for you and exports each stage.
            config ([`~transformers.exporters.configs.ExportConfigMixin`]):
                Backend-specific configuration.

        Returns:
            Backend-specific export artifact.
        z does not implement `export`. Pick a concrete exporter (`DynamoExporter`, `OnnxExporter`, `ExecutorchExporter`), or override `export` in your subclass with a backend-specific tracing pipeline that consumes `config` and returns the runtime artifact.)NotImplementedErrorr+   r,   )r   modelsample_inputsconfigs       r   exportzHfExporter.exportV   s+    2 "Dz""# $0 0
 	
r   c                
   t        ||      }t        |t              r@t        |      t        |      z
  }|r$t	        dt        |       dt        |       d      |}nt        j                  ||      }i }|j                         D ]#  \  }\  }	}
	 | j                  |	|
||         ||<   % |S # t        $ rL}t        t        |       j                   d| dt        |	      j                   dt        |
       d      |d	}~ww xY w)
u  
        Decompose a generative model and export each component independently.

        Thin wrapper around [`~exporters.utils.decompose_for_generation`] that calls
        [`~HfExporter.export`] on every returned `(submodel, forward_inputs)` pair. If you need
        the intermediate `(submodel, forward_inputs)` pairs (for verification, custom inputs,
        skipping a stage, …), call [`~exporters.utils.decompose_for_generation`] directly.

        Args:
            model ([`PreTrainedModel`]):
                The generative model to export. Must support `model.generate(**sample_inputs)`.
            sample_inputs (`dict[str, torch.Tensor | Cache]`):
                **Generate** kwargs — what you'd pass to `model.generate(**sample_inputs)`
                (typically `input_ids` + `attention_mask`, plus any modality inputs like
                `pixel_values` / `input_features` for multi-modal models). Per-stage forward
                kwargs are captured internally.
            config ([`~transformers.exporters.configs.ExportConfigMixin`] or `dict[str, ExportConfigMixin]`):
                Backend-specific configuration. Pass a single config to apply to every
                component, or a `dict` keyed by component name (e.g. `"image_encoder"`,
                `"language_model"`, `"lm_head"`, `"decode"`) to override per-component —
                all component names must be present in the dict.

        Returns:
            `dict[str, Any]`: `{component_name: backend_specific_artifact}` — same keys as
            [`~exporters.utils.decompose_for_generation`]. Values are whatever
            [`~HfExporter.export`] returns for the concrete backend (`ExportedProgram`,
            `ONNXProgram`, `ExecutorchProgramManager`).
        z4Per-component `config` dict is missing entries for: z$. Expected one entry per component: .)r>   z.export failed on component 'z' (submodel=z, input keys=z).N)r   
isinstancedictset
ValueErrorsortedfromkeysitemsr?   	ExceptionRuntimeErrorr+   r,   list)r   r<   r=   r>   
componentsr1   configsexportednamesubmodel	subinputses               r   export_for_generationz HfExporter.export_for_generationv   s*   D .e]C
fd#*oF3G J6RY?J[ \99?
9K8LAO  GmmJ7G&(+5+;+;+='D'8Y!%XyQU!W ,>   "Dz**++H O!!%h!8!8 9tIFWWY[ s   B--	D6AC==DN)r<   r   r=   )MutableMapping[str, torch.Tensor | Cache]r>   r   )r<   r   r=   rT   r>   z0ExportConfigMixin | dict[str, ExportConfigMixin]returnzdict[str, object])r,   
__module____qualname____doc__r   __annotations__r   r   r   r   r?   rS   r#   r   r   r   r   (   s     $&y%&(O^($B 

 A
 "	
 
>66 A6 A	6
 
6r   r   )rX   
__future__r   abcr   r   collections.abcr   typingr   utilsr	   utils.import_utilsr
   r   rM   r   r   
get_loggerr,   r-   torchcache_utilsr   modeling_utilsr   r   r#   r   r   <module>rd      sX    : " # *    J & + 
		H	% '4D Dr   