+
    QV-jaÀ  ã                   ó4  € ^ RI t ^ RIt^RIHtHtHtHtHtHtH	t	 ^RI
Ht ^RIHt ^RIHtHt  ! R R4      t ! R R	]P$                  P&                  4      tR
 R lt ! R R]P$                  P&                  4      t ! R R]P$                  P&                  4      tRR R llt ! R R]P$                  P&                  4      t ! R R]P$                  P&                  4      t ! R R]P$                  P&                  4      tR R R lltR tR R ltR R ltR# )!é    N)ÚDynamicCacheÚDynamicLayerÚDynamicSlidingWindowLayerÚEncoderDecoderCacheÚStaticCacheÚStaticLayerÚStaticSlidingWindowLayer)ÚGenerationConfig)ÚPreTrainedModel)Úis_torch_greater_or_equalÚ"is_torch_greater_or_equal_than_2_6c                   ób   a € ] tR t^"t o RtRV 3R lR lltR tR tR tR t	R t
RR
 ltRtV tR	# )ÚTorchExportableModuleForVLMad  
A wrapper class for exporting Vision-Language Models (VLMs) like SmolVLM2 for ExecuTorch.

This class handles the export of three main components:
    1. Vision encoder (processes images to visual features)
    2. Connector/projector (maps visual features to text embedding space)
    3. Text decoder (generates text from combined visual and text tokens)
c                ó&   <€ V ^8„  d   QhRS[ RS[ /# )é   Úmax_batch_sizeÚmax_cache_len)Úint)ÚformatÚ__classdict__s   "€Úu/Volumes/fast/ai/experiments/ui-tars-smoke/.venv/lib/python3.14/site-packages/transformers/integrations/executorch.pyÚ__annotate__Ú(TorchExportableModuleForVLM.__annotate__,   s   ø€ ÷ *ñ *©cð *Ácñ *ó    c                ó  € Wn         W n        W0n        VP                  V n        VP                   P                  V n        VP                   P                  V n        VP                   P                  V n        RV n	        RV n
        RV n        R# )zÛ
Initialize the exportable VLM module.

Args:
    model: The VLM (e.g. SmolVLM) model instance
    max_batch_size: Maximum batch size. Always 1 for ExecuTorch
    max_cache_len: Maximum cache length for text generation
N)Úmodelr   r   ÚconfigÚvision_modelÚvision_encoderÚ	connectorÚ
text_modelÚtext_decoderÚexported_vision_encoderÚexported_connectorÚexported_text_decoder)Úselfr   r   r   s   &&&&r   Ú__init__Ú$TorchExportableModuleForVLM.__init__,   sq   € ð Œ
Ø,ÔØ*ÔØ—l‘lˆŒð $Ÿk™k×6Ñ6ˆÔØŸ™×.Ñ.ˆŒØ!ŸK™K×2Ñ2ˆÔð (,ˆÔ$Ø"&ˆÔØ%)ˆÖ"r   c                óž  € V P                   P                  4        \        P                  ! ^^RR\        P                  R7      pR^\        P
                  P                  P                  ^\        P
                  P                  P                  //p\        P
                  P                  V P                   V3VRR7      V n        V P                  # )z$Export the vision encoder component.i€  ©ÚdtypeÚpixel_valuesF©ÚargsÚdynamic_shapesÚstrict)	r   ÚevalÚtorchÚrandnÚfloat32ÚexportÚDimÚAUTOr#   )r&   r,   r/   s   &  r   Úexport_vision_encoderÚ1TorchExportableModuleForVLM.export_vision_encoderD   s«   € à×Ñ× Ñ Ô"ô —{’{ 1 a¨¨c¼¿¹ÔGˆð Ø”5—<‘<×#Ñ#×(Ñ(Ø”5—<‘<×#Ñ#×(Ñ(ðð
ˆô (-§|¡|×':Ñ':Ø×ÑØ�Ø)Øð	 (;ó (
ˆÔ$ð ×+Ñ+Ð+r   c                ó2  € V P                   P                  4        V P                  P                  P                  pV P                  P                  P
                  pV P                  P                  P                  pW#,          pWD,          p\        P                  ! ^WQ\        P                  R7      pR^\        P                  P                  P                  //p\        P                  P                  V P                   V3VRR7      V n        V P                  # )zExport the connector component.r*   Úimage_hidden_statesFr-   )r    r1   r   Úvision_configÚhidden_sizeÚ
image_sizeÚ
patch_sizer2   r3   r4   r5   r6   r7   r$   )r&   Úvision_hidden_sizer>   r?   Úpatches_per_dimÚnum_patchesr;   r/   s   &       r   Úexport_connectorÚ,TorchExportableModuleForVLM.export_connector\   sÞ   € à�‰×ÑÔð "Ÿ[™[×6Ñ6×BÑBÐØ—[‘[×.Ñ.×9Ñ9ˆ
Ø—[‘[×.Ñ.×9Ñ9ˆ
Ø$Õ2ˆØ%Õ7ˆÜ#Ÿkšk¨!¨[ÔTY×TaÑTaÔbÐð 0°!´U·\±\×5EÑ5E×5JÑ5JÐ1KÐLˆô #(§,¡,×"5Ñ"5Ø�N‰NØ%Ð'Ø)Øð	 #6ó #
ˆÔð ×&Ñ&Ð&r   c                ó  € \        V P                  R7      V n        ^p\        P                  ! ^V3\        P
                  R7      p\        P                  ! V\        P
                  R7      p\        V P                  V P                  P                  P                  4      p\        P                  P                  RV^,
          R7      pR^V/R^ V//pV P                  P                  VVVRR7      V n        V P                  # )	z"Export the text decoder component.©r   r*   Úseq_length_dim©ÚmaxÚ	input_idsÚcache_positionF)rJ   rK   r/   r0   )Ú%TorchExportableModuleForDecoderOnlyLMr"   Úexportable_text_decoderr2   ÚzerosÚlongÚarangeÚminr   r   Útext_configÚmax_position_embeddingsr5   r6   r%   )r&   Ú
seq_lengthrJ   rK   Úmax_seq_lengthÚseq_len_dimr/   s   &      r   Úexport_text_decoderÚ/TorchExportableModuleForVLM.export_text_decoderu   så   € ô (MÐSW×SdÑSdÔ'eˆÔ$ð ˆ
Ü—K’K  J ´u·z±zÔBˆ	ÜŸš j¼¿
¹
ÔCˆÜ˜T×/Ñ/°·±×1HÑ1H×1`Ñ1`ÓaˆÜ—l‘l×&Ñ&Ð'7¸^ÈaÕ=OÐ&ÓPˆð ˜!˜[Ð)Ø˜q +Ð.ð
ˆð
 &*×%AÑ%A×%HÑ%HØØ)Ø)Øð	 &Ió &
ˆÔ"ð ×)Ñ)Ð)r   c                óº   € V P                   ! R/ VB  V P                  ! R/ VB  V P                  ! R/ VB  RV P                  RV P                  RV P
                  /# )z'Export all components of the VLM model.r   r    r"   © )r8   rC   rW   r#   r$   r%   )r&   Úkwargss   &,r   r5   Ú"TorchExportableModuleForVLM.export�   s`   € à×"Ò"Ñ, VÒ,Ø×ÒÑ' Ò'Ø× Ò Ñ* 6Ò*à˜d×:Ñ:Ø˜×0Ñ0Ø˜D×6Ñ6ð
ð 	
r   c                ó   € R# )ap  
Simplified forward pass for inference with guaranteed non-null input_ids and cache_position.

Args:
    pixel_values: Input images [1, channels, height, width] (optional)
    input_ids: Text token IDs [1, seq_len] (required - won't be None)
    cache_position: Cache positions [seq_len] (required - won't be None)

Returns:
    Output with logits for text generation
NrZ   )r&   r,   rJ   rK   s   &&&&r   ÚforwardÚ#TorchExportableModuleForVLM.forward›   ó   ‚ r   Nc                ó   € R# )a˜  
Simplified generate method with guaranteed non-null input_ids.

Args:
    pixel_values: Input images [1, channels, height, width] (optional)
    input_ids: Initial text tokens [1, seq_len] (required - won't be None)
    max_new_tokens: Maximum number of tokens to generate
    do_sample: Whether to use sampling or greedy decoding
    temperature: Temperature for sampling

Returns:
    Generated sequences
NrZ   )r&   r,   rJ   Úmax_new_tokensÚ	do_sampleÚtemperaturer[   s   &&&&&&,r   ÚgenerateÚ$TorchExportableModuleForVLM.generate¨   r`   r   )r   r    rM   r$   r%   r#   r   r   r   r"   r   )é   é   )NNé2   Fç      ð?)Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__r'   r8   rC   rW   r5   r^   re   Ú__static_attributes__Ú__classdictcell__)r   s   @r   r   r   "   s7   ø‡ € ñ÷*ò *ò0,ò0'ò2*ò6	
ò÷ò r   r   c                   ó’   a a€ ] tR t^ºt oRtRV3R lV 3R llltRV3R lR lltRV3R lR llt]RV3R lR	 ll4       t	R
t
VtV ;t# )rL   zò
A recipe module designed to make a `PreTrainedModel` exportable with `torch.export`,
specifically for decoder-only LM with cache. This module ensures that the
exported model is compatible with further lowering and execution in `ExecuTorch`.
c          
      ót   <€ V ^8„  d   QhRS[ RS[R,          RS[R,          RS[P                  R,          RR/# ©r   r   Ú
batch_sizeNr   ÚdeviceÚreturn©r   r   r2   rv   )r   r   s   "€r   r   Ú2TorchExportableModuleForDecoderOnlyLM.__annotate__Á   sU   ø€ ÷ hñ háðhñ ˜$•Jðhñ ˜T•zð	hñ
 —‘˜tÕ#ðhð 
ñhr   c                óh  <€ \         SV `  4        VP                  P                  4       p\	        VR4      '       d   VP
                  RJ d   \        R4      h\	        VR4      '       d#   \        VRR4      e   \        WW44      V n	        R# \        P                  ! R4       \        WW44      V n	        R# )zÅ
Initializes the exportable module.

Args:
    model (`PreTrainedModel`): The pretrained model to wrap.

Raises:
    ValueError: If the model is configured with a unsupported cache implementation.
Ú	use_cacheFz5The model must have caching enabled to be performant.Úlayer_typesÚsliding_windowNzmUsing `StaticCache` for export as `layer_types` is not specified or `sliding_window` is `null` in the config.)Úsuperr'   r   Úget_text_configÚhasattrr{   Ú
ValueErrorÚgetattrÚ$TorchExportableModuleWithHybridCacher   ÚloggingÚinfoÚ$TorchExportableModuleWithStaticCache)r&   r   ru   r   rv   r   Ú	__class__s   &&&&& €r   r'   Ú.TorchExportableModuleForDecoderOnlyLM.__init__Á   s–   ø€ ô  	‰ÑÔà—‘×-Ñ-Ó/ˆä�v˜{×+Ò+¨v×/?Ñ/?À5Ó/HÜÐTÓUÐUä�6˜=×)Ò)¬g°fÐ>NÐPTÓ.UÒ.aÜ=¸eÐQ^ÓgˆDŽJô �LŠLØôô >¸eÐQ^ÓgˆDŽJr   c                ó¬   <€ V ^8„  d   QhRS[ P                  R,          RS[ P                  R,          RS[ P                  R,          RS[ P                  /# ©r   rJ   NÚinputs_embedsrK   rw   )r2   ÚTensor)r   r   s   "€r   r   ry   â   sX   ø€ ÷ Tñ Tá—<‘< $Õ&ðTñ —|‘| dÕ*ðTñ Ÿ™ tÕ+ð	Tñ
 
�‰ñTr   c                ó:   € V P                   P                  WR7      # )aª  
Forward pass of the module, which is compatible with the ExecuTorch llm runner.

Args:
    input_ids (`torch.Tensor`): Tensor representing current input token id to the module.
    inputs_embeds (`torch.Tensor`): Tensor representing current input embeddings to the module.
    cache_position (`torch.Tensor`): Tensor representing current input position in the cache.

Returns:
    torch.Tensor: Logits output from the model.
)rJ   r‹   )r   r^   )r&   rJ   r‹   rK   s   &&&&r   r^   Ú-TorchExportableModuleForDecoderOnlyLM.forwardâ   s   € ð" �z‰z×!Ñ!¨IÐ!ÓSÐSr   c                óè   <€ V ^8„  d   QhRS[ P                  R,          RS[ P                  R,          RS[ P                  R,          RS[R,          RS[R,          RS[ P                  P
                  /# )r   rJ   Nr‹   rK   r/   r0   rw   )r2   rŒ   ÚdictÚboolr5   ÚExportedProgram)r   r   s   "€r   r   ry   õ   s|   ø€ ÷ Z ñ Z á—<‘< $Õ&ðZ ñ —|‘| dÕ*ðZ ñ Ÿ™ tÕ+ð	Z ñ
 ˜t�ðZ ñ �t•ðZ ñ 
