
    ^jV)                     8   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j4                  e      Zi Zeeee eee e	jB                     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	jB                     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,y)#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y)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                 8    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     f/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/fusion_mapping.pyget_empty_logzModuleFusionSpec.get_empty_log6   s"    T
 3 344OPZ|\\    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] ] ]" "t ""T"))_ "bii ""&8 "T/=R "r   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )_FusedPatchEmbeddingMixinc                    t        |   |i | | j                  j                  t	        j
                  | j                  j                        z  | _        t        j                  | j                  | j                  j                  | j                  j                  d u| j                  j                  j                  | j                  j                  j                        | _        | `y )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    $)&) II11DIIdii>S>S4TT99II""t+99##**))""((
 Ir   hidden_statesr   c                     | j                   j                  j                  }|j                  d| j                        }| j                  |j                  |            }|j                  d| j                        S )N)r:   )rF   rE   r:   viewrB   to	embed_dim)r   rJ   target_dtypes      r   forwardz!_FusedPatchEmbeddingMixin.forwardW   sf    ''..44%**2t/@/@A(()9)9)9)MN!!"dnn55r   )r   r,   r-   r<   torchTensorrQ   __classcell__)rI   s   @r   r6   r6   G   s#    6U\\ 6ell 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y)PatchEmbeddingsFusionSpeczJFuse compatible Conv3d patch embeddings into flattened Linear projections.)z(^|\.)patch_embed$r    r   c                     t        t        |dd       x}t        j                        sy|j                  |j
                  k(  xr1 |j                  dk(  xr  |j                  dk(  xr |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 KK4+++ !	)!*! q 		
r   r&   c                 n    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   sB    5!6!6 78;TVb:cegh	#()B)B(C!D	r   r)   r   c                     t        |d|      }|j                  }t        |t              r||f}|j                  gt        |      }|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#&$j1J$88M5;L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6

 

t 

T"))_ bii 

&8 
T/=R 
r   rV   clsztype[PreTrainedModel]r)   r   fusion_namespecr   c                 <   t         j                  |i       }| |v r||    S t        j                  d      5   | |      }ddd       t	               }i }|j
                  r.t        j                  dj                  |j
                              nd}j                         D ]j  \  }	}
t        |
      }||v r||j                  |	      *|j                  |
      s<|j                  |       |j                  |      ||j                  <   l ||| <   |S # 1 sw Y   xY w)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 5LM>B>Z>Z

388D889:`d   %224 
OV&\
% ,1F1M1Mk1Z1bv&$-1-B-B:-Nj))*
O E#J+ s   	DDc           
      z   t        | |||      }|s/t        j                  |j                  | j                               yt        |d       t        | d      rt        | j                  d      st        d| j                   d      | j                  j                  }|j                  |      }t        |      }|l|D ci c]  }t        |j                        | }	}|D ]?  }
t        |
j                        }|	j                  |      }|,t        d	| d
| d| d       ||z   }t        ||d       yc c}w )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 typez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existing_converter_sources	converterrd   existing_converters                r   _register_module_fusionr      sO    0V[_`OD&&s||45?d;3'ws7G7G/V6#,,/QRSS!!,,J%%f-J;JG& at%tT\eH,D,D&Ex&O%t"%t# 	I#I$=$=>O!;!?!?!P!- k]*::, G++:*;1> 		 ):5
*:zTR &us   D8patch_embeddings_FUSION_REGISTRYfusion_configc                     g }| j                         D ]T  \  }}|t        vrt        d|       |du r!|durt        |t              st        d| d      |j                  |       V |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':':'< 	,#^..4[MBCCU"%j.Q,[M9mn  	{+	, r   c                 T    |syt        |      D ]  }t        | ||t        |           y)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      s4     ,]; YV[:J;:WX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      s  
  	 # %   i ` ` 3  5/ 
		H	%MO c4d3RYY3G.H(H#IIJ O" "66 6.-
 0 -
`-	 -- - 	-
 
#tBII
-`*S	 *S*<*SKN*SVf*S	*SZ 2DE^E`0a $s,,- adWS#X=N6N1N)O TXY\T] $ jnY	 Y9@dWUXZ]U]M^F^A^9_bf9fY	Yr   