
    ^j-"                        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 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)version   )logging)_is_package_availableis_torch_available   )ExportConfigMixin)decompose_for_generationN)Cache)PreTrainedModelc                  ~    e Zd ZU dZg Zded<   i 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]min_versionstested_versionsc                $    | j                          y )N)validate_environment)selfs    f/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/exporters/base.py__init__zHfExporter.__init__7   s    !!#    c           	         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|       g } j                  j                         D ]s  \  }}t        |d      \  }}|dk(  s?t        j                  |j                  dd      d         t        j                  |      k  sZ|j                  | d| d| d       u |r2t        t               j                   ddj                  |             |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>N   s@      be@T@T9T3%r$..s345Z]]s   .1zTo use z-, please install the following dependencies: z>=z (found )z requires newer versions of: c              3  8   K   | ]  \  }}}| d | d|   yw)z: installed z	, tested N )r!   r"   gotwants       r   r#   z2HfExporter.validate_environment.<locals>.<genexpr>]   s)     e^SRUW[3%|C5	$ Hes   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__r   itemsr   parseloggerwarning)r   argskwargsmissingdriftr"   exists	installedtestedinstalled_basetested_basespecsoutdatedminimum_detailss   `               r   r   zHfExporter.validate_environment:   s    R)) 
	EC 5c$ OFIs#))--c2F!i5&8!*a!8!;$ll3215![0LL#~{!CD
	E II ip E T
(;(;'<<ijoipqrr  --335 	ILC0TJLAyE!W]]9??33J13M%NQXQ^Q^_fQg%g3%r'(9+Q GH	I d!4!4 55RSWS\S\]eSfRghii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.exportd   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: .)rF   z.export failed on component 'z' (submodel=z, input keys=z).N)r   
isinstancedictset
ValueErrorsortedfromkeysr0   rG   	ExceptionRuntimeErrorr.   r/   list)r   rD   rE   rF   
componentsr6   configsexportednamesubmodel	subinputses               r   export_for_generationz HfExporter.export_for_generation   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)rD   r   rE   )MutableMapping[str, torch.Tensor | Cache]rF   r   )rD   r   rE   r[   rF   z0ExportConfigMixin | dict[str, ExportConfigMixin]returnzdict[str, object])r/   
__module____qualname____doc__r   __annotations__r   r   r   r   r   rG   rZ   r&   r   r   r   r   *   s     $&y%#%L.%&(O^($(T 

 A
 "	
 
>66 A6 A	6
 
6r   r   )r_   
__future__r   abcr   r   collections.abcr   typingr   	packagingr   utilsr
   utils.import_utilsr   r   rT   r   r   
get_loggerr/   r2   torchcache_utilsr   modeling_utilsr   r   r&   r   r   <module>rl      s[    : " # *     J & + 
		H	% '4P Pr   