�‰×	%Ñ	%ñZ r   c           	     ó"  € VRJ VRJ ,          '       g   \        R4      h\        V P                  R4      '       dC   \        V P                  V P                  P                  V P                  4      pVP
                  pMU\        V P                  R4      '       d"   V P                  P                  P
                  pMRp\        P                  ! R4       VeD   RTRVe   TM7\        P                  ! VP                  R,          \        P                  VR	7      /pMBR
TRVe   TM7\        P                  ! VP                  ^,          \        P                  VR	7      /p\        P                  P                  V P                  RTTVe   TMRR7      p	V	# )aG  
Export the wrapped module using `torch.export`.

Args:
    input_ids (`Optional[torch.Tensor]`):
        Tensor representing current input token id to the module. Must specify either this or inputs_embeds.
    inputs_embeds (`Optional[torch.Tensor]`):
        Tensor representing current input embeddings to the module. Must specify either this or input_ids.
    cache_position (`Optional[torch.Tensor]`):
        Tensor representing current input position in the cache. If not provided, a default tensor will be used.
    dynamic_shapes (`Optional[dict]`):
        Dynamic shapes to use for export if specified.
    strict(`Optional[bool]`):
        Flag to instruct `torch.export` to use `torchdynamo`.

Returns:
    torch.export.ExportedProgram: The exported program that can be used for inference.

Examples:
    Export with input_ids:
    ```python
    # Prepare inputs
    input_ids = torch.tensor([[1, 2, 3]], dtype=torch.long, device=model.device)
    cache_position = torch.arange(input_ids.shape[-1], dtype=torch.long, device=model.device)

    # Export
    exported = exportable_module.export(
        input_ids=input_ids,
        cache_position=cache_position
    )
    ```

    Export with inputs_embeds:
    ```python
    # Prepare embeddings
    inputs_embeds = torch.randn(1, 3, 768, device=model.device)  # batch_size=1, seq_len=3, hidden_size=768
    cache_position = torch.arange(inputs_embeds.shape[1], dtype=torch.long, device=model.device)

    # Export
    exported = exportable_module.export(
        inputs_embeds=inputs_embeds,
        cache_position=cache_position
    )
    ```
Nz2Need to specify either input_ids or inputs_embeds.Úbase_model_prefixr   ÚcpuzfTorchExportableModuleForDecoderOnlyLM.export Can't infer device from the model. Set to CPU by default.rJ   rK   ©r+   rv   r‹   T©r.   r[   r/   r0   éÿÿÿÿrZ   )r�   r€   r   r‚   r”   rv   r„   Úwarningr2   rP   ÚshaperO   r5   )
r&   rJ   r‹   rK   r/   r0   ÚbaseÚmodel_deviceÚinput_kwargsÚexported_programs
   &&&&&&    r   r5   Ú,TorchExportableModuleForDecoderOnlyLM.exportõ   sU  € ðj ˜TÐ! m°tÐ&;×<Ô<ÜÐQÓRÐRä�4—:‘:Ð2×3Ò3Ü˜4Ÿ:™: t§z¡z×'CÑ'CÀTÇZÁZÓPˆDØŸ;™;‰LÜ�T—Z‘Z ×)Ò)ØŸ:™:×+Ñ+×2Ñ2‰Là ˆLÜ�OŠOØxôð Ò à˜YØ Ø!Ò-ñ #1ä—\’\ )§/¡/°"Õ"5¼U¿Z¹ZÐP\Ô]ð	‰Lð   Ø Ø!Ò-ñ #1ä—\’\ -×"5Ñ"5°aÕ"8ÄÇ
