Ë
    ÜÓ^j€1  ã                  óN  — d Z ddlmZ ddl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 erdd
lmZ ddlmZ i Ze ed¬«       G d„ d«      «       «       Z G d„ d«      Z ed«      Z	 d	 	 	 	 	 	 	 	 	 dd„Z	 	 	 	 	 	 	 	 dd„Zddd„Z ej4                  «       Zd d„Zdddœd„Zy)!z°
Contains the logic for automatic additional output capture with our forward decorators.
This mostly describe the hooks used and the logic to make capture thread/context safe.
é    )ÚannotationsN)Ú
ContextVar)Ú	dataclass©Úwraps)ÚTYPE_CHECKINGé   )Úis_torchdynamo_compilingÚrequires)Únné   ©ÚPreTrainedModel)Útorch)Úbackendsc                  óT   — e Zd ZU dZded<   dZded<   dZded	<   dZded
<   dZded<   y)ÚOutputRecordera’  
    Configuration for recording outputs from a model via hooks.

    Attributes:
        target_class (Type): The class (e.g., nn.Module) to which the hook will be attached.
        index (Optional[int]): If the output is a tuple/list, optionally record only at a specific index.
        layer_name (Optional[str]): Name of the submodule to target (if needed), e.g., "transformer.layer.3.attn".
        class_name (Optional[str]): Name of the class to which the hook will be attached. Could be the suffix of class name in some cases.
        capture_initial_hidden_state  (bool): Whether to prepend the first module's input as the initial hidden state.
    ztype[nn.Module]Útarget_classr   ÚintÚindexNú
str | NoneÚ
layer_nameÚ
class_nameTÚboolÚcapture_initial_hidden_state)	Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__r   r   r   r   © ó    ún/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/utils/output_capturing.pyr   r   '   s7   … ñ	ð "Ó!Ø€Eˆ3ƒNØ!€J�
Ó!Ø!€J�
Ó!Ø)-Ð  $Ô-r"   r   c                  ó(   — e Zd ZdZd„ Zd„ Zd„ Zd„ Zy)ÚCompileableContextVara¡  
    Convenience wrapper around a ContextVar for usage with `torch.compile`.
    This behaves exactly as a `ContextVar`, except when compilation is triggered in which case it behaves as a simple
    global variable. This is useful as `torch.compile` cannot trace the `get` method of `ContextVar`. This however means
    that the access to the underlying variable is not thread-safe when compilation is triggered.
    c                óD   — t        |d ¬«      | _        d | _        d| _        y )N)ÚdefaultF)r   Úcontext_varÚ
global_varÚ	compiling)ÚselfÚnames     r#   Ú__init__zCompileableContextVar.__init__D   s   € Ü% d°DÔ9ˆÔØˆŒØˆ�r"   c                óf   — | j                   r| j                  S | j                  j                  «       S ©N)r*   r)   r(   Úget)r+   s    r#   r0   zCompileableContextVar.getI   s(   € à�>Š>Ø—?‘?Ð"à×#Ñ#×'Ñ'Ó)Ð)r"   c                ój   — t        «       r|| _        d| _        y | j                  j	                  |«      S )NT)r
   r)   r*   r(   Úset)r+   Úvalues     r#   r2   zCompileableContextVar.setP   s0   € Ü#Ô%Ø#ˆDŒOØ!ˆDŒNØà×#Ñ#×'Ñ'¨Ó.Ð.r"   c                ót   — | j                   s|€d | _        d| _         y | j                  j                  |«       y )NF)r*   r)   r(   Úreset)r+   Útokens     r#   r5   zCompileableContextVar.resetX   s/   € Ø�>Š>˜U˜]Ø"ˆDŒOØ"ˆD�Nà×Ñ×"Ñ" 5Õ)r"   N)r   r   r   r   r-   r0   r2   r5   r!   r"   r#   r%   r%   <   s   „ ñòò
