ó
    pyüi% ã                  óŽ  • % S SK Jr  S SKrS SKrS SKrS SKrS SKJr  SSKJ	r	  SSK
JrJr  SSKJr  SSKJr  \" 5       (       a*  S SKrS SKJr  S S	KJr  \R                  R+                  5       r\R.                  " \5      r SF   SGS
 jjrSHS jrSISJS jjr\" 5       (       a|  \R:                  \R<                  \R>                  \R@                  \RB                  \RD                  \RF                  \RH                  \RJ                  \RL                  \RN                  S.r(SKS jr)S r* SL         SMS jjr+SNSOS jjr,S r- " S S\R\                  R^                  5      r0 " S S\R\                  R^                  5      r1 " S S\R\                  R^                  5      r2 " S S\R\                  R^                  5      r3 " S S\R\                  R^                  5      r4S r5S r6S r7S  r8S! r9   SF   SPS" jjr: " S# S$5      r; " S% S&\;5      r< " S' S(\;5      r= " S) S*\;5      r> " S+ S,\;5      r? " S- S.\<5      r@ " S/ S0\?5      rA " S1 S2\;5      rB " S3 S4\;5      rC " S5 S6\;5      rD " S7 S8\;5      rE " S9 S:\;5      rF " S; S<\;5      rG " S= S>\5      rH\H" 5       rIS>\JS?'           SQS@ jrK        SRSA jrLSB rMSC rNSSSD jrOSE rPg)Té    )ÚannotationsN)Úreduceé   )ÚDistributedConfig)Úis_torch_greater_or_equalÚlogging)ÚGeneralInterface)Úis_torch_available)Únnc                ó˜  • Ub  U c  [        S5      eU b  Ub  [        S5      eUGc  [        S5      (       d  [        S5      e[        R                  R                  5       R                  nUS:X  a  [        S5      e[        [        U5      n[        R                  R                  5       (       d³   [        [        R                  S   5      n[        [        R                  S	   5      n[        [        R                  S
   5      nSSSSSS.n	U	R                  U5      n