Á
ÐS_Ô`ð	ˆLô !Ÿ<™<×.Ñ.Ø�J‰JØØØ)Ø#Ò/‘6°Tð /ó 
Ðð  Ðr   c                óx   <€ V ^8„  d   QhRS[ P                  P                  RS[RS[RS[RS[RS[RS[RS[R	S[/	# )
r   rž   Úpromptrb   rc   rd   Útop_kÚtop_prv   rw   )r2   r5   r’   Ústrr   r‘   Úfloat)r   r   s   "€r   r   ry   R  s…   ø€ ÷ iLñ iLÙŸ,™,×6Ñ6ðiLñ ðiLñ ð	iLñ
 ðiLñ ðiLñ ðiLñ ðiLñ ðiLñ 
ñiLr   c	                ó„  € V P                  4       p	V! VRR7      P                  P                  V4      p
V
P                  4       p^ p\	        V
P
                  ^,          4       FP  pV
RWÝ^,           13,          p\        P                  ! V.\        P                  VR7      pV	! WïR7      pV^,          pKR  	  \	        V4       EFâ  pVRRR13,          p\        P                  ! V.\        P                  VR7      pV	! WïR7      pV'       Ed   V^ 8”  d   VV,          pMTpV^ 8”  d7   V\        P                  ! VV4      ^ ,          R,          8  p\        R4      VV&   VR	8  d“   \        P                  ! VR
R7      w  pp\        P                  ! \        P                  ! VRR7      RR7      pVV8„  pVRRR13,          P                  4       VR&   ^ VR&   VP                  RVV4      p\        R4      VV&   \        P                  ! VRR7      p\        P                  ! V^R7      pMVP!                  RR
R7      pVP#                  4       ^8”  d   VP%                  R4      p\        P&                  ! VV.RR7      pV^,          pVP)                  4       VP*                  8X  g   EKã   M	  VP-                  V^ ,          R
R7      # )a�  
Generate a sequence of tokens using an exported program.

Args:
    exported_program (`torch.export.ExportedProgram`): The exported model being used for generate.
    tokenizer: The tokenizer to use.
    prompt (str): The input prompt.
    max_new_tokens (int): Maximum number of new tokens to generate.
    do_sample (bool): Whether to use sampling or greedy decoding.
    temperature (float): The temperature for sampling.
    top_k (int): The number of highest probability tokens to keep for top-k sampling.
    top_p (float): The cumulative probability for nucleus sampling.
    device (str): The device to use.

Returns:
    str: The generated text.
Úpt)Úreturn_tensorsºNNNr–   ©rJ   rK   N.z-infrj   T)Ú
descending©Údim)Únum_samples)r­   Úkeepdim)Úskip_special_tokensr˜   ).r˜   N).:rg   NN).r   )ÚmodulerJ   ÚtoÚcloneÚrangerš   r2   ÚtensorrO   Útopkr¥   ÚsortÚcumsumÚsoftmaxÚscatterÚmultinomialÚargmaxr­   ÚsqueezeÚcatÚitemÚeos_token_idÚdecode)rž   Ú	tokenizerr¡   rb   rc   rd   r¢   r£   rv   Úexported_modulerJ   Úgenerated_idsÚcurr_positionÚiÚcurr_input_idsÚcurr_cache_positionÚ_ÚoutputsÚlogitsÚindices_to_removeÚsorted_logitsÚsorted_indicesÚcumulative_probsÚsorted_indices_to_removeÚprobsÚnext_token_ids   &&&&&&&&&                 r   re   Ú.TorchExportableModuleForDecoderOnlyLM.generateQ  s™  € ð< +×1Ñ1Ó3ˆñ ˜f°TÔ:×DÑD×GÑGÈÓOˆ	ð "Ÿ™Ó)ˆð ˆÜ�y—‘ qÕ)Ö*ˆAà& q¨!°!­e¨) |Õ4ˆNÜ"'§,¢,°¨ÄeÇjÁjÐY_Ô"`Ðñ  ¨.Ô]ˆAØ˜QÕŠMñ +ô �~×&ˆAà*¨1¨b©c¨6Õ2ˆNÜ"'§,¢,°¨ÄeÇjÁjÐY_Ô"`Ðñ &°ÔcˆG÷ ˆyà ”?Ø$ {Õ2‘Fà$�Fð ˜1”9Ø(.´·²¸FÀEÓ1JÈ1Õ1MÈmÕ1\Ñ(\Ð%Ü05°f³�FÐ,Ñ-ð ˜3”;Ü49·J²J¸vÐRVÔ4WÑ1�M >Ü',§|¢|´E·M²MÀ-ÐUWÔ4XÐ^`Ô'aÐ$ð 0@À%Ñ/GÐ,à8PÐQTÐVYÐWYÐVYÐQYÕ8Z×8`Ñ8`Ó8bÐ,¨WÑ5Ø78Ð,¨VÑ4ð )A×(HÑ(HÈÈ^Ð]uÓ(vÐ%Ü05°f³�FÐ,Ñ-ô Ÿš f°"Ô5�Ü %× 1Ò 1°%ÀQÔ G‘ð !(§¡°2¸t Ó D�ð × Ñ Ó" QÔ&Ø -× 5Ñ 5°bÓ 9�ô "ŸIšI }°mÐ&DÈ"ÔMˆMØ˜QÕˆMð ×!Ñ!Ó# y×'=Ñ'=×=Ùñk 'ðp ×Ñ ¨aÕ 0ÀdÐÓKÐKr   rF   ©NNN)NNNNN)é   Frj   ri   rj   r•   )rk   rl   rm   rn   ro   r'   r^   r5   Ústaticmethodre   rp   rq   Ú__classcell__©r‡   r   s   @@r   rL   rL   º   sV   ù‡ € ñ÷hõ h÷BTò T÷&Z ò Z ðx ÷iLñ iLó ÷iLð iLr   rL   c                óž   € V ^8„  d   QhR\         \        \        \        ,          ,          \        \        \        ,          ,          3,          /# )r   rw   )Útupler   Úlist)r   s   "r   r   r   ¾  s-   € ÷ ñ œu¤S¬4´­9¥_´c¼DÄ½IµoÐ%EÕFñ r   c                ó   € \        V R4      '       d¢   V P                  RV P                  )   Uu. uF"  pVR8X  d   V P                  MV P                  NK$  	  ppV P                  RV P                  )   Uu. uF4  pVR8X  d   V P
                  '       d   V P                  MV P                  NK6  	  ppW23# \        V RV P                  V P                  ,          4      p\        V RV P                  4      pW23# u upi u upi )zqReturns a tuple `(num_heads, head_dim)` containing either 2 ints, or a list of int with the value for each