*ò/ó*r"   r%   Úoutput_collectorTc                ó:   ‡‡‡— ˆˆˆfd„}| j                  |«       y)zaInstall the forward hook needed to capture the output described by `key` and `index` in `module`.c                ó:  •— t         j                  «       }|�‰|j                  «       vry ‰r-‰dk(  r(t        |‰   «      dk(  r|‰   j	                  |d   «       t        |t        «      s|‰   j	                  |«       y |‰   �|‰   j	                  |‰   «       y y )NÚhidden_statesr   )Ú_active_collectorr0   ÚkeysÚlenÚappendÚ
isinstanceÚtuple)ÚmoduleÚargsÚoutputÚcollected_outputsr   r   Úkeys       €€€r#   Úoutput_capturing_hookz;install_output_capuring_hook.<locals>.output_capturing_hooki   s¤   ø€ ä-×1Ñ1Ó3ÐàÐ$¨Ð3D×3IÑ3IÓ3KÑ(KØá'¨C°?Ò,BÄsÐK\Ð]`ÑKaÓGbÐfgÒGgØ˜cÑ"×)Ñ)¨$¨q©'Ô2Ü˜&¤%Ô(Ø˜cÑ"×)Ñ)¨&Õ1Ø�E‰]Ð&Ø˜cÑ"×)Ñ)¨&°©-Õ8ð 'r"   N)Úregister_forward_hook)rA   rE   r   r   rF   s    ``` r#   Úinstall_output_capuring_hookrH   d   s   ú€ ö
9ð × Ñ Ð!6Õ7r"   c                ó  — ddl m} | j                  «       D ]6  \  }}t        ||«      st	        ||› d|› �|«       Œ%t        ||› d|› �¬«       Œ8 |D ]¶  \  }}|j                  duxr t        | |j                  «      }|j                  duxr |j                  |j                  «      }	|s|	sŒ\|j                  �-|j                  j                  d«      }
d|
z   dz   }
|
|dz   v }|sŒ•t        | ||j                  |j                  «       Œ¸ y)aÖ  
    Recursively install all output capturing hooks on all submodules of `parent_module`.
    Note that we need to use this recursive approach instead of simply iterating over all modules, because we want
    to respect the `capture_tasks` of all individual submodels (`PreTrainedModel` instances) in the graph. That is, once
    we reach a submodel in the graph, its children should use this submodel's `capture_tasks`, but other parts of the graph
    should not.
    r   r   ú.)ÚprefixN)Úmodeling_utilsr   Únamed_childrenr?   Úrecursively_install_hooksÚ"install_all_output_capturing_hooksr   r   Úendswithr   ÚstriprH   r   r   )Úparent_moduleÚmodule_nameÚcapture_tasksr   r,   rA   rE   ÚspecsÚmatch_target_classÚmatch_class_nameÚtarget_layer_nameÚmatchess               r#   rN   rN   z   s)  € õ 1ð &×4Ñ4Ó6ò W‰ˆˆfä˜& /Ô2Ü% f°°¸Q¸t¸fÐ.EÀ}ÕUô /¨vÀÀÈQÈtÈfÐ>UÖVðWð $ò n‰
ˆˆUà"×/Ñ/°tÐ;ÒmÄ
È=ÐZ_×ZlÑZlÓ@mÐà ×+Ñ+°4Ð7Òb¸K×<PÑ<PÐQV×QaÑQaÓ<bÐáÒ!1à×ÑÐ+à$)×$4Ñ$4×$:Ñ$:¸3Ó$?Ð!Ø$'Ð*;Ñ$;¸cÑ$AÐ!à+¨{¸SÑ/@Ð@�ÙØä(¨¸¸U¿[¹[È%×JlÑJlÕmñ#nr"   c                óÆ  — t         j                  t        | j                  «      «      xs i }g }|j	                  «       D ]€  \  }}t        |t        «      s|g}|D ]c  }t        |t        «      s>d|v rdnd}t        |t        «      sdn|}t        |t        «      s|nd}	t        |	||¬«      }|j                  ||f«       Œe Œ‚ |�|nd}t        | ||«       t        | dd«       y)	zÙ
    Install the output recording hooks on all the modules in `model`. This will take care of correctly dispatching
    the `_can_record_outputs` property of each individual submodels in case of composite models.
    r:   r   r	   N)r   r   r   Ú Ú!_output_capturing_hooks_installedT)Ú_CAN_RECORD_REGISTRYr0   ÚstrÚ	__class__Úitemsr?   Úlistr   r>   rN   Úsetattr)
