
    #jV)                        U d Z ddlZddlZddlmZ ddlmZmZ ddlZddlm	Z	 ddl
mZmZ ddlmZmZmZmZ dd	lmZ dd
lmZ erddlmZ ddlmZ  ej        e          Zi Zeeee eee e	j!                 f         f         f         e"d<    G d d          Z# G d d          Z$ G d de#          Z%dddddede#deee e	j!                 f         f
dZ&dddddede#ddf
dZ'd e%            iZ(eee#f         e"d<   deee)eeef         z  f         de*e         fd Z+	 d"dddeee)eeef         z  f         dz  ddfd!Z,dS )#zrFusion registration helpers.

See `docs/source/en/fusion_mapping.md` for the design overview and extension guide.
    N)Mapping)TYPE_CHECKINGAny)nn   )!get_checkpoint_conversion_mapping&register_checkpoint_conversion_mapping)Conv3dToLinearWeightConverterWeightRenamingWeightTransform)register_patch_mapping)logging)PretrainedConfig)PreTrainedModel_FUSION_DISCOVERY_CACHEc                       e Zd ZU dZdZeedf         ed<   dedefdZde	j
        defd	Zd
ee	j
                 dee	j
                 fdZdddee         fdZdS )ModuleFusionSpeczBase recipe for a fusion family.

    A fusion spec decides which modules are eligible for a fusion, how to build
    the runtime replacement class, and which weight transforms are needed to map
    checkpoints between the original and fused layouts.
     .target_modules_patterns
model_namereturnc                 6    dt          |           j         d| S )zDReturn the log message emitted when no compatible modules are found.zNo compatible z classes found to fuse for )type__name__)selfr   s     e/lsinfo/ai/hellotax_ai/base_platform/venv/lib/python3.11/site-packages/transformers/fusion_mapping.pyget_empty_logzModuleFusionSpec.get_empty_log6   s"    \T

 3\\PZ\\\    modulec                     t           )z>Return whether `module` is compatible with this fusion family.NotImplementedError)r   r    s     r   
is_fusablezModuleFusionSpec.is_fusable:       !!r   original_clsc                     t           )zBBuild the runtime replacement class for a compatible module class.r"   )r   r&   s     r   make_fused_classz!ModuleFusionSpec.make_fused_class>   r%   r   configr   c                     t           )zMBuild the weight transforms needed to load and save the fused runtime layout.r"   )r   r)   s     r   make_transformsz ModuleFusionSpec.make_transformsB   r%   r   N)r   
__module____qualname____doc__r   tuplestr__annotations__r   r   Moduleboolr$   r   r(   listr   r+   r   r   r   r   r   ,   s           02U38_111] ] ] ] ] ]" "t " " " ""T")_ "bi " " " ""&8 "T/=R " " " " " "r   r   c                   B     e Zd Z fdZdej        dej        fdZ xZS )_FusedPatchEmbeddingMixinc                 L    t                      j        |i | | j        j        t	          j        | j        j                  z  | _        t          j	        | j        | j        j
        | j        j        d u| j        j        j        | j        j        j                  | _        | `d S )N)biasdevicedtype)super__init__projin_channelsmathprodkernel_sizepatch_volumer   Linearout_channelsr8   weightr9   r:   linear_proj)r   argskwargs	__class__s      r   r<   z"_FusedPatchEmbeddingMixin.__init__H   s    $)&))) I1DIdi>S4T4TT9I"t+9#*)"(
 
 
 IIIr   hidden_statesr   c                     | j         j        j        }|                    d| j                  }|                      |                    |                    }|                    d| j                  S )N)r:   )rF   rE   r:   viewrB   to	embed_dim)r   rJ   target_dtypes      r   forwardz!_FusedPatchEmbeddingMixin.forwardW   sd    '.4%**2t/@AA(()9)9)9)M)MNN!!"dn555r   )r   r,   r-   r<   torchTensorrQ   __classcell__)rI   s   @r   r6   r6   G   s^            6U\ 6el 6 6 6 6 6 6 6 6r   r6   c                       e Zd ZdZdZdej        defdZde	ej                 de	ej                 fdZ
dd	dee         fd
ZdS )PatchEmbeddingsFusionSpeczJFuse compatible Conv3d patch embeddings into flattened Linear projections.)z(^|\.)patch_embed$r    r   c                     t          t          |dd           x}t          j                  sdS |j        |j        k    o |j        dk    o|j        dk    o
|j        dk    S )Nr=   F)r   r   r   )r   r   r   r   )	
isinstancegetattrr   Conv3dstriderA   paddingdilationgroups)r   r    r=   s      r   r$   z$PatchEmbeddingsFusionSpec.is_fusablec   so    '&&$"?"??$KK 	5 K4++ !	)!*! q 		
r   r&   c                 d    t          d|j         t          |fi           }d|j         |_        |S )NFused)r   r   r6   r-   )r   r&   	fused_clss      r   r(   z*PatchEmbeddingsFusionSpec.make_fused_classo   s@    8!688;TVb:ceghh	!D)B!D!D	r   r)   r   c                    t          |d|          }|j        }t          |t                    r||f}|j        gt          |          R }|j        }t          ddt          ||          g          t          dd          gS )	Nvision_configzpatch_embed\.proj\.weight$z!patch_embed\.linear_proj\.weight$)r>   rA   )source_patternstarget_patterns
operationszpatch_embed\.proj\.bias$zpatch_embed\.linear_proj\.bias$)rd   re   )
rY   
patch_sizerX   inttemporal_patch_sizer/   r>   r   r
   r   )r   r)   rc   rg   rA   r>   s         r   r+   z)PatchEmbeddingsFusionSpec.make_transformst   s    @@"-
j#&& 	2$j1J$8M5;L;LMM#/  = D"$/$/  	 	 	  ; B  
 	
r   N)r   r,   r-   r.   r   r   r2   r3   r$   r   r(   r4   r   r+   r   r   r   rV   rV   ^   s        TT6

 

t 

 

 

 

T")_ bi    

&8 
T/=R 
 
 
 
 
 
r   rV   clsztype[PreTrainedModel]r)   r   fusion_namespecr   c                 r   t                               |i           }| |v r||          S t          j        d          5   | |          }ddd           n# 1 swxY w Y   t	                      }i }|j        r,t          j        d                    |j                            nd}|	                                D ]y\  }	}
t          |
          }||v r||                    |	          1|                    |
          sG|                    |           |                    |          ||j        <   z||| <   |S )ar  Discover compatible module classes for one fusion family on a meta-initialized model.

    This function:
    - instantiates `cls(config)` on the meta device
    - scans `named_modules()` for candidate modules
    - optionally pre-filters them with `target_modules_patterns`
    - uses `is_fusable(...)` as the final structural check
    - builds the class-level patch mapping used by monkey patching

    Results are cached per `(fusion_name, cls)` to avoid repeated meta-initialization.
    This matches the current class-level fusion behavior, where one compatible
    module class maps to one fused replacement class.
    metaN|)r   
setdefaultrR   r9   setr   recompilejoinnamed_modulesr   searchr$   addr(   r   )rj   r)   rk   rl   cachemodelseen_classespatch_mappingtarget_module_patternmodule_namer    
module_clss               r   _discover_fusable_modulesr      s   ( $..{B??E
e||Sz	f		  F               55LM>B>Zd
388D899:::`d   %2244 
O 
OV&\\
%% ,1F1M1Mk1Z1Z1bv&& 	$$$-1-B-B:-N-Nj)**E#Js   AAAc           
      p   t          | |||          }|s4t                              |                    | j                             dS t          |d           t          | d          rt          | j        d          st          d| j         d          | j        j	        }|
                    |          }t          |          }|Zd	 |D             }|D ]F}	t          |	j                  }