layer.Úglobal_head_dimNÚfull_attentionÚhead_dimÚnum_key_value_heads)r€   r|   Únum_kv_shared_layersrÝ   rß   Úattention_k_eq_vÚnum_global_key_value_headsrà   r‚   r=   Únum_attention_heads)r   Úlayerrß   Ú	num_headss   &   r   Úget_head_shapesrç   ¾  s  € ô ˆvÐ(×)Ò)ð  ×+Ñ+Ð,J¨v×/JÑ/JÐ.JÑKó
áK�ð ',Ð/?Ô&?ˆF×"Ò"ÀVÇ_Á_ÒTÙKð 	ð 
ð  ×+Ñ+Ð,J¨v×/JÑ/JÐ.JÑKó	
ñ L�ð Ð(Ô(¨V×-D×-DÐ-Dð ×-Ò-à×+Ñ+ò,ñ Lð	 	ð 
ð ÐÐô ˜6 :¨v×/AÑ/AÀV×E_ÑE_Õ/_Ó`ˆÜ˜FÐ$9¸6×;UÑ;UÓVˆ	àÐÐùò
ùò
s   ¯(C6Á5C;ÂC;c                   óx   a a€ ] tR tRt oRtR
V3R lV 3R llltR
V3R lR llt]V3R lR l4       tR	t	Vt
V ;t# )r†   iÔ  a¶  
A recipe module designed to make a `PreTrainedModel` exportable with `torch.export`,
specifically for decoder-only LM to `StaticCache`. This module ensures that the
exported model is compatible with further lowering and execution in `ExecuTorch`.

Note:
    This class is specifically designed to support export process using `torch.export`
    in a way that ensures the model can be further lowered and run efficiently in `ExecuTorch`.
c          
      ót   <€ V ^8„  d   QhRS[ RS[R,          RS[R,          RS[P                  R,          RR/# rt   rx   )r   r   s   "€r   r   Ú1TorchExportableModuleWithStaticCache.__annotate__ß  s\   ø€ ÷ Ofñ OfáðOfñ ˜$•JðOfñ ˜T•zð	Ofñ
 —‘˜tÕ#ðOfð 
ñOfr   c                ó”  <€ \         SV `  4        VP                  P                  4       pVP                  pVf   \        R4      hVP                  '       g   \        R4      hVP                  R8w  d   \        R4      hVP                  f   / MVP                  pVf"   VP                  RR4      pVf   \        R4      hVf"   VP                  RR4      pVf   \        R	4      hVf   VP                  R
VP                  4      pWn        \        W5R7      V n        \        V P                  P                   4       F?  w  r‰\#        V	\$        4      '       g   K  \'        V4      V P                  P                   V&   KA  	  \)        V4      w  r«V P                  P*                  pV P                  P-                  W*W¼V4       \        V P                  P                   4       Fh  w  r‰V P/                  RV 2V	P0                  RR7       V P/                  RV 2V	P2                  RR7       V P/                  RV 2V	P4                  RR7       Kj  	  R# )a  
Initializes the wrapper module with the pretrained model.

Args:
    model (`PreTrainedModel`): The pretrained model to wrap. The model must have caching
        enabled and use a 'static' caching implementation.
    batch_size (`Optional[int]`): The batch size of the model. If not provided, we check if a value can be found
        in `generation_config.cache_config` and otherwise we raise a ValueError.
    max_cache_len (`Optional[int]`): The maximum cache length for generation. Same mechanism as `batch_size` if
        not provided.
    device (`Optional[torch.device]`): The device to use. If not provided, we check if a value can be found
        in `generation_config.cache_config` and otherwise we use `model.device` (no error is raised).

Raises:
    AssertionError: If the pretrained model does not have caching enabled or if it does
    not use a 'static' caching implementation in `model.generation_config`.
    ValueError: If `batch_size` or `max_cache_len` is not provided, either as an argument or in `cache_config`.
NúvThe model must have a generation config to be exported with static caching. Please set `generation_config` in `model`.zvThe model must have caching enabled to be exported with static caching. Please set `generation_config.use_cache=True`.Ústaticz–The model must use a 'static' caching implementation to be exported with static caching. Please set `generation_config.cache_implementation='static'`.ru   úFbatch_size must be provided, either as an argument or in cache_config.r   úImax_cache_len must be provided, either as an argument or in cache_config.rv   )r   r   Ú
key_cache_F©Ú
persistentÚvalue_cache_Úcumulative_length_)r~   r'   r   r   Úgeneration_configÚAssertionErrorr{   Úcache_implementationÚcache_configÚgetr�   rv   r   r   Ústatic_cacheÚ	enumerateÚlayersÚ
isinstancer	   r   rç   r+   Úearly_initializationÚregister_bufferÚkeysÚvaluesÚcumulative_length©r&   r   ru   r   rv   r   rõ   rø   rÆ   rå   ræ   rß   r+   r‡   s   &&&&&        €r   r'   Ú-TorchExportableModuleWithStaticCache.__init__ß  s.  ø€ ô2 	‰ÑÔà—‘×-Ñ-Ó/ˆØ!×3Ñ3Ðð Ò$Ü ð=óð ð !×*×*Ð*Ü ðAóð ð ×1Ñ1°XÔ=Ü ðPóð ð
 /×;Ñ;ÒC‘rÐIZ×IgÑIgˆð ÒØ%×)Ñ)¨,¸Ó=ˆJØÒ!Ü Ð!iÓjÐjØÒ Ø(×,Ñ,¨_¸dÓCˆMØÒ$Ü Ð!lÓmÐmàŠ>Ø!×%Ñ% h°·±Ó=ˆFð Œ
Ü'°mÔSˆÔô " $×"3Ñ"3×":Ñ":Ö;‰HˆAÜ˜%Ô!9×:Ô:Ü.9¸-Ó.H�×!Ñ!×(Ñ(¨Ó+ñ <ô .¨fÓ5Ñˆ	Ø—
‘
× Ñ ˆà×Ñ×.Ñ.¨zÀhÐW]Ô^ô " $×"3Ñ"3×":Ñ":Ö;‰HˆAØ× Ñ  :¨a¨SÐ!1°5·:±:È%Ð ÔPØ× Ñ  <°¨sÐ!3°U·\±\ÈeÐ ÔTØ× Ñ Ð#5°a°SÐ!9¸5×;RÑ;RÐ_dÐ Öeó <r   c                ó’   <€ V ^8„  d   QhRS[ P                  R,          RS[ P                  R,          RS[ P                  R,          /# )r   rJ   Nr‹   rK   ©r2   Ú
LongTensorrŒ   )r   r   s   "€r   r   rê   0  sF   ø€ ÷ /*ñ /*á×#Ñ# dÕ*ð/*ñ —|‘| dÕ*ð/*ñ Ÿ™ tÕ+ñ	/*r   c                ó  € V P                   P                   F%  pVP                  P                  VR,          4       K'  	  V P                   pV P	                  VVRVRR7      p\        VR4      '       d   VP                  # VP                  # )aÀ  
Forward pass of the module, which is compatible with the ExecuTorch runtime.

Args:
    input_ids (`torch.Tensor`): Tensor representing current input token id to the module.
    inputs_embeds (`torch.Tensor`): Tensor representing current input embeddings to the module.
    cache_position (`torch.Tensor`): Tensor representing current input position in the cache.

Returns:
    torch.Tensor: Logits output from the model.

This forward adapter serves two primary purposes:

1. **Making the Model `torch.export`-Compatible**:
    The adapter hides unsupported objects, such as the `Cache`, from the graph inputs and outputs,
    enabling the model to be exportable using `torch.export` without encountering issues.

2. **Ensuring Compatibility with `ExecuTorch` runtime**:
    The adapter matches the model's forward signature with that in `executorch/extension/llm/runner`,
    ensuring that the exported model can be executed in `ExecuTorch` out-of-the-box.