ÚmodelrK   Úcapture_flagsrT   rE   Úlayer_specsrU   r   r   r   s
             r#   rO   rO   ¤   sä   € ô )×,Ñ,¬S°·±Ó-AÓBÒHÀb€Mà€MØ)×/Ñ/Ó1ò 	/Ñˆˆ[Ü˜+¤tÔ,Ø&˜-ˆKØ ò 	/ˆEÜ˜e¤^Ô4Ø,°Ñ3™¸�Ü)3°E¼3Ô)?™TÀU�
Ü,6°u¼cÔ,B™uÈ�Ü&°LÈÐZdÔe�Ø× Ñ  # u Õ.ñ	/ð	/ð Ð)‰V¨r€FÜ˜e V¨]Ô;äˆEÐ6¸Õ=r"   c                óš   — t        | dd«      ryt        5  t        | dd«      r
	 ddd«       yt        | «       ddd«       y# 1 sw Y   yxY w)zà
    Check if the model already has output capturing hooks installed, and install them if it is not already the
    case.
    Note that this is thread-safe, in case 2 (or more) threads want to install them concurrently.
    r\   FN)ÚgetattrÚ_hook_installation_lockrO   )rc   s    r#   Úmaybe_install_capturing_hooksri   Ä   sR   € ô ˆuÐ9¸5ÔAØä	 ñ 2ô �5Ð=¸uÔEØ÷	2ð 2ô 	+¨5Ô1÷2÷ 2ñ 2ús   •A­AÁA
)Útie_last_hidden_statesc               ó&   ‡— ˆfd„}| � || «      S |S )aÿ  
    Decorator to intercept specific layer outputs through hooks. The hooks are installed only once and lazily,
    the first time output capture is requested with the `output_xxx` kwargs/config.
    The implementation is fully context/thread safe, except when using `torch.compile`, as dynamo is unable to trace
    through `ContextVar` methods.

    Args:
        tie_last_hidden_states (`bool`, *optional*, defaults to `True`):
            Whether to overwrite `out.hidden_states[-1]` with the `out.last_hidden_state`.
            This is true for all language models and should be toggled off only if
            `out.hidden_states[-1]` has to be the hidden state before last layer norm, which
            is needed for some vision models (e.g. CLIP, SigLIP)
    c                ó2   •‡ — t        ‰ «      ˆ ˆfd„«       }|S )Nc                óv  •— |j                  dt        | j                  dd«      «      }t        j	                  t        | j                  «      «      xs i }|D �ci c]3  }d|› �|j	                  d|› �t        | j                  d|› �d«      «      “Œ5 }}d|v r*|j	                  dt        | j                  dd«      «      |d<   d|v r*|j	                  dt        | j                  dd«      «      |d	<   |j                  «       D ��ci c]  \  }}|sŒ	|j                  dd