[        R                  R                  X¦US9  [        [        U5      nUS:w  a  UR!                  U5        US:w  aT  UR!                  [        [        R                  S	   5      5        UR%                  5       n[        R&                  " XL5      nUnO![        R&                  " U5      nU=(       d    0 nUb  UO[        R                  R)                  5       n[        R                  R+                  UR                  U45      nOUR,                  S:”  a   SUR.                  ;  a  [        S5      eUS   nUR1                  5       n[        R&                  " UR2                   S[        [        R                  S	   5       35      nX2U4$ ! ["         a  n[        S5      UeSnAff = f)z 
Sets up the device mesh and initialized the backend for tensor parallelism.
This function is called when the model is loaded and the TP plan is set to 'auto'.
Nz-tp_plan has to be set when tp_size is passed.zY`tp_plan` and `device_map` are mutually exclusive. Choose either one for parallelization.z2.5z3Tensor parallel is only supported for `torch>=2.5`.Úmpsz3Tensor parallelism is not supported on MPS devices.ÚRANKÚ
LOCAL_RANKÚ
WORLD_SIZEÚncclÚglooÚxcclÚhcclÚneuron)ÚcudaÚcpuÚxpuÚhpur   )ÚbackendÚrankÚ
world_sizer   z†We tried to initialize torch.distributed for you, but it failed. Make sure you init torch distributed in your script to use `tp_plan`.é   ÚtpzsWhen using `tp_plan` and n-d `device_mesh`, it must contain a 'tp' dimension. Please provide a valid `device_mesh`.Ú:)Ú
ValueErrorr   ÚOSErrorÚtorchÚ_CÚ_get_acceleratorÚtypeÚRuntimeErrorÚgetattrÚdistributedÚis_initializedÚintÚosÚenvironÚgetÚinit_process_groupÚ
set_deviceÚ	ExceptionÚcurrent_deviceÚdeviceÚget_world_sizeÚinit_device_meshÚndimÚmesh_dim_namesÚsizeÚdevice_type)Útp_planÚtp_sizeÚdevice_meshÚ
device_mapr8   r1   r   Ú
local_rankr   Úbackend_mapr   ÚeÚindexÚ	tp_devices                 Úf/home/mande/repo/quber/.venv/lib/python3.13/site-packages/transformers/integrations/tensor_parallel.pyÚinitialize_tensor_parallelismrC   (   s{  € ð Ñ˜w™ÜÐHÓIÐIØÑ˜zÑ5ÜÐtÓuÐuØÒÜ(¨×/Ñ/ÜÐOÓPÐPô —h‘h×/Ñ/Ó1×6Ñ6ˆØ˜%ÓÜÐTÓUÐUÜ ¤¨Ó4ˆÜ× Ñ ×/Ñ/×1Ñ1ðÜœ2Ÿ:™: fÑ-Ó.�Ü ¤§¡¨LÑ!9Ó:�
Ü ¤§¡¨LÑ!9Ó:�
à'-°fÀVÐTZÐfnÑo�Ø%Ÿ/™/¨+Ó6�ä×!Ñ!×4Ñ4¸WÐ\fÐ4ÑgÜ!(¬°Ó!<�Ø %Ó'Ø"×-Ñ-¨jÔ9ð ˜%ÓØ×%Ñ%¤c¬"¯*©*°\Ñ*BÓ&CÔDØ"×1Ñ1Ó3ˆEÜŸš [Ó8ˆIØ"‰JäŸš [Ó1ˆIØ$×*¨ˆJà$Ñ0‘'´e×6GÑ6G×6VÑ6VÓ6XˆÜ×'Ñ'×8Ñ8¸¿¹È'ÈÓT‰à×Ñ˜aÓØ˜;×5Ñ5Ó5Ü ð<óð ð & dÑ+ˆKØ×"Ñ"Ó$ˆÜ—\’\ [×%<Ñ%<Ð$=¸Q¼sÄ2Ç:Á:ÈlÑC[Ó?\Ð>]Ð"^Ó_ˆ
à GÐ+Ð+øô9 ó ÜðWóð ðûðús   Â/B2J. Ê.
K	Ê8KËK	c                ó4   • [         R                  " SS U 5      $ )aS  
Replace the numbers in the `name` by wildcards, only if they are in-between dots (`.`) or if they are between
a dot (`.`) and the end of the string.
This matches how modules are named/numbered when using a nn.ModuleList or nn.Sequential, but will NOT match
numbers in a parameter name itself, e.g. if the param is named `"w1"` or `"w2"`.
z\.\d+(\.|$)c                ó*   • SU R                  S5      -   $ )Nz.*r   ©Úgroup)Úms    rB   Ú<lambda>Ú2replace_layer_number_by_wildcard.<locals>.<lambda>p   s   € ¨D°1·7±7¸1³:Ò,=ó    )ÚreÚsub)Únames    rB   Ú replace_layer_number_by_wildcardrO   i   s   € ô �6Š6�.Ñ"=¸tÓDÐDrK   c                ó‚   • [        U 5      nX1;   a  X   $ U(       a$  SU;   a  UR                  SS5      S   =oA;   a  X   $ g)a‹  
Get the TP style for a parameter from the TP plan.

The TP plan is a dictionary that maps parameter names to TP styles.
The parameter name can be a generic name with wildcards (e.g. "*.weight") or a specific name (e.g. "layer_1.weight").

The `is_weight` is important because for weights, we want to support `.weights` and `.bias` cases seamlessly! but
not parent classes for `post_init` calls
Ú.r   r   N)rO   Úrsplit)Úparameter_namer9   Ú	is_weightÚgeneric_param_nameÚmodule_names        rB   Ú_get_parameter_tp_planrW   s   sU   € ô :¸.ÓIÐØÓ$ØÑ*Ð*Þ	�sÐ0Ó0ÐEW×E^ÑE^Ð_bÐdeÓEfÐghÑEiÐ6i°kÓ5uØÑ#Ð#ØrK   )ÚBOOLÚU8ÚI8ÚI16ÚF16ÚBF16ÚI32ÚF32ÚF64ÚI64ÚF8_E4M3c                óà   • [        U[        5      (       a9  [        U5      nX-  S:X  d   SU  SU 35       eX-  nU Vs/ s H  oCU-  PM	     sn$ X-  S:X  d
   SU 35       eX-  nU/U-  $ s  snf )a›  
Convert block count or proportions to block sizes.

This function accepts

- The number of blocks (int), in which case the block size is
  total_size//blocks; or
- A list of block sizes (list[int]).

In the second case, if sum(blocks) < total_size, the ratios between
the block sizes will be preserved. For instance, if blocks is
[2, 1, 1] and total_size is 1024, the returned block sizes are
[512, 256, 256].
r   zCannot split z in proportional blocks: zPrepacked is not divisible by )Ú
isinstanceÚlistÚsum)Ú
total_sizeÚblocksÚtotal_blocksÚ	part_sizeÚblockÚsingle_sizes         rB   Ú_blocks_to_block_sizesrm   š   s˜   € ô �&œ$×ÑÜ˜6“{ˆØÑ(¨AÓ-Ðl°¸z¸lÐJcÐdjÐckÐ/lÓlÐ-ØÑ.ˆ	Ù/5Ó6ªv e˜EÔ!©vÑ6Ð6àÑ" aÓ'ÐRÐ+IÈ&ÈÐ)RÓRÐ'Ø Ñ*ˆØˆ}˜vÑ%Ð%ùò	 7s   ¾A+c                ó  • U nUR                   U   nUR                  5       n[        USS9n/ n	Sn
U H*  nX·-  nX<-  nUS-   U-  nU	[        X­-   X®-   5      -  n	X«-  n
M,     UR	                  5       nSnUS:X  d  US:X  a$  US   R                  [        R                  5      nS	nUS:X  a  XYS4   nO:US:X  d  US
:X  a  USS2U	S4   nO#US:X  d  US:X  a  USU	4   nO[        SU S35      eU(       a  U$ UR                  [        U   5      $ )uˆ  
When weights are packed (gate_up_proj), we need to make sure each shard gets its correct share.
So if you have: gate_proj       ( 16, 5120, 8190)
and             up_proj         ( 16, 5120, 8190)
packed as       gate_up_proj    ( 16, 5120, 2 * 8190)
And you shard along the last dimension, you need to interleave the gate and up values:

Now, if we shard along the last dimension across TP_size (Tensor Parallelism size), we must interleave the values from gate and up projections correctly.

Let's take TP_size = 4 for an example:

Packed tensor `gate_up_proj`
---------------------------------------------------------------
[ G0  G1  G2  G3 | G4  G5  G6  G7 | ... | U0  U1  U2  U3 | U4  U5  U6  U7 | ... ]
 â†‘â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â†‘   â†‘â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â†‘        â†‘â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â†‘  â†‘â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â†‘
   Gate Slice 0      Gate Slice 1            Up Slice 0       Up Slice 1

Explanation:
- The first half of the tensor (left of the center) holds the gate_proj values.
- The second half (right of the center) holds the up_proj values.
- For TP=4, we divide each half into 4 slices. In this example, we show two slices for brevity.
- Each shard receives one slice from the gate part and the corresponding slice from the up part.

For instance:
â€¢ Shard 0 gets: [ Gate Slice 0, Up Slice 0 ] = [ G0, G1, G2, G3, U0, U1, U2, U3 ]
â€¢ Shard 1 gets: [ Gate Slice 1, Up Slice 1 ] = [ G4, G5, G6, G7, U4, U5, U6, U7 ]
â€¢ â€¦ and so on.

This ensures that each shard receives an equal portion of both gate and up projections, maintaining consistency across tensor parallelism.
r   )rg   rh   r   r   Frb   ÚF8_E5M2.TéþÿÿÿNéÿÿÿÿzUnsupported dim z", only dim 0, 1 or 2 are supported)
Úshaper7   rm   ÚrangeÚ	get_dtypeÚtor"   Úfloat16r    Ústr_to_dtype)ÚparamÚempty_paramr;   r   ÚdimÚslice_rg   r   Úblock_sizesÚtensors_slicesÚblock_offsetÚ
block_sizeÚshard_block_sizeÚstartÚstopÚslice_dtypeÚcastedÚtensors                     rB   Úget_packed_weightsr†   ´   sG  € ð> €FØ×"Ñ" 3Ñ'€JØ×!Ñ!Ó#€JÜ(°JÀqÑI€Kà€NØ€LÛ!ˆ
Ø%Ñ3ÐØÑ'ˆØ�q‘Ð,Ñ,ˆØœ% Ñ 4°lÑ6IÓJÑJˆØÑ"Šñ "ð ×"Ñ"Ó$€Kð €FØ�iÓ ;°)Ó#;Ø˜‘—‘¤§¡Ó.ˆØˆà
ˆaƒxØ¨Ð+Ñ,‰Ø	�‹�S˜B“YØš˜>¨3Ð.Ñ/‰Ø	�‹�S˜B“YØ˜˜^Ð+Ñ,‰äÐ+¨C¨5Ð0RÐSÓTÐTæØˆà�y‰yœ kÑ2Ó3Ð3rK   c                óÀ  • US:w  a  [        S5      eUS:¼  a  UOXR                  -   nU R                  U   nXS-  nXb-  nU R                  SU nU R                  US-   S n	U R                  " / UQUPUPUPU	Q76 n
[	        U5      n[	        U5      S-   n[        [        U
R                  5      5      nXÜ   XÛ   sXÛ'   XÜ'   U
R                  " U6 nUR                  U 5      nU$ )a?  
Reorders a tensor that was reconstructed from sharded packed weights into its canonical packed format.

For example, if a weight was packed (e.g., gate_proj and up_proj) and then sharded,
DTensor.full_tensor() might produce an interleaved layout like [G0, U0, G1, U1, ...]
along the sharded dimension. This function reorders it to [G0, G1, ..., U0, U1, ...].
This is an inverse operation to get_packed_weights.

Args:
    reconstructed_tensor: The tensor reconstructed from DTensor (e.g., via .full_tensor().contiguous()).
    sharded_dim: The dimension index in the reconstructed_tensor that was originally sharded.
    world_size: The tensor parallel world size.
    num_packed_projs: The number of projections that were packed together (e.g., 2 for gate_up_proj).

Returns:
    The reordered tensor in canonical packed format.
r   z”Num blocks different from 2 is not supported yet. This is most likely a bug in your implementation as we only pack gate and up projections together.r   Nr   )	r    r5   rr   ÚviewÚlenre   rs   ÚpermuteÚ
reshape_as)Úpacked_parameterÚsharded_dimr   Ú
num_blocksÚactual_sharded_dimÚtotal_size_on_sharded_dimÚoriginal_block_size_on_dimÚshard_chunk_sizeÚprefix_shapeÚsuffix_shapeÚtensor_viewÚaxis_ws_absÚaxis_npp_absÚpermute_orderÚtensor_permutedÚfinal_ordered_tensors                   rB   Úrepack_weightsr›   ø   s:  € ð0 �QƒÜð có
ð 	
ð )4°qÓ(8™¸k×LaÑLaÑ>aÐØ 0× 6Ñ 6Ð7IÑ JÐØ!:Ñ!HÐØ1Ñ?Ðà#×)Ñ)Ð*=Ð+=Ð>€LØ#×)Ñ)Ð*<¸qÑ*@Ð*BÐC€Là"×'Ò'ð Ø	ðàðð 	ðð 	ð	ð
 
ò€Kô �lÓ#€KÜ�|Ó$ qÑ(€Läœ˜{×/Ñ/Ó0Ó1€MØ>KÑ>YÐ[hÑ[uÐ;€MÑ Ñ ;à!×)Ò)¨=Ð9€Oð +×5Ñ5Ð6FÓGÐàÐrK   c                ód  • UR                   nUR                  n[        [        R                  U5      n[        U [        R                  5      (       a  [        U R                  5      OU R                  5       n	US:  a  Xd-   nUR                  5       S:X  a  US:X  a  [        U	5      S:X  a  SnO+UR                  5       S:X  a  US:X  a  [        U	5      S:X  a  Sn[        R                  " X”   U-  5      n
X:-  n[        Xº-   X”   5      nXF:¼  a  [        SU SU 35      eX8:¼  a  [        SU SU 35      eUba  UR                  5       S:X  aM  US:X  aG  [        U	5      S:X  a8  Xµs=::  a  U:  a  O  OU S	S	 $ [        R                   " / [        R"                  US
9$ [%        S	5      /[        U	5      -  nX¹U   :  aF  [%        X¼5      XÔ'   U ['        U5         n [        U [        5      (       a  U  Vs/ s H  oîS	S	 PM	     n nU $ SX”'   [        R                   " ['        U	5      [        R"                  S9$ s  snf )a}  
Generalized tensor sharding across a multi-dimensional device mesh.
Extract only the fraction of the parameter owned by the given `rank` when the parameter would have gone sharding at provided `dim`.
Extraction follows the pytorch `Shard` placement so that sharding and materializing back to full tensor follows `Shard` semantics.
`Shard` follows torch.chunk style sharding of the tensor. We demonstrate some cases below on how sharding happens including some edge cases
such as some ranks having an empty tensor as shard. Below implementation is robut to all these cases.

Case (1)
empty_param                 (16, 5120, 8190)
dim                         0
device_mesh.size()          4
rank 0 gets                                 (4, 5120, 8190)                  (0 ... 4, 5120, 8190)
rank 1 gets                                 (4, 5120, 8190)                  (4 ... 8, 5120, 8190)
rank 2 gets                                 (4, 5120, 8190)                  (8 ... 12, 5120, 8190)
rank 3 gets                                 (4, 5120, 8190)                  (12 ... 16, 5120, 8190)

Case (2)
empty_param                 (16, 5120, 8190)
dim                         0
device_mesh.size()          14
rank 0 gets                                 (2, 5120, 8190)                  (0 ... 2, 5120, 8190)
rank 1 gets                                 (2, 5120, 8190)                  (2 ... 4, 5120, 8190)
rank 2 gets                                 (2, 5120, 8190)                  (4 ... 6, 5120, 8190)
rank 3 gets                                 (2, 5120, 8190)                  (6 ... 8, 5120, 8190)
rank 4 gets                                 (2, 5120, 8190)                  (8 ... 10, 5120, 8190)
rank 5 gets                                 (2, 5120, 8190)                  (10 ... 12, 5120, 8190)
rank 6 gets                                 (2, 5120, 8190)                  (12 ... 14, 5120, 8190)
rank 7 gets                                 (2, 5120, 8190)                  (14 ... 16, 5120, 8190)
rank 8 gets                                 (0, 5120, 8190)
rank 9 gets                                 (0, 5120, 8190)
rank 10 gets                            (0, 5120, 8190)
rank 11 gets                                (0, 5120, 8190)
rank 12 gets                                (0, 5120, 8190)
rank 13 gets                                (0, 5120, 8190)

Case (3)
empty_param                 (16, 5120, 8190)
dim                         0
device_mesh.size()          3
rank 0 gets                                 (6, 5120, 8190)                  (0 ... 6, 5120, 8190)
rank 1 gets                                 (6, 5120, 8190)                  (6 ... 12, 5120, 8190)
rank 2 gets                                 (4, 5120, 8190)                  (12 ... 16, 5120, 8190)

In case (2), empty shards are returned with appropriate dimension to allow for operations to work smoothly.
Args:
    param (torch.Tensor): The tensor to shard.
    empty_param (torch.Tensor): A tensor used for shape reference.
    device_mesh (torch.Tensor): Shape [d_0, ..., d_n] representing the mesh.
    rank (int): Global rank of the current process/device.
    dim (int): Dimension along which to shard the tensor.
r   é   r   r   zdim z* is out of bounds for tensor of dimension zRank z  is out of bounds for mesh size N©Údtyper2   )rŸ   )r5   rr   r   ÚoperatorÚmulrd   r"   ÚTensorre   Ú	get_shaperz   r‰   ÚmathÚceilÚminr    ÚemptyÚint64ÚsliceÚtuple)rx   ry   r;   r   rz   Ú
tensor_idxÚ	param_dimÚ
mesh_shaper   Úparam_shapeÚ
shard_sizer�   ÚendÚslice_indicesÚps                  rB   Úget_tensor_shardr³   9  sù  € ðh × Ñ €IØ×"Ñ"€JÜœŸ™ jÓ1€Jä'1°%¼¿¹×'FÑ'F”$�u—{‘{Ô#ÈEÏOÉOÓL]€KØ
ˆQƒwØ‰oˆØ‡�Ó˜AÓ #¨£(¬s°;Ó/?À1Ó/DØ‰Ø	�‰Ó	˜aÓ	 C¨1£H´°[Ó1AÀQÓ1FØˆä—’˜;Ñ+¨jÑ8Ó9€JØÑ€EÜ
ˆeÑ  +Ñ"2Ó
3€Cà
ÓÜ˜4 ˜uÐ$NÈyÈkÐZÓ[Ð[àÓÜ˜5  Ð&FÀzÀlÐSÓTÐTð Ñ +§/¡/Ó"3°qÓ"8¸SÀA»XÌ#ÈkÓJZÐ^_ÓJ_àÕ$ Ö$à™�8ˆOä—;’;˜r¬¯©¸TÑBÐBä˜4“[�M¤C¨Ó$4Ñ4€Mà˜3ÑÓÜ" 5Ó.ˆÑØ”e˜MÓ*Ñ+ˆÜ�eœT×"Ñ"Ù#(Ó)¢5˜a‘q“T¡5ˆEÐ)Øˆà€KÑÜ�;Š;”u˜[Ó)´·±Ñ=Ð=ùò	 *s   Ç+H-c                ó,   • [         R                  " XSS9$ )z9Split tensor along last dimension into world_size chunks.rq   ©rz   )r"   Úchunk)Úxr   s     rB   Ú_split_along_last_dimr¸   ¡  s   € ä�;Š;�q¨"Ñ-Ð-rK   c                  ó8   • \ rS rSrSr\S 5       r\S 5       rSrg)Ú_AllReduceBackwardi»  zRIdentity forward, all-reduce backward. Used before colwise layers (f in Megatron).c                ó   • X l         U$ ©N)r;   ©Úctxr·   r;   s      rB   ÚforwardÚ_AllReduceBackward.forward¾  s   € à%ŒØˆrK   c                óê   • U R                   nUR                  5       S:X  a  US 4$ UR                  5       n[        R                  " U[        R
                  R                  UR                  5       S9  US 4$ ©Nr   ©ÚoprG   )r;   r7   Ú
contiguousÚdistÚ
all_reduceÚReduceOpÚSUMÚ	get_group)r¾   Úgrad_outputr;   s      rB   ÚbackwardÚ_AllReduceBackward.backwardÃ  sc   € à—o‘oˆØ×ÑÓ Ó"Ø Ð$Ð$Ø!×,Ñ,Ó.ˆÜ�Š˜¬¯©×(9Ñ(9À×AVÑAVÓAXÒYØ˜DÐ Ð rK   © N©	Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__Ústaticmethodr¿   rÌ   Ú__static_attributes__rÎ   rK   rB   rº   rº   »  s+   † Ù\àñó ðð ñ!ó ó!rK   rº   c                  ó8   • \ rS rSrSr\S 5       r\S 5       rSrg)Ú_AllReduceForwardiÍ  zQAll-reduce forward, identity backward. Used after rowwise layers (g in Megatron).c                óª   • UR                  5       S:X  a  U$ [        R                  " U[        R                  R                  UR                  5       S9  U$ rÂ   )r7   rÆ   rÇ   rÈ   rÉ   rÊ   r½   s      rB   r¿   Ú_AllReduceForward.forwardÐ  s@   € à×ÑÓ Ó"ØˆHÜ�Š˜œdŸm™m×/Ñ/°{×7LÑ7LÓ7NÒOØˆrK   c                ó
   • US 4$ r¼   rÎ   )r¾   rË   s     rB   rÌ   Ú_AllReduceForward.backward×  s   € à˜DÐ Ð rK   rÎ   NrÏ   rÎ   rK   rB   rØ   rØ   Í  s+   † Ù[àñó ðð ñ!ó ó!rK   rØ   c                  ó8   • \ rS rSrSr\S 5       r\S 5       rSrg)Ú
_AllGatheriÜ  z<All-gather forward, split backward. Gathers sharded outputs.c                ó¢  • X l         UR                  5       nUS:X  a  U$ UR                  5       S-
  nUR                  5       nUR	                  5       nUR                  5       n[        U5       Vs/ s H  n[        R                  " U5      PM     nnXU'   [        R                  " X�US9  [        R                  " X„S9R                  5       $ s  snf ©Nr   rF   rµ   ©r;   r7   rz   Úget_local_rankrÊ   rÅ   rs   r"   Ú
empty_likerÆ   Ú
all_gatherÚcat)	r¾   r·   r;   r   Úlast_dimr   rG   Ú_Útensor_lists	            rB   r¿   Ú_AllGather.forwardß  s±   € à%ŒØ ×%Ñ%Ó'ˆ
à˜‹?ØˆHà—5‘5“7˜Q‘;ˆØ×)Ñ)Ó+ˆØ×%Ñ%Ó'ˆà�L‰L‹NˆÜ49¸*Ô4EÓFÒ4E¨q”u×'Ò'¨Ö*Ñ4EˆÐFØ�DÑÜ�Š˜¨eÒ4Ü�yŠy˜Ñ3×>Ñ>Ó@Ð@ùò Gs   Á/ Cc                ó¬   • U R                   nUR                  5       nUS:X  a  US 4$ UR                  5       n[        X5      nXT   R	                  5       S 4$ ©Nr   ©r;   r7   râ   r¸   rÅ   )r¾   rË   r;   r   r   Úchunkss         rB   rÌ   Ú_AllGather.backwardñ  sY   € à—o‘oˆØ ×%Ñ%Ó'ˆ
à˜‹?Ø Ð$Ð$à×)Ñ)Ó+ˆÜ& {Ó?ˆØ‰|×&Ñ&Ó(¨$Ð.Ð.rK   rÎ   NrÏ   rÎ   rK   rB   rÞ   rÞ   Ü  s-   † ÙFàñAó ðAð" ñ	/ó ó	/rK   rÞ   c                  ó8   • \ rS rSrSr\S 5       r\S 5       rSrg)Ú_Splitiþ  z>Split forward, all-gather backward. Scatters replicated input.c                ó˜   • X l         UR                  5       nUS:X  a  U$ UR                  5       n[        X5      nXT   R	                  5       $ rë   rì   )r¾   r·   r;   r   r   rí   s         rB   r¿   Ú_Split.forward  sJ   € à%ŒØ ×%Ñ%Ó'ˆ
à˜‹?ØˆHà×)Ñ)Ó+ˆÜ& qÓ5ˆØ‰|×&Ñ&Ó(Ð(rK   c                ó¶  • U R                   nUR                  5       nUS:X  a  US 4$ UR                  5       S-
  nUR                  5       nUR	                  5       nUR                  5       n[        U5       Vs/ s H  n[        R                  " U5      PM     nnXU'   [        R                  " X�US9  [        R                  " X„S9R                  5       S 4$ s  snf rà   rá   ©	r¾   rË   r;   r   ræ   r   rG   rç   rè   s	            rB   rÌ   Ú_Split.backward  óÅ   € à—o‘oˆØ ×%Ñ%Ó'ˆ
à˜‹?Ø Ð$Ð$à—?‘?Ó$ qÑ(ˆØ×)Ñ)Ó+ˆØ×%Ñ%Ó'ˆà!×,Ñ,Ó.ˆÜ>CÀJÔ>OÓPÒ>O¸”u×'Ò'¨Ö4Ñ>OˆÐPØ'�DÑÜ�Š˜¸Ò>Ü�yŠy˜Ñ3×>Ñ>Ó@À$ÐFÐFùò Qó   Á7 CrÎ   NrÏ   rÎ   rK   rB   rð   rð   þ  s-   † ÙHàñ	)ó ð	)ð ñGó óGrK   rð   c                  ó8   • \ rS rSrSr\S 5       r\S 5       rSrg)Ú_ReduceScatteri   zCReduce-scatter forward, all-gather backward. For sequence parallel.c                ó¨  • X l         UR                  5       nUS:X  a  U$ UR                  5       S-
  nUR                  5       n[	        UR                  X4S95      n[	        UR                  5      nXt==   U-  ss'   [        R                  " XqR                  UR                  S9n[        R                  " X†[        R                  R                  US9  U$ )Nr   rµ   rž   rÃ   )r;   r7   rz   rÊ   re   r¶   rr   r"   r§   rŸ   r2   rÆ   Úreduce_scatterrÈ   rÉ   )	r¾   r·   r;   r   ræ   rG   Úinput_chunksÚoutput_shapeÚoutputs	            rB   r¿   Ú_ReduceScatter.forward#  s§   € à%ŒØ ×%Ñ%Ó'ˆ
à˜‹?ØˆHà—5‘5“7˜Q‘;ˆØ×%Ñ%Ó'ˆä˜AŸG™G J˜GÐ=Ó>ˆÜ˜AŸG™G“}ˆØÓ :Ñ-ÓÜ—’˜\·±ÀÇÁÑJˆä×Ò˜F´T·]±]×5FÑ5FÈeÒTØˆrK   c                ó¶  • U R                   nUR                  5       nUS:X  a  US 4$ UR                  5       S-
  nUR                  5       nUR	                  5       nUR                  5       n[        U5       Vs/ s H  n[        R                  " U5      PM     nnXU'   [        R                  " X�US9  [        R                  " X„S9R                  5       S 4$ s  snf rà   rá   rô   s	            rB   rÌ   Ú_ReduceScatter.backward6  rö   r÷   rÎ   NrÏ   rÎ   rK   rB   rù   rù      s-   † ÙMàñó ðð$ ñGó óGrK   rù   c                ó,   • [         R                  X5      $ )zAIdentity forward, all-reduce backward. Use before colwise layers.)rº   Úapply©r·   r;   s     rB   Úall_reduce_backwardr  N  s   € ä×#Ñ# AÓ3Ð3rK   c                ó,   • [         R                  X5      $ )z@All-reduce forward, identity backward. Use after rowwise layers.)rØ   r  r  s     rB   Úall_reduce_forwardr  S  s   € ä×"Ñ" 1Ó2Ð2rK   c                ó,   • [         R                  X5      $ )z#All-gather forward, split backward.)rÞ   r  r  s     rB   rä   rä   X  s   € ä×Ñ˜AÓ+Ð+rK   c                ó,   • [         R                  X5      $ )z#Split forward, all-gather backward.)rð   r  r  s     rB   Úsplitr
  ]  s   € ä�<‰<˜Ó'Ð'rK   c                ó,   • [         R                  X5      $ )z,Reduce-scatter forward, all-gather backward.)rù   r  r  s     rB   rû   rû   b  s   € ä×Ñ Ó/Ð/rK   c                óp   ^^^• Tb  U R                  UU4S j5        Tb  U R                  UU4S j5        U $ )z’
Copy pasted from torch's function but we remove the communications (partitioning)
as well as buffer registering that is similarly not efficient.
c                ó   >• T" XT5      $ r¼   rÎ   )ÚmodÚinputsr;   Úinput_fns     €€rB   rI   Ú#distribute_module.<locals>.<lambda>r  s   ø€ ¹XÀcÐS^Ô=_rK   c                ó   >• T" XT5      $ r¼   rÎ   )r  r  Úoutputsr;   Ú	output_fns      €€rB   rI   r  t  s   ø€ Á)ÈCÐZeÔBfrK   )Úregister_forward_pre_hookÚregister_forward_hook)Úmoduler;   r  r  s    ```rB   Údistribute_moduler  g  s4   ú€ ð ÑØ×(Ñ(Õ)_Ô`ØÑØ×$Ñ$Õ%fÔgØ€MrK   c                  ór   • \ rS rSrSrSrSrSrSS jrS r	S r
 S     SS jjrSS jrSS	 jrSS
 jrSrg)ÚTensorParallelLayerix  z.General tensor parallel layer for transformersNc                ó(   • X l         Xl        X0l        g r¼   )r   r;   ry   )Úselfr;   r   ry   s       rB   Ú__init__ÚTensorParallelLayer.__init__  s   € ØŒ	Ø&ÔØ&ÕrK   c                ó   • [         er¼   ©ÚNotImplementedError©r  r  r  r;   s       rB   Ú_prepare_input_fnÚ%TensorParallelLayer._prepare_input_fn„  ó   € Ü!Ð!rK   c                ó   • [         er¼   r   ©r  r  r  r;   s       rB   Ú_prepare_output_fnÚ&TensorParallelLayer._prepare_output_fn‡  r%  rK   c                ó   • [         er¼   r   ©r  rx   r«   r2   rŸ   s        rB   Úshard_tensorÚ TensorParallelLayer.shard_tensorŠ  s
   € ô "Ð!rK   c                óH   • [        UUU R                  U R                  5        g r¼   )r  r#  r(  ©r  r  r;   Úkwargss       rB   Úprepare_module_tpÚ%TensorParallelLayer.prepare_module_tp�  s"   € ÜØØØ×"Ñ"Ø×#Ñ#õ		
rK   c                ó   • [        U5      $ )z¹
Compute the expected shape after TP sharding for a given full shape.

Args:
    full_shape: The full (unsharded) parameter shape

Returns:
    The expected sharded shape for this rank
)rª   )r  Ú
full_shapes     rB   Úget_expected_sharded_shapeÚ.TensorParallelLayer.get_expected_sharded_shape—  s   € ô �ZÓ Ð rK   c                ó   • g)z±
Update module attributes (e.g. in_features, out_features) to reflect sharded dimensions.

Args:
    module: The module to update

Returns:
    None, update the module in-place
NrÎ   ©r  r  s     rB   Úupdate_module_attributesÚ,TensorParallelLayer.update_module_attributes¤  s   € ð 	rK   )r;   ry   r   ©NNN©rx   útorch.Tensorr«   ú
int | NoneÚreturnr=  ©r  ú	nn.Moduler?  rA  ©r4  ztuple[int, ...] | torch.Sizer?  ztuple[int, ...]©r  rA  )rÐ   rÑ   rÒ   rÓ   rÔ   r;   r   ry   r  r#  r(  r,  r1  r5  r9  rÖ   rÎ   rK   rB   r  r  x  sV   † Ù8à€KØ€DØ€Kô'ò
"ò"ð VZð"Ø!ð"Ø/9ð"à	õ"ô

ô!÷
rK   r  c                  ón   ^ • \ rS rSrSrS
SU 4S jjjrS rS r S     SS jjrSS jr	SS jr
S	rU =r$ )ÚColwiseParalleli±  zÅ
Column-wise parallel: weight is sharded on dim -2 (output features).
Forward: input replicated -> output sharded on last dim.
If gather_output=True, output is all-gathered to produce full tensor.
c                ó2   >• [         TU ]  " S0 UD6  Xl        g ©NrÎ   )Úsuperr  Úgather_output)r  rI  r0  Ú	__class__s      €rB   r  ÚColwiseParallel.__init__¸  s   ø€ Ü‰ÒÑ"˜6Ò"Ø*ÕrK   c                ó4   • U(       a  US   OUn[        XC5      $ ©Nr   ©r  ©r  r  r  r;   Úinput_tensors        rB   r#  Ú!ColwiseParallel._prepare_input_fn¼  s   € Þ$*�v˜a’y°ˆÜ" <Ó=Ð=rK   c                ó>   • U R                   (       a  [        X#5      $ U$ r¼   )rI  rä   r'  s       rB   r(  Ú"ColwiseParallel._prepare_output_fnÀ  s   € Ø××Ü˜gÓ3Ð3ØˆrK   c                ón  • [        U[        R                  5      (       a  UR                  5       O[	        UR                  5       5      nUS:X  a-  [        XR                  U R                  U R                  S5      nO,[        XR                  U R                  U R                  S5      nUR                  X4S9$ ©Nr   rq   rp   ©r2   rŸ   ©rd   r"   r¢   rz   r‰   r£   r³   ry   r;   r   ru   ©r  rx   r«   r2   rŸ   rz   Ú	parameters          rB   r,  ÚColwiseParallel.shard_tensorÅ  s�   € ô (¨¬u¯|©|×<Ñ<ˆe�i‰iŒkÄ#ÀeÇoÁoÓFWÓBXˆØ�!‹8Ü(¨×0@Ñ0@À$×BRÑBRÐTX×T]ÑT]Ð_aÓb‰Iä(¨×0@Ñ0@À$×BRÑBRÐTX×T]ÑT]Ð_aÓbˆIØ�|‰| 6ˆ|Ð7Ð7rK   c                ó4  • U R                   R                  5       n[        U5      n[        U5      S:X  a  SOSnUS:  a  [        U5      U-   OUn[        R
                  " X4   U-  5      nU R                  U-  n[        Xe-   X4   5      nXv-
  X4'   [        U5      $ )Nr   rq   rp   r   )	r;   r7   re   r‰   r¤   r¥   r   r¦   rª   ©r  r4  r   rr   rz   r¯   r�   r°   s           rB   r5  Ú*ColwiseParallel.get_expected_sharded_shapeÐ  sŽ   € Ø×%Ñ%×*Ñ*Ó,ˆ
Ü�ZÓ ˆä˜“J !“O‰b¨ˆØ"%¨£'Œc�%‹j˜3Ò¨sˆÜ—Y’Y˜u™z¨JÑ6Ó7ˆ
Ø—	‘	˜JÑ&ˆÜ�%Ñ$ e¡jÓ1ˆØ‘[ˆ‰
Ü�U‹|ÐrK   c                ó”   • U R                   (       d7  [        US5      (       a%  U R                  UR                  45      S   Ul        g g g )NÚout_featuresr   )rI  Úhasattrr5  r_  r8  s     rB   r9  Ú(ColwiseParallel.update_module_attributesÜ  sD   € ð ×!×!¤g¨f°n×&EÑ&EØ"&×"AÑ"AÀ6×CVÑCVÐBXÓ"YÐZ[Ñ"\ˆFÕð 'FÐ!rK   ©rI  ©F)rI  Úboolr;  r<  rB  rC  ©rÐ   rÑ   rÒ   rÓ   rÔ   r  r#  r(  r,  r5  r9  rÖ   Ú__classcell__©rJ  s   @rB   rE  rE  ±  sQ   ø† ñ÷+ñ +ò>òð VZð	8Ø!ð	8Ø/9ð	8à	õ	8ô
÷]ò ]rK   rE  c                  ó4   • \ rS rSrSrS rS rS	S jrS rSr	g)
ÚReplicatedWithGradAllReduceiã  a5  
Replicated parameter with gradient all-reduce.

For parameters like q_norm/k_norm that sit between colwise and rowwise
layers. The parameter is replicated (not sharded), but its gradient
accumulates from local heads only in TP mode. This class registers a
backward hook to all-reduce the parameter gradient.
c                ó   • U$ r¼   rÎ   r"  s       rB   r#  Ú-ReplicatedWithGradAllReduce._prepare_input_fní  s   € ØˆrK   c                ó   • U$ r¼   rÎ   r'  s       rB   r(  Ú.ReplicatedWithGradAllReduce._prepare_output_fnð  s   € ØˆrK   Nc                ó&   • US   R                  X4S9$ ©N.rV  ©ru   r+  s        rB   r,  Ú(ReplicatedWithGradAllReduce.shard_tensoró  ó   € Ø�S‰z�}‰} Fˆ}Ð8Ð8rK   c                ó2   • U4S jnUR                  U5        g )Nc                ó|   • U R                  5        H(  nUR                  c  M  [        UR                  U5        M*     g r¼   )Ú
parametersÚgradr  )r  Ú
grad_inputrË   Úmeshrx   s        rB   Ú_backward_hookÚEReplicatedWithGradAllReduce.prepare_module_tp.<locals>._backward_hookù  s+   € ØŸ™Ö)�Ø—:‘:Ó)Ü& u§z¡z°4Ö8ò *rK   )Úregister_full_backward_hook)r  r  r;   r0  ry  s        rB   r1  Ú-ReplicatedWithGradAllReduce.prepare_module_tpö  s   € ð ?Jô 	9ð
 	×*Ñ*¨>Õ:rK   rÎ   r;  )
rÐ   rÑ   rÒ   rÓ   rÔ   r#  r(  r,  r1  rÖ   rÎ   rK   rB   ri  ri  ã  s   † ñòòô9õ;rK   ri  c                  ó2   • \ rS rSrSrS rSS jrS	S jrSrg)
ÚMlaKvAProjParalleli  aË  
For MLA attention used in DeepSeek-V2 style models (deepseek_v2, longcat_flash, glm_moe_dsa, glm4_moe_lite):
kv_a_proj_with_mqa output is [kv_lora_rank + qk_rope_head_dim] (can have different naming but important thing
to understand is that it is split)
Example below (from modeling_longcat_flash.py):

kv_a_proj_with_mqa
        |
        split
        /            k_pass    k_rot  <-- "bypasses kv_b_proj"
    |          |        (goes straight to attention,
kv_a_layernorm |         never touches kv_b_proj)
    |          |
kv_b_proj      |
(colwise)      |
    |          |
    k_pass     k_rot
        \      /
           cat
            |
        key_states

k_pass is passed to kv_b_proj (colwise) which has built-in all_reduce_backward so we don't have a partial gradient for it.
However, k_rot goes straight to attention, never touches kv_b_proj. So we need to average gradient across all ranks otherwise we only get gradient for one rank (partial gradient).
c                ó2  • [        UR                  S5      (       d"  [        S[        U5      R                   S35      eUR                  R
                  nUR                  UR                  S   U-
  U/SS9u  pV[        Xc5      n[        R                  " XV/SS9$ )NÚqk_rope_head_dimzConfig for z· does not have `qk_rope_head_dim`. MlaKvAProjParallel requires `qk_rope_head_dim` to be defined in the model config. Please add it to the model's config or update the TP plan mapping.rq   rµ   )r`  ÚconfigÚAttributeErrorr%   rÐ   r€  r
  rr   r  r"   rå   )r  r  rþ   r;   Úrope_dimÚpass_outputÚrope_outputs          rB   r(  Ú%MlaKvAProjParallel._prepare_output_fn  s—   € Ü�s—z‘zÐ#5×6Ñ6Ü Øœd 3›i×0Ñ0Ð1ð 2Uð Uóð ð
 —:‘:×.Ñ.ˆØ#)§<¡<°·±¸bÑ1AÀHÑ1LÈhÐ0WÐ]_ <Ð#`Ñ ˆÜ)¨+ÓCˆÜ�yŠy˜+Ð3¸Ñ<Ð<rK   Nc                ó&   • US   R                  X4S9$ ro  rp  r+  s        rB   r,  ÚMlaKvAProjParallel.shard_tensor)  rr  rK   c                ó8   • X1l         [        XU R                  S9  g )N)r  )r�  r  r(  )r  r  r;   r�  r0  s        rB   r1  Ú$MlaKvAProjParallel.prepare_module_tp,  s   € ØŒÜ˜&¸×9PÑ9PÓQrK   rÎ   r;  r¼   )	rÐ   rÑ   rÒ   rÓ   rÔ   r(  r,  r1  rÖ   rÎ   rK   rB   r~  r~    s   † ñò6
=ô9÷RrK   r~  c                  ón   ^ • \ rS rSrSrS
SU 4S jjjrS rS r S     SS jjrSS jr	SS jr
S	rU =r$ )ÚRowwiseParalleli1  a‚  
Row-wise parallel: weight is sharded on dim -1 (input features).
Forward: input (optionally split) -> output partial -> all-reduce to replicate.

Args:
    split_input: If True, splits replicated input before matmul. Use when input
                 comes from a non-parallelizable operation (chunk/slice).
                 Default False (expects pre-sharded input from colwise layer).
c                ó2   >• [         TU ]  " S0 UD6  Xl        g rG  )rH  r  Úsplit_input)r  rŽ  r0  rJ  s      €rB   r  ÚRowwiseParallel.__init__<  s   ø€ Ü‰ÒÑ"˜6Ò"Ø&ÕrK   c                óÆ   • [        US5      (       a%  UR                  b  UR                  Ul        S Ul        U(       a  US   OUnU R                  (       a  [	        XC5      $ U$ )NÚbiasr   )r`  r‘  Ú_biasrŽ  r
  rO  s        rB   r#  Ú!RowwiseParallel._prepare_input_fn@  sQ   € Ü�3˜×Ñ C§H¡HÑ$8ØŸ™ˆCŒIØˆCŒHæ$*�v˜a’y°ˆà××ä˜Ó3Ð3ØÐrK   c                ót   • [        X#5      n[        US5      (       a  UR                  b  X!R                  -   nU$ )Nr’  )r  r`  r’  r'  s       rB   r(  Ú"RowwiseParallel._prepare_output_fnL  s3   € Ü$ WÓ:ˆÜ�3˜× Ñ  S§Y¡YÑ%:Ø§	¡	Ñ)ˆGØˆrK   c                ó   • [        U[        R                  5      (       a  UR                  5       O[	        UR                  5       5      nUS:X  a  US   nO,[        XR                  U R                  U R                  S5      nUR                  X4S9$ )Nr   .rq   rV  rW  rX  s          rB   r,  ÚRowwiseParallel.shard_tensorR  sr   € ô (¨¬u¯|©|×<Ñ<ˆe�i‰iŒkÄ#ÀeÇoÁoÓFWÓBXˆØ�!‹8Ø˜c™
‰Iä(¨×0@Ñ0@À$×BRÑBRÐTX×T]ÑT]Ð_aÓbˆIØ�|‰| 6ˆ|Ð7Ð7rK   c                óF  • [        U5      S:X  a  [        U5      $ U R                  R                  5       n[	        U5      nSnUS:  a  [        U5      U-   OUn[
        R                  " X4   U-  5      nU R                  U-  n[        Xe-   X4   5      nXv-
  X4'   [        U5      $ ©Nr   rq   r   )	r‰   rª   r;   r7   re   r¤   r¥   r   r¦   r\  s           rB   r5  Ú*RowwiseParallel.get_expected_sharded_shape]  s™   € äˆz‹?˜aÓÜ˜Ó$Ð$Ø×%Ñ%×*Ñ*Ó,ˆ
Ü�ZÓ ˆØˆØ"%¨£'Œc�%‹j˜3Ò¨sˆÜ—Y’Y˜u™z¨JÑ6Ó7ˆ
Ø—	‘	˜JÑ&ˆÜ�%Ñ$ e¡jÓ1ˆØ‘[ˆ‰
Ü�U‹|ÐrK   c                óv   • [        US5      (       a(  SUR                  4nU R                  U5      S   Ul        g g )NÚin_featuresr   )r`  rœ  r5  )r  r  rr   s      rB   r9  Ú(RowwiseParallel.update_module_attributesk  s>   € Ü�6˜=×)Ñ)ð ˜×*Ñ*Ð+ˆEØ!%×!@Ñ!@ÀÓ!GÈÑ!JˆFÕð	 *rK   ©rŽ  rc  )rŽ  rd  r;  r<  rB  rC  re  rg  s   @rB   rŒ  rŒ  1  sQ   ø† ñ÷'ñ 'ò
òð VZð	8Ø!ð	8Ø/9ð	8à	õ	8ô÷Kò KrK   rŒ  c                  ó2   • \ rS rSrSr S     SS jjrSrg)ÚPackedColwiseParallelis  z@Packed column-wise parallel for fused weights like gate_up_proj.Nc                ó0  • [        U[        R                  5      (       a  UR                  5       O[	        UR                  5       5      nUS:X  a-  [        XR                  U R                  U R                  S5      nO�U R                  U R                  R                  5      nU[	        U5      :  a-  [        XR                  U R                  U R                  S5      nO,[        XR                  U R                  U R                  S5      nUR                  X4S9$ rU  )rd   r"   r¢   rz   r‰   r£   r³   ry   r;   r   r5  rr   r†   ru   )r  rx   r«   r2   rŸ   rz   rY  Úexpected_shapes           rB   r,  Ú"PackedColwiseParallel.shard_tensorv  sÞ   € ô (¨¬u¯|©|×<Ñ<ˆe�i‰iŒkÄ#ÀeÇoÁoÓFWÓBXˆØ�!‹8Ü(¨×0@Ñ0@À$×BRÑBRÐTX×T]ÑT]Ð_aÓb‰Ià!×<Ñ<¸T×=MÑ=M×=SÑ=SÓTˆNØ”S˜Ó(Ó(ô -¨U×4DÑ4DÀd×FVÑFVÐX\×XaÑXaÐceÓf‘	ô /¨u×6FÑ6FÈ×HXÑHXÐZ^×ZcÑZcÐegÓh�	Ø�|‰| 6ˆ|Ð7Ð7rK   rÎ   r;  r<  ©rÐ   rÑ   rÒ   rÓ   rÔ   r,  rÖ   rÎ   rK   rB   r   r   s  s.   † ÙJð VZð8Ø!ð8Ø/9ð8à	÷8ð 8rK   r   c                  ó2   • \ rS rSrSr S     SS jjrSrg)ÚPackedRowwiseParalleli‰  z=Packed row-wise parallel for fused weights like gate_up_proj.Nc                ó˜  • [        U[        R                  5      (       a  UR                  5       O[	        UR                  5       5      nUS:X  a  US   nOè[        U[        R                  5      (       a  UR                  OUR                  5       nU R                  R                  5       S:¼  a  U R                  R                  S   OSn[	        U5      S:¼  a  US   OSn	X˜:  a-  [        XR                  U R                  U R                  S5      nO,[        XR                  U R                  U R                  S5      nUR                  X4S9$ )Nr   .rq   r   rV  )rd   r"   r¢   rz   r‰   r£   rr   ry   r³   r;   r   r†   ru   )
r  rx   r«   r2   rŸ   rz   rY  r®   Úexpected_packed_dimÚ
actual_dims
             rB   r,  Ú"PackedRowwiseParallel.shard_tensorŒ  s
  € ô (¨¬u¯|©|×<Ñ<ˆe�i‰iŒkÄ#ÀeÇoÁoÓFWÓBXˆØ�!‹8Ø˜c™
‰Iô *4°E¼5¿<¹<×)HÑ)H˜%Ÿ+š+ÈeÏoÉoÓN_ˆKØ@D×@PÑ@P×@TÑ@TÓ@VÐZ[Ó@[ $×"2Ñ"2×"8Ñ"8¸Ò"<ÐabÐÜ,/°Ó,<ÀÓ,A˜ RšÀqˆJàÓ/ä,¨U×4DÑ4DÀd×FVÑFVÐX\×XaÑXaÐceÓf‘	ô /¨u×6FÑ6FÈ×HXÑHXÐZ^×ZcÑZcÐegÓh�	Ø�|‰| 6ˆ|Ð7Ð7rK   rÎ   r;  r<  r¤  rÎ   rK   rB   r¦  r¦  ‰  s.   † ÙGð VZð8Ø!ð8Ø/9ð8à	÷8ð 8rK   r¦  c                  ór   ^ • \ rS rSrSrSS.SU 4S jjjrS rS r S     SS jjrSS	 jr	SS
 jr
SrU =r$ )ÚEmbeddingParalleli£  zXEmbeddingParallel: shards embedding table, handles masked lookups for vocab parallelism.r   ©Úembedding_dim_shardingc               ó2   >• [         TU ]  " S0 UD6  Xl        g rG  )rH  r  r®  )r  r®  r0  rJ  s      €rB   r  ÚEmbeddingParallel.__init__¦  s   ø€ Ü‰ÒÑ"˜6Ò"Ø&<Õ#rK   c                óô   • U(       a  US   OUnU R                   S:X  aY  UR                  5       nUR                  R                  S   nXV-  nXv-   nXG:  XH:¬  -  n	X‘l        UR                  5       U-
  n
SX©'   U
$ U$ rM  )r®  râ   Úweightrr   Ú_input_maskÚclone)r  r  r  r;   rP  r   Úper_partition_sizeÚvocab_start_indexÚvocab_end_indexÚ
input_maskÚmasked_inputs              rB   r#  Ú#EmbeddingParallel._prepare_input_fnª  s–   € Þ$*�v˜a’y°ˆð ×&Ñ&¨!Ó+Ø×-Ñ-Ó/ˆDð
 "%§¡×!1Ñ!1°!Ñ!4ÐØ $Ñ 9ÐØ/ÑDˆOð 'Ñ:¸|Ñ?^Ñ_ˆJØ(ŒOð (×-Ñ-Ó/Ð2CÑCˆLØ'(ˆLÑ$àÐàÐrK   c                óò   • U R                   S:X  a]  [        US5      (       aL  UR                  nUR                  S5      R	                  U5      nX%) R                  UR                  5      -  nU?[        X#5      $ )Nr   r³  rq   )r®  r`  r³  Ú	unsqueezeÚ	expand_asru   rŸ   r  )r  r  r  r;   r¸  Úmask_expandeds         rB   r(  Ú$EmbeddingParallel._prepare_output_fnÄ  si   € à×&Ñ&¨!Ó+´¸¸]×0KÑ0KØŸ™ˆJà&×0Ñ0°Ó4×>Ñ>¸wÓGˆMØ × 3Ñ 3°G·M±MÓ BÑBˆGØ�ä! 'Ó7Ð7rK   c                ó„  • [        U[        R                  5      (       a  UR                  5       O[	        UR                  5       5      nUS:X  a-  [        XR                  U R                  U R                  S5      nO7[        UU R                  U R                  U R                  U R                  5      nUR                  X4S9$ )Nr   rq   rV  )rd   r"   r¢   rz   r‰   r£   r³   ry   r;   r   r®  ru   rX  s          rB   r,  ÚEmbeddingParallel.shard_tensorÏ  sš   € ô (¨¬u¯|©|×<Ñ<ˆe�i‰iŒkÄ#ÀeÇoÁoÓFWÓBXˆØ�!‹8Ü(¨×0@Ñ0@À$×BRÑBRÐTX×T]ÑT]Ð_aÓb‰Iä(ØØ× Ñ Ø× Ñ Ø—	‘	Ø×+Ñ+óˆIð �|‰| 6ˆ|Ð7Ð7rK   c                óH  • U R                   R                  5       n[        U5      n[        U5      S:X  a  SOU R                  nUS:  a  [        U5      U-   OUn[
        R                  " X4   U-  5      nU R                  U-  n[        Xe-   X4   5      nXv-
  X4'   [        U5      $ r™  )
r;   r7   re   r‰   r®  r¤   r¥   r   r¦   rª   r\  s           rB   r5  Ú,EmbeddingParallel.get_expected_sharded_shapeà  s–   € Ø×%Ñ%×*Ñ*Ó,ˆ
Ü�ZÓ ˆô ˜“J !“O‰b¨×)DÑ)DˆØ"%¨£'Œc�%‹j˜3Ò¨sˆÜ—Y’Y˜u™z¨JÑ6Ó7ˆ
Ø—	‘	˜JÑ&ˆÜ�%Ñ$ e¡jÓ1ˆØ‘[ˆ‰
Ü�U‹|ÐrK   c                ó  • [        US5      (       a4  U R                  S:X  a$  U R                  UR                  45      S   Ul        [        US5      (       a6  U R                  S:X  a%  U R                  UR                  45      S   Ul        g g g )NÚnum_embeddingsr   Úembedding_dimr   )r`  r®  r5  rÅ  rÆ  r8  s     rB   r9  Ú*EmbeddingParallel.update_module_attributesí  s…   € Ü�6Ð+×,Ñ,°×1LÑ1LÐPQÓ1QØ$(×$CÑ$CÀV×EZÑEZÐD\Ó$]Ð^_Ñ$`ˆFÔ!Ü�6˜?×+Ñ+°×0KÑ0KÈqÓ0PØ#'×#BÑ#BÀF×DXÑDXÐCZÓ#[Ð\]Ñ#^ˆFÕ ð 1QÐ+rK   )r®  r*   r;  r<  rB  rC  re  rg  s   @rB   r¬  r¬  £  sR   ø† Ùbà89÷ =ò =òò4	8ð VZð8Ø!ð8Ø/9ð8à	õ8ô"÷_ò _rK   r¬  c                  óZ   ^ • \ rS rSrSrSS	U 4S jjjrS rS r S
     SS jjrSr	U =r
$ )ÚSequenceParalleliô  zX
Sequence Parallel: input/output sharded on sequence dimension.
Weights are replicated.
c                ó2   >• [         TU ]  " S0 UD6  Xl        g rG  )rH  r  Úsequence_dim)r  rË  Úuse_local_outputÚuse_dtensorr0  rJ  s        €rB   r  ÚSequenceParallel.__init__ú  s   ø€ Ü‰ÒÑ"˜6Ò"Ø(ÕrK   c                ó4   • U(       a  US   OUn[        XC5      $ rM  )rä   rO  s        rB   r#  Ú"SequenceParallel._prepare_input_fnþ  s   € Þ$*�v˜a’y°ˆô ˜,Ó4Ð4rK   c                ó   • [        X#5      $ r¼   )rû   r'  s       rB   r(  Ú#SequenceParallel._prepare_output_fn  s   € Ü˜gÓ3Ð3rK   c                ó&   • US   R                  X4S9$ ro  rp  r+  s        rB   r,  ÚSequenceParallel.shard_tensor  ó   € ð �S‰z�}‰} Fˆ}Ð8Ð8rK   )rË  )r   FF)rË  r*   rÌ  rd  r;  r<  ©rÐ   rÑ   rÒ   rÓ   rÔ   r  r#  r(  r,  rÖ   rf  rg  s   @rB   rÉ  rÉ  ô  sE   ø† ñ÷
)ñ )ò5ò4ð VZð9Ø!ð9Ø/9ð9à	÷9ó 9rK   rÉ  c                  óZ   ^ • \ rS rSrSrU 4S jr S     S	S jjrS
S jrSS jrSr	U =r
$ )ÚGroupedGemmParalleli  zZ
Applies Expert Parallelism to MoE experts by loading the correct experts on each device.
c                ó&   >• [         TU ]  " S0 UD6  g rG  ©rH  r  ©r  r0  rJ  s     €rB   r  ÚGroupedGemmParallel.__init__  ó   ø€ Ü‰ÒÑ"˜6Ó"rK   c                óv  • U R                   R                  S   nXPR                  R                  5       -  S:w  a*  [	        SU SU R                  R                  5        S35      eXPR                  R                  5       -  nUnU R
                  U-  nU R
                  S-   U-  n	[        U[        R                  5      (       d  UR                  5       OUR                  n
Ub!  X‚s=::  a  U	:  a  O  OUS S  R                  US9$ Uc  XU	 R                  X4S9$ [        U
5      S:¼  a  Ub  g US S  R                  X4S9$ )Nr   zAGlobal number of experts must be divisible by number of devices: ú % ú != 0r   )r2   rV  )ry   rr   r;   r7   r    r   rd   r"   r¢   r£   ru   r‰   )r  rx   r«   r2   rŸ   Úglobal_num_expertsÚlocal_num_expertsr¯   r�   r°   rr   s              rB   r,  Ú GroupedGemmParallel.shard_tensor  sM  € ð "×-Ñ-×3Ñ3°AÑ6ÐØ× 0Ñ 0× 5Ñ 5Ó 7Ñ7¸1Ó<ÜØSÐTfÐSgÐgjÐko×k{Ñk{÷  lAñ  lAó  lCð  kDð  DIð  Jóð ð /×2BÑ2B×2GÑ2GÓ2IÑIÐØ&ˆ
Ø—	‘	˜JÑ&ˆØ�y‰y˜1‰} 
Ñ*ˆä)3°E¼5¿<¹<×)HÑ)H�—‘Ô!ÈeÏkÉkˆØÑ! eÕ&?¸CÖ&?à™�8—;‘; f�;Ð-Ð-ØÑØ˜sÐ#×&Ñ&¨fÐ&ÐBÐBÜ�‹Z˜1‹_ Ñ!7Øà™�8—;‘; f�;Ð:Ð:rK   c                óz   • U R                   R                  5       n[        U5      nUS   U-  nXCS'   [        U5      $ rM  )r;   r7   re   rª   )r  r4  r   rr   râ  s        rB   r5  Ú.GroupedGemmParallel.get_expected_sharded_shape-  s@   € à×%Ñ%×*Ñ*Ó,ˆ
Ü�ZÓ ˆØ! !™H¨
Ñ2ÐØ$ˆa‰Ü�U‹|ÐrK   c                óŠ   • [        US5      (       a2  U R                  U R                  R                  S   45      S   Ul        g g )NÚnum_expertsr   )r`  r5  ry   rr   rç  r8  s     rB   r9  Ú,GroupedGemmParallel.update_module_attributes5  sB   € Ü�6˜=×)Ñ)Ø!%×!@Ñ!@À$×BRÑBR×BXÑBXÐYZÑB[ÐA]Ó!^Ð_`Ñ!aˆFÕð *rK   rÎ   r;  r<  rB  rC  )rÐ   rÑ   rÒ   rÓ   rÔ   r  r,  r5  r9  rÖ   rf  rg  s   @rB   rØ  rØ    sB   ø† ñõ#ð VZð;Ø!ð;Ø/9ð;à	õ;ô0÷bò brK   rØ  c                  óR   ^ • \ rS rSrSrU 4S jrS rS r S     S	S jjrSr	U =r
$ )
ÚRouterParalleli:  zI
Allows to reshape the router scores to support running expert parallel.
c                ó&   >• [         TU ]  " S0 UD6  g rG  rÚ  rÛ  s     €rB   r  ÚRouterParallel.__init__?  rÝ  rK   c                ó   • U(       a  US   $ U$ rM  rÎ   r"  s       rB   r#  Ú RouterParallel._prepare_input_fnB  s   € Þ"ˆv�a‰yÐ.¨Ð.rK   c                ó2  • UR                  5       UR                  5       pT[        USS5      nUc  [        [        USS5      SS5      nUc"  [        S[	        U5      R
                   S35      eXe-  S:w  a  [        SU SU S	35      eXe-  nUu  p‰n
X§-  U:g  nU	R                  US
5      n	U
R                  US5      n
US:”  a  [        R                  " X§5      n
O(U
R                  U
S:„  S5      R                  U
S:  S5      n
U
R                  U
S:H  U5      n
X‰U
4$ )uá  
Remap global expert indices to local and zero out non-local scores.

Example: 4 tokens, top_k=4, 128 experts, EP=8. num_local_experts = 128/8 = 16.

Router produces (all ranks see the same values):
    router_scores:  (4, 4)  â€” top-k routing weights
    router_indices: (4, 4)  â€” global expert IDs
        [ 52,  42, 119,  67],
        [102,  89,  61,  40],
        [ 82, 103,   4,  34],
        [ 93,  23, 109,  11],

Each index maps to a rank: index // 16 gives the owning rank.
        [3, 2, 7, 4],
        [6, 5, 3, 2],
        [5, 6, 0, 2],
        [5, 1, 6, 0],

For rank 0 (owns experts 0-15), we remap local indices with fmod and
fill non-local with sentinel=16 (used for one_hot masking):
    router_indices (rank 0):
        [ 16, 16, 16, 16],
        [ 16, 16, 16, 16],
        [ 16, 16,  4, 16],
        [ 16, 16, 16, 11],

Scores for non-local experts are zeroed out via masked_fill:
    router_scores (rank 0):
        [0.0, 0.0, 0.0, 0.0],
        [0.0, 0.0, 0.0, 0.0],
        [0.0, 0.0, 0.3, 0.0],    â†� only expert 4 (local) keeps its score
        [0.0, 0.0, 0.0, 0.1],    â†� only expert 11 (local) keeps its score

both router_scores and router_indices stay (seq, top_k) shape.
They are paired element-wise: scores[i] is the weight for indices[i].
All expert forward implementations (grouped_mm, batched_mm, eager) flatten
both with reshape(-1) and rely on this pairing. Changing the shape of one
without the other breaks routing!

Each rank believes it is alone and computes only its part of the hidden states.
The sentinel index (num_local_experts) is skipped by one_hot encoding or clamped
+ masked in grouped_mm/batched_mm. After the expert forward, an all_reduce sums
partial outputs across EP ranks to produce the full result.
rç  Nr�  zRouter module z. is missing num_experts and config.num_expertsr   z>The number of experts must be divisible by number of ep_size: rß  rà  g        rq   r   )
râ   r7   r'   r‚  r%   rÐ   r    Úmasked_fillr"   Úfmod)r  r  r  r;   Úep_rankÚep_sizerç  Únum_local_expertsÚrouter_logitsÚrouter_scoresÚrouter_indicesÚnon_local_masks               rB   r(  Ú!RouterParallel._prepare_output_fnE  sJ  € ð\ '×5Ñ5Ó7¸×9IÑ9IÓ9K�Ü˜c =°$Ó7ˆØÑÜ!¤'¨#¨x¸Ó">ÀÈtÓTˆKØÑÜ  >´$°s³)×2DÑ2DÐ1EÐEsÐ!tÓuÐuàÑ  AÓ%ÜØPÐQ\ÐP]Ð]`ÐahÐ`iÐinÐoóð ð (Ñ2ÐØ7>Ñ4ˆ nØ(Ñ=À'ÑIˆØ%×1Ñ1°.À#ÓFˆØ'×3Ñ3°NÀBÓGˆà˜qÓ Ü"ŸZšZ¨ÓJ‰Nà+×7Ñ7¸ÈÑ8JÈAÓN×ZÑZÐ[iÐlmÑ[mÐoqÓrˆNØ'×3Ñ3°NÀbÑ4HÐJ[Ó\ˆØ¨^Ð;Ð;rK   c                ó&   • US   R                  X4S9$ ro  rp  r+  s        rB   r,  ÚRouterParallel.shard_tensor‹  rÕ  rK   rÎ   r;  r<  rÖ  rg  s   @rB   rê  rê  :  sB   ø† ñõ#ò/òD<ðN VZð9Ø!ð9Ø/9ð9à	÷9ó 9rK   rê  c                  óR   ^ • \ rS rSrSrU 4S jrS rS r S     S	S jjrSr	U =r
$ )
ÚMoeTensorParalellExpertsi‘  a#  
Note: For tensor parallel, the MoEExpertsParallel TP layer handles gradient sync:
    - all_reduce_backward on hidden_states (for colwise gate_up_proj gradient)
    - all_reduce_backward on top_k_weights (for router gradient)
    - all_reduce_forward on output (for partial expert outputs)
c                ó&   >• [         TU ]  " S0 UD6  g rG  rÚ  rÛ  s     €rB   r  Ú!MoeTensorParalellExperts.__init__™  rÝ  rK   c                óT   • US   nUS   nUS   n[        XC5      n[        Xc5      nXEU4$ )Nr   r   r   rN  )r  r  r  r;   Úhidden_statesÚtop_k_indexÚtop_k_weightss          rB   r#  Ú*MoeTensorParalellExperts._prepare_input_fnœ  s@   € à˜q™	ˆØ˜Q‘iˆØ˜q™	ˆô ,¨MÓGˆô
 ,¨MÓGˆà¨MÐ:Ð:rK   c                ó   • [        X#5      $ r¼   )r  r'  s       rB   r(  Ú+MoeTensorParalellExperts._prepare_output_fn¬  s   € ä! 'Ó7Ð7rK   c                ó&   • US   R                  X4S9$ ro  rp  r+  s        rB   r,  Ú%MoeTensorParalellExperts.shard_tensor°  s   € ð
 �S‰z�}‰} Fˆ}Ð8Ð8rK   rÎ   r;  r<  rÖ  rg  s   @rB   rý  rý  ‘  s@   ø† ñõ#ò;ò 8ð
 VZð9Ø!ð9Ø/9ð9à	÷9ó 9rK   rý  c                  ó.   • \ rS rSrSrS rSS jrS rSrg)	ÚMoeIdentityExpertParalleli¸  a5  
TP class for zero/identity experts in MoE layers.

Under TP, the parent MoeTensorParalellExperts does all_reduce_forward (sum)
on the expert module output. Identity experts produce the same output on
every rank, so the sum gives world_size * output. This class divides the
input by world_size to compensate.
c                óB   • U(       a  US   OUnXCR                  5       -  $ rM  )r7   rO  s        rB   r#  Ú+MoeIdentityExpertParallel._prepare_input_fnÂ  s!   € Þ$*�v˜a’y°ˆà×.Ñ.Ó0Ñ0Ð0rK   Nc                ó&   • US   R                  X4S9$ ro  rp  r+  s        rB   r,  Ú&MoeIdentityExpertParallel.shard_tensorÇ  rr  rK   c                ó,   • [        XU R                  S9  g )N)r  )r  r#  r/  s       rB   r1  Ú+MoeIdentityExpertParallel.prepare_module_tpÊ  s   € Ü˜&¸×8NÑ8NÓOrK   rÎ   r;  )	rÐ   rÑ   rÒ   rÓ   rÔ   r#  r,  r1  rÖ   rÎ   rK   rB   r
  r
  ¸  s   † ñò1ô
9õPrK   r
  c                  óf  • \ rS rSr% \" 5       (       a`  \(       aY  \" SS9\" SS9\" SS9\" 5       \" 5       \" SS9\	" 5       \
" 5       \" 5       \" 5       \" 5       \" 5       \" 5       \" 5       \" 5       S.O0 rS	S	S	S
S
S
SSSSSS.rS\S'   S
S
S
SSSSSSSSS.rS\S'   \SS j5       r\SS j5       rSrg)ÚParallelInterfaceiÎ  r   r­  r   Trb  rž  )Úembedding_rowwiseÚembedding_colwiseÚcolwise_gather_outputÚcolwiseÚrowwiseÚrowwise_split_inputÚpacked_colwiseÚpacked_rowwiseÚsequence_parallelÚgrouped_gemmÚ	ep_routerÚmoe_tp_expertsÚmoe_identity_expertÚreplicated_with_grad_allreduceÚmla_kv_a_projrp   rq   N)r  r  r  r  r  r  r  r  r  r   r!  zdict[str, int | None]Úplan_to_weight_dimÚplan_to_bias_dimc                ó    • X R                   U'   g r¼   )r"  ©ÚclsÚkeyÚvalues      rB   Úregister_plan_to_weight_dimÚ-ParallelInterface.register_plan_to_weight_dim  s   € à&+×Ñ˜sÒ#rK   c                ó    • X R                   U'   g r¼   )r#  r%  s      rB   Úregister_plan_to_bias_dimÚ+ParallelInterface.register_plan_to_bias_dim  s   € à$)×Ñ˜SÒ!rK   rÎ   )r'  Ústrr(  r>  )rÐ   rÑ   rÒ   rÓ   r
   Ú_torch_distributed_availabler¬  rE  rŒ  r   r¦  rÉ  rØ  rê  rý  r
  ri  r~  Ú_global_mappingr"  Ú__annotations__r#  Úclassmethodr)  r,  rÖ   rÎ   rK   rB   r  r  Î  s  ‡ ñ* ×ÑÖ$@ñ! "3È!Ñ!LÙ!2È!Ñ!LÙ%4À4Ñ%HÙ&Ó(Ù&Ó(Ù#2¸tÑ#DÙ3Ó5Ù3Ó5Ù!1Ó!3Ù/Ó1Ù'Ó)Ù6Ó8Ù#<Ó#>Ù.IÓ.KÙ/Ó1ò	
ð$ ð' ð4 Ø!#ØØØ!ØØØØ!Ø*.Øñ1ÐÐ-ó ð  Ø!#ØØØ#ØØ!Ø!Ø!Ø*.Øñ/ÐÐ+ó ð ó,ó ð,ð ó*ó ó*rK   r  ÚALL_PARALLEL_STYLESc                óz  • UR                  5       nSUR                  =(       d    0 ;   a  UR                  S5      OSnUS:  a  U R                  U-   n[	        U5       Vs/ s H  n[
        R                  " U 5      PM     nn[        R                  " X`R                  5       US9  [
        R                  " XaS9$ s  snf )a^  
All-gather a sharded tensor along the specified dimension to reconstruct the full tensor.

Args:
    local_tensor: The local shard of the tensor on this rank
    shard_dim: The dimension along which the tensor was sharded
    device_mesh: The device mesh for distributed communication

Returns:
    The full reconstructed tensor (same on all ranks)
r   Nr   rF   rµ   )r7   r6   rÊ   r5   rs   r"   rã   rÆ   rä   rÅ   rå   )Úlocal_tensorÚ	shard_dimr;   r   Úprocess_grouprç   Úgathered_tensorss          rB   Úgather_full_tensorr9    s¬   € ð ×!Ñ!Ó#€Jà37¸K×<VÑ<V×<\ÐZ\Ó3]�K×)Ñ)¨$Ô/Ðcg€Mð �1ƒ}Ø ×%Ñ%¨	Ñ1ˆ	ô AFÀjÔ@QÓRÒ@Q¸1œ×(Ò(¨Ö6Ñ@QÐÐRÜ‡O‚OÐ$×&=Ñ&=Ó&?À}ÒUô �9Š9Ð%Ñ5Ð5ùò	 Ss   Á B8c                óª  • [         R                  n[         R                  n0 nU R                  5        GH  u  pxSU;   a  UR	                  SS5      S   OUn	SU;   a  UR	                  SS5      S   OSn
[
        R                  " SSU	5      n[
        R                  " SSU5      nSnXÁ;   a  X   nO.X±;   a  X   nO$SU;   a  UR	                  SS5      S   nXá;   a  X   nUb  XÔ;  a  X†U'   M¸  U
S:X  a  UR                  U5      nOUR                  U5      nUc  X†U'   Mê  [        X�U5      nUS;   a  [        UXóS	5      nUR                  5       Xg'   GM     U$ )
aþ  
Gather sharded tensors to reconstruct full tensors for saving.

This function all-gathers each sharded tensor along its shard dimension
to reconstruct the full unsharded tensor for checkpoint saving.

Args:
    state_dict: The model state dict with local sharded tensors
    tp_plan: The tensor parallel plan mapping layer patterns to shard styles
    device_mesh: The device mesh for distributed communication
    tp_size: The tensor parallel world size

Returns:
    State dict with full (gathered) tensors
rQ   r   r   Nú\d+Ú*r‘  )r  r  r   )r3  r"  r#  ÚitemsrR   rL   rM   r-   r9  r›   rÅ   )Ú
state_dictr9   r;   r:   r"  r#  Úresultr'  r…   Ú
param_nameÚ
param_typerU   Úgeneric_full_keyÚcurrent_planÚparent_param_namer6  Úfull_tensors                    rB   Úgather_state_dict_for_saverF  6  su  € ô, -×?Ñ?ÐÜ*×;Ñ;Ðà€FØ!×'Ñ'×)‰ˆà.1°S«j�S—Z‘Z  QÓ'¨Ò*¸cˆ
Ø.1°S«j�S—Z‘Z  QÓ'¨Ò*¸dˆ
ÜŸVšV F¨C°Ó<ÐäŸ6š6 &¨#¨sÓ3Ðð ˆØÓ&à"Ñ4‰LØÓ*Ø"Ñ6‰LØÐ&Ó&Ø 2× 9Ñ 9¸#¸qÓ AÀ!Ñ DÐØ Ó+Ø&Ñ9�àÑ <Ó#Ià �3‰KÙð ˜ÓØ(×,Ñ,¨\Ó:‰Ià*×.Ñ.¨|Ó<ˆIàÑà �3‰KÙô )¨¸KÓHˆØÐ?Ó?Ü(¨°iÈ!ÓLˆKØ!×,Ñ,Ó.ˆŒñQ *ðT €MrK   c           	     óö   ^^• Tb?  [         T   n UR                  TX@R                  S9  TTl        UTl        UU4S jTl        gg! [         a(  n[        R                  SU ST SU 35         SnANISnAff = f)aó  
This function is called in `PretrainedModel.post_init()`. It is responsible of adding hooks
to the modules of the `model`, based on the `PretrainedModel._tp_plan`.

This is the place where we add the `pre_forward` and `post_forwards` hooks. These are defined
for each `TensorParallelLayer` as `_prepare_input_fn` and `_prepare_output_fn`.

Args:
    model (`PretrainedModel`): The model containing the modules.
    module (`nn.Module`): The current module to which we want to add the hooks.
    current_module_plan (`str` or `None`): The tensor parallel plan for the current module, if any.
    layer_name (`str`): The qualified name of the current module.
    device_mesh (`dist.device_mesh.DeviceMesh`): The device mesh for distributed communication.

N)r�  úTrying to prepare ú0, but it's not supported. Corresponding module: z Fix it's TP plan: c                 ó.   >• TR                  5        ST  3$ )Nz

TP Plan: )Ú__repr__)Úcurrent_module_planr  s   €€rB   rI   Ú5add_tensor_parallel_hooks_to_module.<locals>.<lambda>Ÿ  s   ø€  V§_¡_Ó%6Ð$7°{ÐCVÐBWÑ"XrK   )	r3  r1  r�  r!  ÚloggerÚwarningÚ_hf_tp_planÚ_hf_device_meshrK  )Úmodelr  rL  Ú
layer_namer;   Útp_layerr?   s    ``    rB   Ú#add_tensor_parallel_hooks_to_modulerU  }  s“   ù€ ð, Ñ&Ü&Ð':Ñ;ˆð	Ø×&Ñ& v¨{Ç<Á<Ð&ÑPð 1ˆÔØ!,ˆÔÝXˆ�ð 'øô #ó 	Ü�N‰NØ$ Z LÐ0`ÐagÐ`hð iØ˜ð÷ñ ûð	ús   �A Á
A8ÁA3Á3A8c                óX  • SU;   a  UR                  SS5      OUu  p‰U R                  =(       d    0 n
U R                  U5      n[        U5      n[	        X:5      n[
        R                  " 5       S:X  a8  Uc  [        R                  SU S35        O[        R                  SU SU 35        SnUbE   [        U   nX-l
        X}l        Xml        UR                  USXFS9nU(       a  UR                  5       nOUSS R#                  U5      n[%        U[&        R(                  R*                  5      (       d+  [&        R(                  R+                  XR-                  5       S9n[/        X¹U5        Ub  UR1                  U5        U$ ! [         a!  n[!        S	U S
U SU SU 35         SnANœSnAff = f)a¦  
This function is called in `from_pretrained` when loading a model's checkpoints.
It receives the pointer to the parameter (or the parameter itself) and takes care of "sharding".
All process run this function, so they just load the partition of the tensor that they require.

Main uses cases:
- column / rowise parallelism, you just shard all the weights of the layer (weight and bias)
- packed layers: you slice the weights, then shard like above
- custom operation:
    - you want to add an all-gather at the end of a local layer.
    - you want to have a layer that is isolated from the rest of the world (because torch.DTensor does not work well with `.view` for instance)

rQ   r   r   NzTensor sharding plan for z+ not found, using default 'replicate' plan.z: )r«   rŸ   r2   rH  rI  z" Fix it's TP plan, current layer: z : )Úrequires_grad)rR   r9   Úget_submoduler*   rW   rÆ   Úget_rankrN  Úinfor3  ry   r;   r   r,  rÅ   r!  Úprintru   rd   r"   r   Ú	ParameterÚis_floating_pointÚsetattrr9  )rR  rx   ry   rS   Úparam_casting_dtypeÚis_contiguousr   r;   r@  rA  r9   Úmodule_to_tpÚcurrent_shard_planrT  r?   s                  rB   Úshard_and_distribute_modulerc  ¢  sÄ  € ð  ?BÀ^Ó>S˜^×2Ñ2°3¸Ô:ÐYgÑ€JØ�m‰m×!˜r€GØ×&Ñ& zÓ2€LÜˆt‹9€DÜ/°ÓHÐä‡}‚}ƒ˜!ÓØÑ%Ü�K‰KÐ3°J°<Ð?jÐkÕlä�K‰KÐ3°J°<¸rÐBTÐAUÐVÔWà€HØÑ%ð	Ü*Ð+=Ñ>ˆHØ#.Ô Ø#.Ô Ø ŒMØ×)Ñ)¨%¸DÐH[Ð)ÐiˆEÞØ×(Ñ(Ó*�øð ‘a�—‘Ð/Ó0ˆô �eœUŸX™X×/Ñ/×0Ñ0Ü—‘×"Ñ" 5×8UÑ8UÓ8WÐ"ÐXˆÜˆL eÔ,ØÑØ×)Ñ)¨,Ô7Ø€Løô #ó 	ÜØ$ ^Ð$4Ð4dÐeqÐdrð  sUð  V^ð  U_ð  _bð  cdð  beð  f÷ñ ûð	ús   Â0AE> Å>
F)ÆF$Æ$F)c                óœ  • Uc  gU  Vs1 s H  n[        U5      iM     nn[        U5      nUR                  5       nU H©  nSU;   a  UR                  SS5      S   OUn[        R
                  " SSU5      nXq;   a%  UR                  US5        UR                  U5        Mb  SU;   d  Mj  UR                  SS5      S   =o�;   d  M†  UR                  US5        UR                  U5        M«     [        U5      S:”  a  [        R                  SU 35        [        U5      S:”  a(  [        R                  SS	R                  U5       35        ggs  snf )
zy
Verify the TP plan of the model, log a warning if the layers that were not sharded and the rules that were not applied.
NrQ   r   r   r;  r<  z>The following TP rules were not applied on any of the layers: z'The following layers were not sharded: z, )rO   ÚsetÚcopyrR   rL   rM   ÚpopÚdiscardr‰   rN  rO  Újoin)	Úexpected_keysr9   r'  Úgeneric_keysÚunsharded_layersÚunused_rulesr@  rU   rD  s	            rB   Úverify_tp_planrn  Ù  sA  € ð
 �ØáERÓSÂ]¸cÔ4°SÖ9Á]€LÐSÜ˜<Ó(ÐØ—<‘<“>€LãˆØ.1°S«j�S—Z‘Z  QÓ'¨Ò*¸cˆ
ÜŸVšV F¨C°Ó<ÐàÓ(Ø×ÑÐ/°Ô6Ø×$Ñ$ SÖ)ØÐ&Õ&ÐAS×AZÑAZÐ[^Ð`aÓAbÐcdÑAeÐ,eÐ,=Õ+qØ×ÑÐ.°Ô5Ø×$Ñ$ SÖ)ñ ô ˆ<Ó˜1ÓÜ�‰ÐWÐXdÐWeÐfÔgÜ
ÐÓ˜qÓ Ü�‰Ð@ÀÇÁÐK[ÓA\Ð@]Ð^Õ_ð !ùò# Ts   ‰E	c                ó  • X@l         X0l        Ub;  [        U[        5      (       a  [        R
                  " U5      nX R                  l        [        U[        5      (       a  Xl        U R                  nUbŒ  [        (       a�  UR                  5        H"  nU[        ;  d  M  [        SU S[         35      e   U R                  5        H7  u  px[        USS5      (       d  [        XuSS9n	[!        U UU	UU5        SUl        M9     U $ )z,Distribute a model according to the TP plan.z"Unsupported tensor parallel style z. Supported styles are Ú
_is_hookedF)rS   r9   rT   T)Ú_tp_sizeÚ_device_meshrd   Údictr   Ú	from_dictr�  Údistributed_configr9   r/  Úvaluesr3  r    Únamed_modulesr'   rW   rU  rp  )
rR  r9   ru  r;   r:   Ú
model_planÚvrN   r  Úplans
             rB   Údistribute_modelr{  ö  s÷   € à„NØ$ÔØÑ%ÜÐ(¬$×/Ñ/Ü!2×!<Ò!<Ð=OÓ!PÐØ*<�‰Ô'ä�'œ4× Ñ ØŒØ—‘€JØÑ×">Ò">Ø×"Ñ"Ö$ˆAØÔ+Õ+Ü Ð#EÀaÀSÐH_Ô`sÐ_tÐ!uÓvÐvñ %ð "×/Ñ/Ö1‰LˆDÜ˜6 <°×7Ñ7Ü-¸TÐafÑg�Ü3ØØØØØôð !%ˆFÖñ 2ð €LrK   r;  )r9   zstr | dict[str, str] | Noner:   r>  )rN   r.  r?  r.  )T)rS   r.  r9   údict[str, str]r?  z
str | None)rg   r*   rh   zint | list[int]r?  z	list[int])r   )
rŒ   r=  r�   r*   r   r*   rŽ   r*   r?  r=  r¼   )r«   r>  r@  )r5  r=  r6  r*   r;   zdist.device_mesh.DeviceMeshr?  r=  )r>  údict[str, torch.Tensor]r9   r|  r:   r*   r?  r}  )rj  z	list[str]r9   zdict[str, str] | None)QÚ
__future__r   r¤   r    r+   rL   Ú	functoolsr   r(   r   Úutilsr   r   Úutils.genericr	   Úutils.import_utilsr
   r"   Útorch.distributedrÆ   r   Úis_availabler/  Ú
get_loggerrÐ   rN  rC   rO   rW   rd  Úuint8Úint8Úint16rv   Úbfloat16Úint32Úfloat32Úfloat64r¨   Úfloat8_e4m3fnrw   rm   r†   r›   r³   r¸   ÚautogradÚFunctionrº   rØ   rÞ   rð   rù   r  r  rä   r
  rû   r  r  rE  ri  r~  rŒ  r   r¦  r¬  rÉ  rØ  rê  rý  r
  r  r3  r1  r9  rF  rU  rc  rn  r{  rÎ   rK   rB   Ú<module>r�     s3  ðö #ã Û Û 	Û 	Ý å +ß 6Ý ,Ý 3ñ ×ÑÛÝ$Ýð $)×#4Ñ#4×#AÑ#AÓ#CÐ ð 
×	Ò	˜HÓ	%€ð dhð>,Ø(ð>,Ø3=õ>,ôBEöñ. ×Ñà—
‘
Ø�k‰kØ�j‰jØ�{‰{Ø�}‰}Ø—‘Ø�{‰{Ø�}‰}Ø�}‰}Ø�{‰{Ø×&Ñ&ñ€Lô&ò4A4ðP ð	> Ø"ð> àð> ð ð> ð ð	> ð
 õ> öBe>òP.ô4!˜Ÿ™×0Ñ0ô !ô$!˜Ÿ™×/Ñ/ô !ô/�—‘×(Ñ(ô /ôDGˆU�^‰^×$Ñ$ô GôD&G�U—^‘^×,Ñ,ô &Gò\4ò
3ò
,ò
(ò
0ð ØØð	Øðð
 õ÷"6ñ 6ôr/]Ð)ô /]ôd;Ð"5ô ;ô<-RÐ,ô -Rô`?KÐ)ô ?KôD8˜Oô 8ô,8˜Oô 8ô4N_Ð+ô N_ôb9Ð*ô 9ô2*bÐ-ô *bôZT9Ð(ô T9ôn$9Ð2ô $9ôNPÐ 3ô Pô,?*Ð(ô ?*ñD *;Ó)<Ð Ð&Ó <ð6Øð6Ø+.ð6Ø=Xð6àô6ð<DØ'ðDàðDð ð	Dð
 ôDòN"YòJ4ôn`ó:rK   