ºr   rg   NNT©rJ   r‹   Úattention_maskÚpast_key_valuesr{   rË   )rú   rü   r  Úcopy_r   r€   rË   Úlast_hidden_state)r&   rJ   r‹   rK   rå   r  Úoutss   &&&&   r   r^   Ú,TorchExportableModuleWithStaticCache.forward0  s‰   € ð< ×&Ñ&×-Ô-ˆEØ×#Ñ#×)Ñ)¨.¸Õ*=Ö>ñ .ð ×+Ñ+ˆà�z‰zØØ'ØØ+Øð ó 
ˆô �4˜×"Ò"à—;‘;Ðð ×)Ñ)Ð)r   c                ó‚   <€ V ^8„  d   QhRS[ P                  P                  RS[ P                  RS[RS[ P                  /# )r   rž   Úprompt_token_idsrb   rw   )r2   r5   r’   rŒ   r   )r   r   s   "€r   r   rê   b  sI   ø€ ÷ 2Pñ 2PÙŸ,™,×6Ñ6ð2PáŸ,™,ð2Pñ ð2Pñ 
�‰ñ	2Pr   c           
     óŽ  € VP                   pVP                  R,          pWB,           pV P                  4        F<  w  rgVP                  R4      '       g   K  VP                  ^,          p\	        WX4      p M	  . p	\        \	        WT4      4       Fˆ  p
V P                  4       P                  VRWª^,           13,          \        P                  ! V
.\        P                  VR7      R7      pV	P                  V^ ,          V
,          P                  4       4       KŠ  	  \        P                  ! XR,          RR7      P                  4       pV	P                  V4       \        V	4      V8  d¸   V P                  4       P                  \        P                  ! V..\        P                  VR7      \        P                  ! \        V	4      .\        P                  VR7      R7      p\        P                  ! VR,          RR7      P                  4       pV	P                  V4       KÇ  \        P                  ! V	.\        P                  VR7      # )ay  
Generate a sequence of tokens using an exported program.

This util function is designed to test exported models by simulating the generation process.
It processes the input prompt tokens sequentially (no parallel prefill).
This generate function is not intended to replace the original `generate` method, and the support
for leveraging the original `generate` is potentially planned!

Args:
    exported_program (`torch.export.ExportedProgram`): The exported program generated via `torch.export`.
    prompt_token_ids (`torch.Tensor`): Tensor representing the input prompt token IDs.
    max_new_tokens (`int`): Maximum number of new tokens to generate. Note that the total generation
        length is limited by both `max_new_tokens` and the model's cache size.

Returns:
    torch.Tensor: A tensor containing the generated sequence of token IDs, including the original prompt tokens.
Ú	key_cacher©   r–   rª   r¬   r˜   ©r©   r˜   r©   )rv   rš   Únamed_buffersÚ
startswithrQ   r´   r±   r^   r2   rµ   rO   Úappendr¿   r¼   Úlen)rž   r  rb   rv   Úprompt_token_lenÚmax_generation_lengthÚbuffer_nameÚbufferr   Úresponse_tokensÚ	input_posÚresultÚcurrent_tokens   &&&          r   re   Ú-TorchExportableModuleWithStaticCache.generatea  sÐ  € ð. "×(Ñ(ˆØ+×1Ñ1°"Õ5ÐØ 0Õ AÐØ#3×#AÑ#AÖ#CÑˆKØ×%Ñ% k×2Ô2Ø &§¡¨Q¥�Ü(+Ð,AÓ(QÐ%Ùñ	 $Dð ˆÜœsÐ#8ÓKÖLˆIØ%×,Ñ,Ó.×6Ñ6Ø*¨1¨iÀa½-Ð.GÐ+GÕHÜ$Ÿ|š|¨Y¨K¼u¿z¹zÐRXÔYð 7ó ˆFð ×"Ñ"Ð#3°AÕ#6°yÕ#A×#FÑ#FÓ#HÖIñ Mô Ÿš V¨HÕ%5¸2Ô>×CÑCÓEˆØ×Ñ˜}Ô-ä�/Ó"Ð%:Ô:Ø%×,Ñ,Ó.×6Ñ6ÜŸ,š,¨¨Ð'8ÄÇ
Á
ÐSYÔZÜ$Ÿ|š|¬S°Ó-AÐ,BÌ%Ï*É*Ð]cÔdð 7ó ˆFô "ŸLšL¨°Õ)9¸rÔB×GÑGÓIˆMØ×"Ñ" =Ö1ä�|Š|˜_Ð-´U·Z±ZÈÔOÐOr   )r   rú   rÔ   )rk   rl   rm   rn   ro   r'   r^   rÖ   re   rp   rq   r×   rØ   s   @@r   r†   r†   Ô  s@   ù‡ € ñ÷Ofõ Of÷b/*ò /*ðb ÷2Pó ÷2Pð 2Pr   r†   c                   ó\   a a€ ] tR tRt oRtRV3R lV 3R llltRV3R lR lltRtVtV ;t	# )	rƒ   i—  zÿ
A recipe module designed to make a `PreTrainedModel` exportable with `torch.export`,
specifically for decoder-only LM to hybrid `StaticCache`. This module ensures that the
exported model is compatible with further lowering and execution in `ExecuTorch`.
c          
      ót   <€ V ^8„  d   QhRS[ RS[R,          RS[R,          RS[P                  R,          RR/# rt   rx   )r   r   s   "€r   r   Ú1TorchExportableModuleWithHybridCache.__annotate__ž  s\   ø€ ÷ Bfñ BfáðBfñ ˜$•JðBfñ ˜T•zð	Bfñ
 —‘˜tÕ#ðBfð 
ñBfr   c                ó\  <€ \         SV `  4        Wn        VP                  P	                  4       pVP
                  pVf   \        R4      hVP                  '       g   \        R4      hVP                  f   / MVP                  pVf"   VP                  RR4      pVf   \        R4      hVf"   VP                  RR4      pVf   \        R4      hVf   VP                  RVP                  4      p\        WSR	7      V n        \        V P                  P                  4       F?  w  r‰\!        V	\"        4      '       g   K  \%        V4      V P                  P                  V&   KA  	  \'        V4      w  r«V P                  P(                  pV P                  P+                  W*W¼V4       \        V P                  P                  4       Fh  w  r‰V P-                  R
V 2V	P.                  RR7       V P-                  RV 2V	P0                  RR7       V P-                  RV 2V	P2                  RR7       Kj  	  R# )a[  
Initializes the exportable module.

Args:
    model (`PreTrainedModel`): The pretrained model to wrap.
    batch_size (`Optional[int]`): The batch size of the model. If not provided, we check if a value can be found
        in `generation_config.cache_config` and otherwise we raise a ValueError.
    max_cache_len (`Optional[int]`): The maximum cache length for generation. Same mechanism as `batch_size` if
        not provided.
    device (`Optional[torch.device]`): The device to use. If not provided, we check if a value can be found
        in `generation_config.cache_config` and otherwise we use `model.device` (no error is raised).
Raises:
    AssertionError: If the model doesn't have the expected configuration for hybrid StaticCache.
    ValueError: If `batch_size` or `max_cache_len` is not provided, either as an argument or in `cache_config`.
Nrì   z Model must have caching enabled.ru   rî   r   rï   rv   ©r   r   rð   Frñ   ró   rô   )r~   r'   r   r   r   rõ   rö   r{   rø   rù   r�   rv   r   Úcacherû   rü   rý   r	   r   rç   r+   rþ   rÿ   r   r  r  r  s   &&&&&        €r   r'   Ú-TorchExportableModuleWithHybridCache.__init__ž  s÷  ø€ ô, 	‰ÑÔØŒ
Ø—‘×-Ñ-Ó/ˆØ!×3Ñ3Ðð Ò$Ü ð=óð ð ××ÐÜ Ð!CÓDÐDà.×;Ñ;ÒC‘rÐIZ×IgÑIgˆàÒØ%×)Ñ)¨,¸Ó=ˆJØÒ!Ü Ð!iÓjÐjØÒ Ø(×,Ñ,¨_¸dÓCˆMØÒ$Ü Ð!lÓmÐmàŠ>Ø!×%Ñ% h°·±Ó=ˆFô !¨ÔLˆŒ
ô " $§*¡*×"3Ñ"3Ö4‰HˆAÜ˜%Ô!9×:Ô:Ü'2°=Ó'A�—
‘
×!Ñ! !Ó$ñ 5ô .¨fÓ5Ñˆ	Ø—
‘
× Ñ ˆà�
‰
×'Ñ'¨
¸xÐPVÔWô " $§*¡*×"3Ñ"3Ö4‰HˆAØ× Ñ  :¨a¨SÐ!1°5·:±:È%Ð ÔPØ× Ñ  <°¨sÐ!3°U·\±\ÈeÐ ÔTØ× Ñ Ð#5°a°SÐ!9¸5×;RÑ;RÐ_dÐ Öeó 5r   c                ó¬   <€ V ^8„  d   QhRS[ P                  R,          RS[ P                  R,          RS[ P                  R,          RS[ P                  /# rŠ   r  )r   r   s   "€r   r   r%  â  sT   ø€ ÷ !ñ !á×#Ñ# dÕ*ð!ñ —|‘| dÕ*ð!ñ Ÿ™ tÕ+ð	!ñ
 
�‰ñ!r   c                óØ   € V P                   P                   F%  pVP                  P                  VR,          4       K'  	  V P	                  VVRV P                   RR7      pVP
                  # )a´  
Forward pass of the module, which is compatible with the ExecuTorch llm runner.

Args:
    input_ids (`torch.Tensor`): Tensor representing current input token id to the module.
    inputs_embeds (`Optional[torch.Tensor]`): Tensor representing current input embeddings to the module.
    cache_position (`torch.Tensor`): Tensor representing current input position in the cache.

Returns:
    torch.Tensor: Logits output from the model.
r	  NTr
  )r(  rü   r  r  r   rË   )r&   rJ   r‹   rK   rå   rÊ   s   &&&&  r   r^   Ú,TorchExportableModuleWithHybridCache.forwardâ  se   € ð( —Z‘Z×&Ô&ˆEØ×#Ñ#×)Ñ)¨.¸Õ*=Ö>ñ 'ð —*‘*ØØ'ØØ ŸJ™JØð ó 
ˆð �~‰~Ðr   )r(  r   rÔ   ©
rk   rl   rm   rn   ro   r'   r^   rp   rq   r×   rØ   s   @@r   rƒ   rƒ   —  s(   ù‡ € ñ÷Bfõ Bf÷H!÷ !ò !r   rƒ   c                ó´   € V ^8„  d   QhR\         R\        P                  R,          R\        P                  R,          R\        R,          R\        R,          /# )r   r   Úexample_input_idsNÚexample_cache_positionr/   r0   )r   r2   rŒ   r�   r‘   )r   s   "r   r   r     sT   € ÷ ? ñ ? Üð? ä—|‘| dÕ*ð? ô "ŸL™L¨4Õ/ð? ô ˜4•Kð	? ô
 �4�Kñ? r   c           
     ó   € ^ RI pVP                  ! 4       ;_uu_ 4        Ve   TM*VP                  ! ^..VP                  V P                  R7      pVe   TM)VP                  ! ^ .VP                  V P                  R7      p\        R4      '       d5   VP                  P                  \        V 4      RRVRV/TVe   TMRR7      pMkVe   \        P                  ! R4       Ve   \        P                  ! R	4       VP                  P                  P                  \        V 4      RRVRV/R
RR7      pVuuRRR4       #   + '       g   i     R# ; i)aÇ  
Convert a `PreTrainedModel` into an exportable module and export it using `torch.export`,
ensuring the exported model is compatible with `ExecuTorch`.

Args:
    model (`PreTrainedModel`): The pretrained model to be exported.
    example_input_ids (`Optional[torch.Tensor]`): Example input token id used by `torch.export`.
    example_cache_position (`Optional[torch.Tensor]`): Example current cache position used by `torch.export`.
    dynamic_shapes(`Optional[dict]`): Dynamic shapes used by `torch.export`.
    strict(`Optional[bool]`): Flag to instruct `torch.export` to use `torchdynamo`.

Returns:
    Exported program (`torch.export.ExportedProgram`): The exported program generated via `torch.export`.
Nr–   z2.6.0rJ   rK   Tr—   zWDynamic shapes spec will be ignored by convert_and_export_with_cache for torch < 2.6.0.zSThe strict flag will be ignored by convert_and_export_with_cache for torch < 2.6.0.F)r.   r[   Úpre_dispatchr0   rZ   )Útorch.export._traceÚno_gradrµ   rO   rv   r   r5   r†   r„   r™   Ú_traceÚ_export)r   r/  r0  r/   r0   r2   rž   s   &&&&&  r   Úconvert_and_export_with_cacher7    s:  € ó, à	�Š��ð !Ò,ñ à—’ ˜s˜e¨5¯:©:¸e¿l¹lÔKð 	ð &Ò1ñ #à—’˜q˜c¨¯©¸E¿L¹LÔIð 	ô % W×-Ò-Ø$Ÿ|™|×2Ñ2Ü4°UÓ;ØØ#Ð%6Ð8HÐJ`ÐaØ-Ø!'Ò!3‘v¸ð  3ó  Ñð Ò)Ü—’Ømôð Ò!Ü—’Ð uÔvð
  %Ÿ|™|×2Ñ2×:Ñ:Ü4°UÓ;ØØ#Ð%6Ð8HÐJ`ÐaØ"Øð  ;ó  Ðð  ÷O 
��‹ús   žDD<Ä<E	c                   ó<   a a€ ] tR tRt oRtV 3R ltR tRtVtV ;t	# )Ú Seq2SeqLMEncoderExportableModuleiH  z«
A wrapper module designed to make a Seq2Seq LM encoder exportable with `torch.export`.
This module ensures that the exported encoder model is compatible with ExecuTorch.
c                ó0   <€ \         SV `  4        Wn        R # ©N)r~   r'   Úencoder)r&   Úencoder_modelr‡   s   &&€r   r'   Ú)Seq2SeqLMEncoderExportableModule.__init__N  s   ø€ Ü‰ÑÔØ$Žr   c                ó:   € V P                  VR 7      P                  # ))rJ   )r<  r  )r&   rJ   s   &&r   r^   Ú(Seq2SeqLMEncoderExportableModule.forwardR  s   € Ø�|‰| iˆ|Ó0×BÑBÐBr   )r<  r-  rØ   s   @@r   r9  r9  H  s   ù‡ € ñõ
%÷Cò Cr   r9  c                   ó<   a a€ ] tR tRt oRtV 3R ltR tRtVtV ;t	# )Ú/Seq2SeqLMDecoderExportableModuleWithStaticCacheiV  zÊ
A wrapper module designed to make a Seq2Seq LM decoder exportable with `torch.export`,
specifically for use with static caching. This module ensures the exported decoder
is compatible with ExecuTorch.
c                óâ  <€ \         S	V `  4        VP                  4       V n        VP                  V n        VP
                  V n        \        VP                  4       4      P                  p\        V P
                  VR 7      V n
        \        V P                  P                  4       F?  w  rV\        V\        4      '       g   K  \        V4      V P                  P                  V&   KA  	  \!        V P
                  4      w  rxV P                  P#                  W7V\$        P&                  V4       \)        V P                  \+        V P
                  R7      4      V n        \/        4        \        V P                  P                  4       Fh  w  rVV P1                  RV 2VP2                  RR7       V P1                  RV 2VP4                  RR7       V P1                  RV 2VP6                  RR7       Kj  	  R# )r'  ©r   rð   Frñ   ró   rô   N)r~   r'   Úget_decoderÚdecoderÚlm_headr   ÚnextÚ
parametersrv   r   rú   rû   rü   rý   r	   r   rç   rþ   r2   r4   r   r   r(  Ú%register_dynamic_cache_export_supportrÿ   r   r  r  )
r&   r   Úmax_static_cache_lengthru   rœ   rÆ   rå   ræ   rß   r‡   s
   &&&&     €r   r'   Ú8Seq2SeqLMDecoderExportableModuleWithStaticCache.__init__]  sŽ  ø€ Ü‰ÑÔð ×(Ñ(Ó*ˆŒØ—}‘}ˆŒØ—l‘lˆŒô ˜E×,Ñ,Ó.Ó/×6Ñ6ˆô (¨t¯{©{ÐJaÔbˆÔô " $×"3Ñ"3×":Ñ":Ö;‰HˆAÜ˜%Ô!9×:Ô:Ü.9Ð:QÓ.R�×!Ñ!×(Ñ(¨Ó+ñ <ô .¨d¯k©kÓ:Ñˆ	Ø×Ñ×.Ñ.¨zÀhÔPU×P]ÑP]Ð_kÔlÜ(¨×):Ñ):¼LÐPT×P[ÑP[Ô<\Ó]ˆŒ
ä-Ô/ô " $×"3Ñ"3×":Ñ":Ö;‰HˆAØ× Ñ  :¨a¨SÐ!1°5·:±:È%Ð ÔPØ× Ñ  <°¨sÐ!3°U·\±\ÈeÐ ÔTØ× Ñ Ð#5°a°SÐ!9¸5×;RÑ;RÐ_dÐ Öeó <r   c                óò   € V P                   P                   F%  pVP                  P                  VR ,          4       K'  	  V P	                  VVV P
                  RR7      pV P                  V^ ,          4      pV# )r	  T)rJ   Úencoder_hidden_statesr  r{   )rú   rü   r  r  rF  r(  rG  )r&   Údecoder_input_idsrN  rK   rå   rÊ   Ú	lm_logitss   &&&&   r   r^   Ú7Seq2SeqLMDecoderExportableModuleWithStaticCache.forward|  sr   € ð ×&Ñ&×-Ô-ˆEØ×#Ñ#×)Ñ)¨.¸Õ*=Ö>ñ .ð —,‘,Ø'Ø"7Ø ŸJ™JØð	 ó 
ˆð —L‘L ¨¥Ó,ˆ	àÐr   )r(  r   rF  rG  rú   r-  rØ   s   @@r   rB  rB  V  s   ù‡ € ñõf÷>ò r   rB  c                   óR   a a€ ] tR tRt oRV 3R lltR tR tR	R ltR tRt	Vt
V ;t# )
ÚSeq2SeqLMExportableModulei‘  c           	     óþ   <€ \         SV `  4        Wn        VP                  4       V n        VP
                  V n        W0n        \        R VVRVRV/VP                  P                  R7      V n        RV n
        RV n        R# )Tru   r   )r{   Ú
max_lengthr÷   rø   rÀ   N)r~   r'   Ú
full_modelÚget_encoderr<  r   Úmax_hidden_seq_lengthr
   rõ   rÀ   Úexported_encoderÚexported_decoder)r&   r   ru   rX  r÷   Úmax_cache_lengthr‡   s   &&&&&&€r   r'   Ú"Seq2SeqLMExportableModule.__init__’  s   ø€ ô 	‰ÑÔàŒØ×(Ñ(Ó*ˆŒØ—l‘lˆŒØ%:Ô"Ü!1ØØ'Ø!5à˜jØÐ!1ðð ×0Ñ0×=Ñ=ô	"
ˆÔð !%ˆÔØ $ˆÖr   c           	     óª  € \        V P                  4      P                  V P                  P                  4      P                  4       p\        P                  P                  R V P                  R7      p\        P                  ! 4       ;_uu_ 4        \        P                  P                  W!3R^V//RR7      pRRR4       V#   + '       g   i     X# ; i)Úencoder_seq_lengthrH   rJ   T©r/   r0   N)r9  r<  r²   rV  rv   r1   r2   r5   r6   rX  r4  )r&   Úencoder_input_idsÚwrapped_encoderrV   rY  s   &&   r   Ú_export_encoderÚ)Seq2SeqLMExportableModule._export_encoder¨  s«   € Ü:¸4¿<¹<ÓH×KÑKÈDÏOÉO×LbÑLbÓc×hÑhÓjˆô —l‘l×&Ñ&Ð';À×A[ÑA[Ð&Ó\ˆô �]Š]�_�_Ü$Ÿ|™|×2Ñ2ØÐ!5À{ÐUVÐXcÐTdÐFeÐnrð  3ó  Ð÷ ð
  Ð÷ Ž_ð
  Ðús   Â(CÃC	c                ó²  € V P                   P                  p\        V P                   V P                  P                  P                  R 4      V P                  P                  P                  R4      R7      P                  V4      P                  4       pVP                  V4      pVP                  V4      pVP                  V4      p\        P                  P                  RV P                  R7      p\        P                  ! 4       ;_uu_ 4        \        P                  P                  VWV3RRR^V/RR/R	R
7      pRRR4       V#   + '       g   i     X# ; i)r   ru   )r   rK  ru   Úencoder_hidden_seq_lengthrH   rO  NrN  rK   Tr_  )rV  rv   rB  rõ   rø   rù   r²   r1   r2   r5   r6   rX  r4  )r&   rO  rN  rK   Útarget_deviceÚwrapped_decoderÚencoder_seq_len_dimrZ  s   &&&&    r   Ú_export_decoderÚ)Seq2SeqLMExportableModule._export_decoder¶  s3  € ØŸ™×.Ñ.ˆä;Ø—o‘oØ(,×(>Ñ(>×(KÑ(K×(OÑ(OÐP_Ó(`Ø×1Ñ1×>Ñ>×BÑBÀ<ÓPô÷
 ‰R�Óß‰T‹Vð 	ð .×0Ñ0°Ó?ÐØ 5× 8Ñ 8¸Ó GÐØ'×*Ñ*¨=Ó9ˆô $Ÿl™l×.Ñ.Ð/JÐPT×PjÑPjÐ.ÓkÐô �]Š]�_�_Ü$Ÿ|™|×2Ñ2ØØ"¸>ÐJà'¨Ø+¨aÐ1DÐ-EØ$ dð ð
 ð  3ó 	 Ð÷ ð  Ð÷ Ž_ð  Ðús   Ä.EÅE	c                ón  € V P                   P                  pVe   TM&\        P                  ! R\        P                  VR7      pVe   TM(\        P
                  ! ^ ..\        P                  VR7      pVe   TM'\        P
                  ! ^ .\        P                  VR7      pVe   TM`\        P                  ! V P                  P                  P                  R4      ^
V P                  P                  3\        P                  VR7      p	V P                  V4      V n        V P                  WyV4      V n        V # )Nr–   ru   )rg   é
   )rV  rv   r2   ÚonesrO   rµ   rN   rõ   rø   rù   r   Úd_modelr4   rb  rY  ri  rZ  )
r&   r`  rO  rN  rK   rv   Úexample_encoder_input_idsÚexample_decoder_input_idsr0  Úexample_encoder_hidden_statess
   &&&&&     r   r5   Ú Seq2SeqLMExportableModule.exportÙ  s  € Ø—‘×'Ñ'ˆð !Ò,ñ ä—’˜G¬5¯:©:¸fÔEð 	"ð !Ò,ñ ä—’ ˜s˜e¬5¯:©:¸fÔEð 	"ð -Ò8‰N¼e¿lºlÈAÈ3ÔV[×V`ÑV`ÐioÔ>pð 	ð
 %Ò0ñ "ä—’Ø×'Ñ'×4Ñ4×8Ñ8¸ÓFÈÈDÏKÉK×L_ÑL_Ð`Ü—m‘mØôð 	&ð !%× 4Ñ 4Ð5NÓ OˆÔØ $× 4Ñ 4Ø%ÐF\ó!
ˆÔð
 ˆr   c                óL  € \         P                  ! 4       ;_uu_ 4        V P                  P                  pVP                  V8w  d   VP	                  V4      pV P
                  P                  4       ! V4      p\         P                  ! ^ ..\         P                  VR7      p^ .p\        V^,
          4       FÍ  pV P                  P                  4       ! WT\         P                  ! V.\         P                  VR7      4      p\         P                  ! VR,          RR7      P                  4       p	VP                  V	4       \         P                  ! V	..\         P                  VR7      pW�P                  P                  8X  g   KÍ   M	  VuuRRR4       #   + '       g   i     R# ; i)r   r–   r¬   Nr˜   r  )r2   r4  rV  rv   r²   rY  r±   rµ   rO   r´   rZ  r¼   r¿   r  rõ   rÀ   )
r&   r  rb   rœ   Úencoder_outputrO  rÄ   rÆ   rË   Ú
next_tokens
   &&&       r   re   Ú"Seq2SeqLMExportableModule.generateù  s:  € Ü�]Š]�_�_ØŸ?™?×1Ñ1ˆLð  ×&Ñ&¨,Ô6Ø#3×#6Ñ#6°|Ó#DÐ ð "×2Ñ2×9Ñ9Ô;Ð<LÓMˆNô !&§¢¨q¨c¨U¼%¿*¹*È\Ô ZÐØ˜CˆMô ˜>¨AÕ-Ö.�à×.Ñ.×5Ñ5Ô7Ø%´u·|²|ÀQÀCÌuÏzÉzÐbnÔ7oó�ô
 #Ÿ\š\¨&°Õ*:ÀÔC×HÑHÓJ�
Ø×$Ñ$ ZÔ0ô %*§L¢L°:°,°ÄuÇzÁzÐZfÔ$gÐ!ð ×!7Ñ!7×!DÑ!DÖDÙñ /ð" !÷A �_�_‹_ús   žEFÆFÆF#	)r   r<  rZ  rY  rV  rõ   rX  )rg   i   rí   rh   ©NNNN)rk   rl   rm   rn   r'   rb  ri  r5   re   rp   rq   r×   rØ   s   @@r   rS  rS  ‘  s%   ù‡ € ÷%ò, ò! ôF÷@!!ò !!r   rS  c                ó€   € V ^8„  d   QhR\         R\        P                  R,          R\        P                  R,          /# )r   r   r/  NÚexample_attention_mask)r   r2   rŒ   )r   s   "r   r   r     s8   € ÷  ñ  Üð ä—|‘| dÕ*ð ô "ŸL™L¨4Õ/ñ r   c                ó  € \        4        \        P                  ! 4       ;_uu_ 4        \        P                  P                  V R
RVRVR\	        V P
                  R7      RR/RR7      pVuuR	R	R	4       #   + '       g   i     R	# ; i)aû  
Export a model with DynamicCache using `torch.export`, ensuring the exported model is compatible with `ExecuTorch`.

Args:
    model (`PreTrainedModel`): The pretrained model to be exported.
    example_input_ids (`Optional[torch.Tensor]`): Example input token id used by `torch.export`.
    example_attention_mask (`Optional[torch.Tensor]`): Example attention mask used by `torch.export`.

Returns:
    Exported program (`torch.export.ExportedProgram`): The exported program generated via `torch.export`.
rJ   r  r  rD  r{   TF)r0   NrZ   )rJ  r2   r4  r5   r   r   )r   r/  ry  rž   s   &&& r   Úexport_with_dynamic_cacher{    so   € ô" *Ô+ä	�Š��Ü Ÿ<™<×.Ñ.ØØàÐ.Ø Ð"8Ø!¤<°u·|±|Ô#DØ˜Tð	ð ð /ó 

Ðð  ÷ 
��‹ús   ¨AA4Á4B	c                 ól  €  \         P                  P                  P                  \        R \
        \        P                   R\        P                   2R R7       \         P                  P                  P                  \        R 4       R#   \         d   p R\        T 4      9  d   h  Rp ? R# Rp ? ii ; i)z6
Utilities for `DynamicCache` <> torch.export support
c                 óf   € \         P                  P                  P                  \	        V 4      4      # r;  )r2   ÚutilsÚ_pytreeÚ_dict_flattenÚ_get_cache_dict©Údynamic_caches   &r   Ú<lambda>Ú7register_dynamic_cache_export_support.<locals>.<lambda>G  s   € ¤%§+¡+×"5Ñ"5×"CÑ"CÄOÐTaÓDbÔ"cr   Ú.c                 óf   € \         P                  P                  P                  \	        V 4      4      # r;  )r2   r~  r  Ú_dict_flatten_with_keysr�  r‚  s   &r   r„  r…  J  s!   € ´u·{±{×7JÑ7J×7bÑ7bÜ Ó.ô8r   )Úserialized_type_nameÚflatten_with_keys_fnc                 óh   € \         P                  P                  P                  \	        V 4      V4      # r;  )r2   Úfxr  Ú_dict_flatten_specr�  )r(  Úspecs   &&r   r„  r…  Q  s"   € ¤§¡× 0Ñ 0× CÑ CÄOÐTYÓDZÐ\`Ô ar   z!already registered as pytree nodeN)r2   r~  r  Úregister_pytree_noder   Ú_unflatten_dynamic_cacherl   rk   rŒ  Úregister_pytree_flatten_specr�   r¤   )Úes    r   rJ  rJ  ?  s”   € ð
Ü�‰×Ñ×0Ñ0ÜÙcÜ$Ü$0×$;Ñ$;Ð#<¸A¼l×>SÑ>SÐ=TÐ!Uñ"ð 	1ô 	
ô 	�‰×Ñ×5Ñ5ÜÙaö	
øô
 ô Ø.´c¸!³fÔ<Øõ =ûðús   ‚BB ÂB3ÂB.Â.B3c                ó$   € V ^8„  d   QhR\         /# )r   r(  )r   )r   s   "r   r   r   Y  s   € ÷ ñ œ<ñ r   c                óä  € \         ;QJ d&    R V P                   4       F  '       g   K   RM	  RM! R V P                   4       4      '       d   \        R4      h\        '       g   \        P
                  ! R4       RV P                   Uu. uF  qP                  f   K  VP                  NK   	  upRV P                   Uu. uF  qP                  f   K  VP                  NK   	  up/# u upi u upi )z9Convert cache to dictionary format for pytree operations.c              3   óX   "  € T F   p\        V\        \        34      '       * x € K"  	  R # 5ir;  )rý   r   r   )Ú.0rå   s   & r   Ú	<genexpr>Ú"_get_cache_dict.<locals>.<genexpr>[  s&   é € Ð
fÑYeÐPUŒz˜%¤,Ô0IÐ!JÓK×KÑKÓYeùs   ‚(*TFzFThis pytree flattening function should only be applied to DynamicCachez[DynamicCache + torch.export is tested on torch 2.6.0+ and may not work on earlier versions.r  Úvalue_cache)Úanyrü   ÚRuntimeErrorr   r„   r™   r   r  )r(  rå   s   & r   r�  r�  Y  s¦   € ç
ƒsÑ
fÐY^×YeÒYeÓ
f‡s‡s‚sÑ
fÐY^×YeÒYeÓ
f×fÒfÜÐcÓdÐdç-Ó-Ü�ŠÐuÔvð 	¨e¯lªlÓU©l U¿j¹j”j�e—j”j©lÑUØ°%·,²,Ó[±,¨Ç,Á,œ˜Ÿœ±,Ñ[ðð ùÚUùÚ[s   ÂC(ÂC(Ã C-
ÃC-
c                ó`   € V ^8„  d   QhR\         P                  P                  P                  /# )r   Úcontext)r2   r~  r  ÚContext)r   s   "r   r   r   g  s#   € ÷ 
ñ 
¬e¯k©k×.AÑ.A×.IÑ.Iñ 
r   c                 óœ  € \         P                  P                  P                  W4      p\	        4       pVP                  R . 4      pVP                  R. 4      p\        \        \        V4      \        V4      4      4       FI  pV\        V4      8  d	   WF,          MRpV\        V4      8  d	   WV,          MRpVP                  WxV4       KK  	  V# )r  r™  N)
r2   r~  r  Ú_dict_unflattenr   rù   r´   rI   r  Úupdate)	r  r�  Ú
dictionaryr(  Úkey_listÚ
value_listÚidxÚkeyÚvalues	   &&       r   r�  r�  g  sž   € Ü—‘×$Ñ$×4Ñ4°VÓE€JÜ‹N€Eà�~‰~˜k¨2Ó.€HØ—‘ ¨rÓ2€JÜ”Sœ˜X›¬¨J«Ó8Ö9ˆØ"¤S¨£]Ô2ˆhŽm¸ˆØ#&¬¨Z«Ô#8�
–¸dˆØ�‰�S Ö%ñ :ð €Lr   rw  )NN) r„   r2   Úcache_utilsr   r   r   r   r   r   r	   Úgeneration.configuration_utilsr
   Úmodeling_utilsr   Úpytorch_utilsr   r   r   ÚnnÚModulerL   rç   r†   rƒ   r7  r9  rB  rS  r{  rJ  r�  r�  rZ   r   r   Ú<module>r®     sá   ðó ã ÷÷ ñ õ >Ý ,÷÷Uñ UôpAL¨E¯H©H¯O©Oô ALõHô,@P¨5¯8©8¯?©?ô @PôFl¨5¯8©8¯?©?ô l÷^? ôDC u§x¡x§¡ô Cô8°e·h±h·o±oô 8ôvI! §¡§¡ô I!÷X òDõ4÷
r   