«      g “Œ }}}t        |«      dkD  rt        | «       t        j                  |«      }		  ‰| g|¢­i |¤Ž}
t        j                  |	«       |D ]†  }|dk(  rn‰snkt        |
d«      r*||   d d ||<   ||   j                  |
j                   «       n5t        |
d«      r)||   d d ||<   ||   j                  |
j"                  «       t%        ||   «      |
|<   Œˆ |du r|
j'                  «       }
|
S c c}w c c}}w # t        j                  |	«       w xY w)NÚreturn_dictTÚoutput_FÚcross_attentionsÚoutput_attentionsÚoutput_cross_attentionsÚmask_decoder_attentionsÚoutput_mask_decoder_attentionsr[   r   r:   Úvision_hidden_stateséÿÿÿÿÚlast_hidden_state)Úpoprg   Úconfigr]   r0   r^   r_   r`   Úreplacer=   ri   r;   r2   r5   Úhasattrr>   ru   rw   r@   Úto_tuple)r+   rB   Úkwargsrn   Úcapturable_flagsÚkÚrecordable_keysÚvrD   Úoutput_tokenÚoutputsrE   Úfuncrj   s               €€r#   Úwrapperz4capture_outputs.<locals>.wrapped_fn.<locals>.wrapperç   sj  ø€ ð !Ÿ*™* ]´G¸D¿K¹KÈÐX\Ó4]Ó^ˆKô  4×7Ñ7¼¸D¿N¹NÓ8KÓLÒRÐPRÐð *öàð ˜!˜�˜vŸz™z¨G°A°3¨-¼ÀÇÁÐPWÐXYÐWZÈmÐ]bÓ9cÓdÑdðˆOð ð
 "Ð%5Ñ5Ø=C¿Z¹ZØ'¬°·±Ð>QÐSXÓ)Yó>�Ð 9Ñ:ð )Ð,<Ñ<ØDJÇJÁJØ'¬°·±Ð>QÐSXÓ)YóE�Ð @ÑAð KZ×J_ÑJ_ÓJa× gÁ$À!ÀQÒef §¡¨9°bÓ!9¸2Ñ!=Ð gÐÑ gäÐ$Ó%¨Ò)Ü-¨dÔ3ä,×0Ñ0Ð1BÓCˆLð6Ù˜tÐ5 dÒ5¨fÑ5�ô "×'Ñ'¨Ô5ð )ò =�Ø˜/Ò)Ù1ØÜ  Ð*@ÔAØ1BÀ3Ñ1GÈÈÐ1LÐ)¨#Ñ.Ø)¨#Ñ.×5Ñ5°g×6RÑ6RÕSÜ  Ð*=Ô>Ø1BÀ3Ñ1GÈÈÐ1LÐ)¨#Ñ.Ø)¨#Ñ.×5Ñ5°g×6OÑ6OÔPä$Ð%6°sÑ%;Ó<�˜’ð=ð ˜eÑ#Ø!×*Ñ*Ó,�àˆNùò]ùó !høô "×'Ñ'¨Õ5ús   Á8HÄ
HÄHÅH! È!H8r   )r„   r…   rj   s   ` €r#   Ú
wrapped_fnz#capture_outputs.<locals>.wrapped_fnæ   s!   ù€ Ü	ˆt‹ô4	ó 
ð4	ðl ˆr"   r!   )r„   rj   r†   s    ` r#   Úcapture_outputsr‡   ×   s"   ø€ ô8ðt ÐÙ˜$ÓÐØÐr"   )T)
rA   ú	nn.ModulerE   r^   r   r   r   r   ÚreturnÚNone)rR   rˆ   rS   r^   rT   z list[tuple[str, OutputRecorder]]r‰   rŠ   r/   )rc   r   rK   r   r‰   rŠ   )rc   r   r‰   rŠ   )r   Ú
__future__r   Ú	threadingÚcontextvarsr   Údataclassesr   Ú	functoolsr   Útypingr   Úimport_utilsr
   r   r   r   rL   r   r]   r   r%   r;   rH   rN   rO   ÚLockrh   ri   r‡   r!   r"   r#   ú<module>r“      sû   ðñõ
 #ã Ý "Ý !Ý Ý  ç <ñ Ýå0ð Ð ð Ù	�:Ô÷.ð .ó ó ð.÷&!*ñ !*ñJ *Ð*<Ó=Ð ð SWð8Øð8Øð8Ø(+ð8ØKOð8à	ó8ð,'nØð'nØ+.ð'nØ?_ð'nà	ó'nôT>ð: )˜)Ÿ.™.Ó*Ð ó2ð&K¸õ Kr"   