|                    |
          }|t          d
| d| d|
 d          G||z   }t          ||d           dS )a  Register one fusion family for `cls`.

    This function updates the two global registries used by fused loading:
    - the monkey-patching registry, so compatible module classes are replaced before initialization
    - the checkpoint conversion mapping, so fused runtime modules still load from the original checkpoint layout

    Notes:
    - conflicting checkpoint transforms fail fast
    )rk   rl   NT)	overwriteconfig_class
model_typezModel z" has no config class or model typec                 8    i | ]}t          |j                  |S r   )r/   rd   ).0existings     r   
<dictcomp>z+_register_module_fusion.<locals>.<dictcomp>   s&    %t%t%tT\eH,D&E&Ex%t%t%tr   zFusion z for model type zC conflicts with an existing conversion mapping for source patterns .)r   loggerinfor   r   r   hasattrr   
ValueErrorr   r+   r   r/   rd   getr	   )rj   r)   rk   rl   fusable_classesr   
convertersexisting_convertersexisting_converter_sources	converterrd   existing_converters               r   _register_module_fusionr      s    0V[_```O D&&s|44555?d;;;;3'' Tws7G/V/V TR#,RRRSSS!,J%%f--J;JGG& &u%t`s%t%t%t"# 	 	I#I$=>>O!;!?!?!P!P!- >k > >: > >+:> > >   . ):5
*:zTRRRRRRr   patch_embeddings_FUSION_REGISTRYfusion_configc                     g }|                                  D ]f\  }}|t          vrt          d|           |du r%|dur(t          |t                    st          d| d          |                    |           g|S )zQValidate `fusion_config` and return enabled fusion names in user-specified order.zUnknown fusion type: FTzInvalid fusion config for z4: expected `True`, `False`, or a mapping of options.)itemsr   r   rX   r   append)r   enabled_fusionsrk   fusion_optionss       r   _iter_enabled_fusionsr      s     O'4':':'<'< 	, 	,#^...B[BBCCCU""%%j.Q.Q%n[nnn   	{++++r   c                 l    |sdS t          |          D ]}t          | ||t          |                     dS )a  Register requested runtime fusions for `cls`.

    This function:
    - validates `fusion_config` against `_FUSION_REGISTRY`
    - resolves the enabled fusion families in user order
    - registers monkey patches and checkpoint transforms before model instantiation
    N)r   r   r   )rj   r)   r   rk   s       r   register_fusion_patchesr      sS      ,];; Y YV[:J;:WXXXXY Yr   )N)-r.   r?   rr   collections.abcr   typingr   r   rR   r   conversion_mappingr   r	   core_model_loadingr
   r   r   r   monkey_patchingr   utilsr   configuration_utilsr   modeling_utilsr   
get_loggerr   r   r   dictr0   r   r2   r1   r   r6   rV   r   r   r   r3   r4   r   r   r   r   r   <module>r      s5    
  				 # # # # # # % % % % % % % %        i i i i i i i i ` ` ` ` ` ` ` ` ` ` ` ` 3 3 3 3 3 3        0555555////// 
	H	%	%MO c4d3RY3G.H(H#IIJ O O O" " " " " " " "66 6 6 6 6 6 6 6.-
 -
 -
 -
 -
 0 -
 -
 -
`-	 -- - 	-
 
#tBI
- - - -`*S	 *S*<*SKN*SVf*S	*S *S *S *SZ 2DE^E^E`E`0a $s,,- a a adWS#X=N6N1N)O TXY\T]    $ jnY Y	 Y9@dWUXZ]U]M^F^A^9_bf9fY	Y Y Y Y Y Yr   