ó
    oM‡j|C  ã                   óš  • S SK Jr  S SKJrJr  S SKrS SKJr  SSK	J
r
  \(       a   \
" \5      r\ " S S5      5       r\ " S S	5      5       r\ " S
 S5      5       r\" SS9 " S S5      5       r\" SS9 " S S5      5       r\\\-  \\\   -  \\S4   -  4   r\\\   -  \\S4   -  r\\\\-  4   rS\S\R4                  S\\   4S jrg)é    )Ú	dataclass)ÚTYPE_CHECKINGÚLiteralNé   )Ú
get_loggerc                   ó  • \ rS rSr% SrSr\S-  \S'   Sr\S-  \S'   Sr	\
\S'   Sr\S	   \S
'   Sr\R                  R                   R"                  S-  \S'   Sr\
\S'   Sr\
\S'   Sr\\S'   Sr\\S'   Sr\R.                  \S'   Sr\R                  R                   R"                  \S'   Sr\R                  R                   R"                  \S'   Sr\R                  R                   R"                  \S'   Sr\R                  R                   R"                  \S'   Sr\\S'   Sr\\S'   S r\S\ \\4   4S j5       r!\S\ \"\"4   4S j5       r#S\S\S\R.                  S\R                  R                   R"                  4S jr$S r%g)!ÚContextParallelConfigé(   a3
  
Configuration for context parallelism.

Args:
    ring_degree (`int`, *optional*, defaults to `1`):
        Number of devices to use for Ring Attention. Sequence is split across devices. Each device computes
        attention between its local Q and KV chunks passed sequentially around ring. Lower memory (only holds 1/N
        of KV at a time), overlaps compute with communication, but requires N iterations to see all tokens. Best
        for long sequences with limited memory/bandwidth. Number of devices to use for ring attention within a
        context parallel region. Must be a divisor of the total number of devices in the context parallel mesh.
    ulysses_degree (`int`, *optional*, defaults to `1`):
        Number of devices to use for Ulysses Attention. Sequence split is across devices. Each device computes
        local QKV, then all-gathers all KV chunks to compute full attention in one pass. Higher memory (stores all
        KV), requires high-bandwidth all-to-all communication, but lower latency. Best for moderate sequences with
        good interconnect bandwidth.
    convert_to_fp32 (`bool`, *optional*, defaults to `True`):
        Whether to convert output and LSE to float32 for ring attention numerical stability.
    rotate_method (`str`, *optional*, defaults to `"allgather"`):
        Method to use for rotating key/value states across devices in ring attention. Currently, only `"allgather"`
        is supported.
    ulysses_anything (`bool`, *optional*, defaults to `False`):
        Whether to enable "Ulysses Anything" mode, which supports arbitrary sequence lengths and head counts that
        are not evenly divisible by `ulysses_degree`. When enabled, `ulysses_degree` must be greater than 1 and
        `ring_degree` must be 1.
    ring_anything (`bool`, *optional*, defaults to `False`):
        Whether to enable "Ring Anything" mode, which supports arbitrary sequence lengths. When enabled,
        `ring_degree` must be greater than 1 and `ulysses_degree` must be 1.
    mesh (`torch.distributed.device_mesh.DeviceMesh`, *optional*):
        A custom device mesh to use for context parallelism. If provided, this mesh will be used instead of
        creating a new one. This is useful when combining context parallelism with other parallelism strategies
        (e.g., FSDP, tensor parallelism) that share the same device mesh. The mesh must have both "ring" and
        "ulysses" dimensions. Use size 1 for dimensions not being used (e.g., `mesh_shape=(2, 1, 4)` with
        `mesh_dim_names=("ring", "ulysses", "fsdp")` for ring attention only with FSDP).

NÚring_degreeÚulysses_degreeTÚconvert_to_fp32Ú	allgather)r   ÚalltoallÚrotate_methodÚmeshFÚulysses_anythingÚring_anythingÚ_rankÚ_world_sizeÚ_deviceÚ_meshÚ_flattened_meshÚ
_ring_meshÚ_ulysses_meshÚ_ring_local_rankÚ_ulysses_local_rankc                 óÊ  • U R                   c  SU l         U R                  c  SU l        U R                   S:X  a  U R                  S:X  a  [        S5      eU R                   S:  d  U R                  S:  a  [        S5      eU R                  S:w  a  [	        SU R                   S35      eU R
                  (       a6  U R                  S:X  a  [        S5      eU R                   S:”  a  [        S5      eU R                  (       a6  U R                   S:X  a  [        S	5      eU R                  S:”  a  [        S
5      eU R
                  (       a  U R                  (       a  [        S5      eg g )Né   zfEither ring_degree or ulysses_degree must be greater than 1 in order to use context parallel inferencezF`ring_degree` and `ulysses_degree` must be greater than or equal to 1.r   z=Only rotate_method='allgather' is supported for now, but got Ú.zIulysses_degree must be greater than 1 for ulysses_anything to be enabled.z8ulysses_anything cannot be enabled when ring_degree > 1.zCring_degree must be greater than 1 for ring_anything to be enabled.z8ring_anything cannot be enabled when ulysses_degree > 1.z:ulysses_anything and ring_anything cannot both be enabled.)r   r   Ú
ValueErrorr   ÚNotImplementedErrorr   r   ©Úselfs    Ú±C:\Users\johnn\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.13_qbz5n2kfra8p0\LocalCache\local-packages\Python313\site-packages\diffusers/models/_modeling_parallel.pyÚ__post_init__Ú#ContextParallelConfig.__post_init__d   sO  € Ø×ÑÑ#Ø ˆDÔØ×ÑÑ&Ø"#ˆDÔà×Ñ˜qÓ  T×%8Ñ%8¸AÓ%=ÜØxóð ð ×Ñ˜aÓ 4×#6Ñ#6¸Ó#:ÜÐeÓfÐfØ×Ñ Ó,Ü%ØOÐPT×PbÑPbÐOcÐcdÐeóð ð × × Ø×"Ñ" aÓ'Ü Ð!lÓmÐmØ×Ñ !Ó#Ü Ð![Ó\Ð\Ø××Ø×Ñ 1Ó$Ü Ð!fÓgÐgØ×"Ñ" QÓ&Ü Ð![Ó\Ð\Ø× ×  T×%7×%7ÜÐYÓZÐZð &8Ð ó    Úreturnc                 ó2   • U R                   U R                  4$ ©N)r   r   r"   s    r$   Ú
mesh_shapeÚ ContextParallelConfig.mesh_shape�   s   € à× Ñ  $×"5Ñ"5Ð6Ð6r'   c                 ó   • g)z$Dimension names for the device mesh.©ÚringÚulysses© r"   s    r$   Úmesh_dim_namesÚ$ContextParallelConfig.mesh_dim_names…   s   € ð #r'   ÚrankÚ
world_sizeÚdevicec           	      óÐ  • Xl         X l        X0l        X@l        U R                  U R
                  -  U:”  a)  [        SU R
                   SU R                   SU S35      eU R                  S   R                  5       U l        U R                  S   U l	        U R                  S   U l
        U R                  R                  5       U l        U R                  R                  5       U l        g )NzThe product of `ring_degree` (z) and `ulysses_degree` (z") must not exceed the world size (z).r.   r/   r0   )r   r   r   r   r   r   r    Ú_flattenr   r   r   Úget_local_rankr   r   ©r#   r4   r5   r6   r   s        r$   ÚsetupÚContextParallelConfig.setupŠ   sæ   € ØŒ
Ø%ÔØŒØŒ
à×Ñ ×!1Ñ!1Ñ1°JÓ>ÜØ0°×1AÑ1AÐ0BÐBZÐ[_×[nÑ[nÐZoð  pRð  S]ð  R^ð  ^`ð  aóð ð  $Ÿz™zÐ*;Ñ<×EÑEÓGˆÔØŸ*™* VÑ,ˆŒØ!ŸZ™Z¨	Ñ2ˆÔØ $§¡× >Ñ >Ó @ˆÔØ#'×#5Ñ#5×#DÑ#DÓ#FˆÕ r'   )r   r   r   r   r   r   r   r   r   r   r   )&Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__r   ÚintÚ__annotations__r   r   Úboolr   r   r   ÚtorchÚdistributedÚdevice_meshÚ
DeviceMeshr   r   r   r   r   r6   r   r   r   r   r   r   r%   ÚpropertyÚtupler+   Ústrr2   r;   Ú__static_attributes__r1   r'   r$   r	   r	   (   s¨  ‡ ñ"ðH #€K��t‘Ó"Ø!%€N�C˜$‘JÓ%Ø €O�TÓ à6A€M�7Ð2Ñ3ÓAØ<@€Dˆ%×
Ñ
×
'Ñ
'×
2Ñ
2°TÑ
9Ó@ð #Ð�dÓ"à€M�4Óà€Eˆ3ÓØ€K�ÓØ €GˆU�\‰\Ó Ø6:€Eˆ5×Ñ×(Ñ(×3Ñ3Ó:Ø@D€O�U×&Ñ&×2Ñ2×=Ñ=ÓDØ;?€J�×!Ñ!×-Ñ-×8Ñ8Ó?Ø>B€M�5×$Ñ$×0Ñ0×;Ñ;ÓBØ Ð�cÓ Ø#Ð˜Ó#ò[ð: ð7˜E # s (™Oó 7ó ð7ð ð#  c¨3 h¡ó #ó ð#ðG˜#ð G¨3ð G¸¿¹ð GÈE×L]ÑL]×LiÑLi×LtÑLt÷ Gr'   r	   c                   ó~  • \ rS rSr% SrSr\\S'   Sr\	R                  R                  R                  S-  \S'   Sr\\S'   Sr\\S'   Sr\	R                   \S	'   Sr\	R                  R                  R                  \S
'   Sr\\S'   S rS\S\S\	R                   S\	R                  R                  R                  4S jrSrg)ÚTensorParallelConfigéœ   a†  
Configuration for tensor parallelism.

Tensor parallelism shards weight matrices (column-wise and row-wise) across devices. Each device computes a partial
result; an AllReduce/AllGather at layer boundaries reconstructs the full output. Uses
`torch.distributed.tensor.parallelize_module` with `ColwiseParallel` / `RowwiseParallel` sharding styles. Supported
device types are `"cuda"` and `"neuron"`.

Args:
    tp_degree (`int`, defaults to `1`):
        Number of devices to shard across. Must be a divisor of the number of attention heads (and FFN hidden
        dimensions) of the model being parallelised.
    mesh (`torch.distributed.device_mesh.DeviceMesh`, *optional*):
        A custom device mesh to use. If provided, `tp_degree` is inferred from `mesh.size()` and the argument is
        ignored. Useful when combining TP with other parallelism strategies (e.g. CP) that share the same mesh.
r   Ú	tp_degreeNr   r   r   r   r   Ú
_tp_degreec                 ó:   • U R                   S:  a  [        S5      eg )Nr   z`tp_degree` must be >= 1.)rP   r    r"   s    r$   r%   Ú"TensorParallelConfig.__post_init__¸   s   € Ø�>‰>˜AÓÜÐ8Ó9Ð9ð r'   r4   r5   r6   c                 ó^   • Xl         X l        X0l        X@l        UR	                  5       U l        g r*   )r   r   r   r   ÚsizerQ   r:   s        r$   r;   ÚTensorParallelConfig.setup¼   s$   € ØŒ
Ø%ÔØŒØŒ
ØŸ)™)›+ˆ�r'   )r   r   r   rQ   r   )r=   r>   r?   r@   rA   rP   rB   rC   r   rE   rF   rG   rH   r   r   r   r6   r   rQ   r%   r;   rL   r1   r'   r$   rN   rN   œ   s¸   ‡ ñð" €IˆsÓØ<@€Dˆ%×
Ñ
×
'Ñ
'×
2Ñ
2°TÑ
9Ó@à€Eˆ3ÓØ€K�ÓØ €GˆU�\‰\Ó Ø6:€Eˆ5×Ñ×(Ñ(×3Ñ3Ó:Ø€J�Óò:ð&˜#ð &¨3ð &¸¿¹ð &ÈE×L]ÑL]×LiÑLi×LtÑLt÷ &r'   rN   c            
       óH  • \ rS rSr% SrSr\S-  \S'   Sr\	S-  \S'   Sr
\\S'   Sr\\S'   Sr\R                  \S'   Sr\R"                  R$                  R&                  \S	'   S
 rSS.S\S\S\R                  S\R"                  R$                  R&                  S-  4S jjrSrg)ÚParallelConfigéÄ   a  
Configuration for applying different parallelisms.

Args:
    context_parallel_config (`ContextParallelConfig`, *optional*):
        Configuration for context parallelism.
    tensor_parallel_config (`TensorParallelConfig`, *optional*):
        Configuration for tensor parallelism.
NÚcontext_parallel_configÚtensor_parallel_configr   r   r   r   c                 óP   • U R                   b  U R                  b  [        S5      eg g )NzµCombining context parallelism and tensor parallelism in a single `ParallelConfig` is not supported. Please specify only one of `context_parallel_config` or `tensor_parallel_config`.)rZ   r[   r    r"   s    r$   r%   ÚParallelConfig.__post_init__Ø   s5   € Ø×'Ñ'Ñ3¸×8SÑ8SÑ8_Üðdóð ð 9`Ð3r'   )r   r4   r5   r6   r   c                óÚ   • Xl         X l        X0l        X@l        U R                  b  U R                  R                  XX45        U R                  b  U R                  R                  XX45        g g r*   )r   r   r   r   rZ   r;   r[   r:   s        r$   r;   ÚParallelConfig.setupß   sb   € ð Œ
Ø%ÔØŒØŒ
Ø×'Ñ'Ñ3Ø×(Ñ(×.Ñ.¨tÀÔNØ×&Ñ&Ñ2Ø×'Ñ'×-Ñ-¨dÀÕMð 3r'   )r   r   r   r   )r=   r>   r?   r@   rA   rZ   r	   rC   r[   rN   r   rB   r   r   rE   r6   r   rF   rG   rH   r%   r;   rL   r1   r'   r$   rX   rX   Ä   sÇ   ‡ ñð =AÐÐ2°TÑ9Ó@Ø:>ÐÐ0°4Ñ7Ó>à€Eˆ3ÓØ€K�ÓØ €GˆU�\‰\Ó Ø6:€Eˆ5×Ñ×(Ñ(×3Ñ3Ó:òð AEòNàðNð ðNð —‘ð	Nð ×Ñ×+Ñ+×6Ñ6¸Ñ=÷Nð Nr'   rX   T)Úfrozenc                   óL   • \ rS rSr% Sr\\S'   Sr\S-  \S'   Sr\	\S'   S r
S	rg)
ÚContextParallelInputéñ   a³  
Configuration for splitting an input tensor across context parallel region.

Args:
    split_dim (`int`):
        The dimension along which to split the tensor.
    expected_dims (`int`, *optional*):
        The expected number of dimensions of the tensor. If provided, a check will be performed to ensure that the
        tensor has the expected number of dimensions before splitting.
    split_output (`bool`, *optional*, defaults to `False`):
        Whether to split the output tensor of the layer along the given `split_dim` instead of the input tensor.
        This is useful for layers whose outputs should be split after it does some preprocessing on the inputs (ex:
        RoPE).
Ú	split_dimNÚexpected_dimsFÚsplit_outputc                 óV   • SU R                    SU R                   SU R                   S3$ )NzContextParallelInput(split_dim=ú, expected_dims=z, split_output=Ú))rd   re   rf   r"   s    r$   Ú__repr__ÚContextParallelInput.__repr__  sK   € Ø0°·±Ð0@Ð@PÐQU×QcÑQcÐPdÐdsÐtx÷  uFñ  uFð  tGð  GHð  Ið  	Ir'   r1   )r=   r>   r?   r@   rA   rB   rC   re   rf   rD   rj   rL   r1   r'   r$   rb   rb   ñ   s,   ‡ ñð ƒNØ $€M�3˜‘:Ó$Ø€L�$ÓõIr'   rb   c                   ó>   • \ rS rSr% Sr\\S'   Sr\S-  \S'   S rSr	g)ÚContextParallelOutputi
  a†  
Configuration for gathering an output tensor across context parallel region.

Args:
    gather_dim (`int`):
        The dimension along which to gather the tensor.
    expected_dims (`int`, *optional*):
        The expected number of dimensions of the tensor. If provided, a check will be performed to ensure that the
        tensor has the expected number of dimensions before gathering.
Ú
gather_dimNre   c                 ó<   • SU R                    SU R                   S3$ )Nz!ContextParallelOutput(gather_dim=rh   ri   )rn   re   r"   s    r$   rj   ÚContextParallelOutput.__repr__  s&   € Ø2°4·?±?Ð2CÐCSÐTX×TfÑTfÐSgÐghÐiÐir'   r1   )
r=   r>   r?   r@   rA   rB   rC   re   rj   rL   r1   r'   r$   rm   rm   
  s"   ‡ ñ	ð ƒOØ $€M�3˜‘:Ó$õjr'   rm   .rU   Úgroupr(   c           	      óø  • [         R                  " US9n[        [         R                  " US95      nSU;   a  SO[        R
                  R                  5       n[        U5       Vs/ s H'  n[        R                  " SU[        R                  S9PM)     nn[         R                  " U[        R                  " U /U[        R                  S9US9  U Vs/ s H  owS   R                  5       PM     nnU$ s  snf s  snf )zkGather the local size from all ranks.
size: int, local size return: list[int], list of size from all ranks
)rq   Úcpu)r   )r6   Údtyper   )ÚdistÚget_world_sizerK   Úget_backendrE   ÚacceleratorÚcurrent_acceleratorÚrangeÚemptyÚint64Ú
all_gatherÚtensorÚitem)rU   rq   r5   Úcomm_backendsÚgather_deviceÚ_Úgathered_sizesÚss           r$   Úgather_size_by_commr…   X  sÍ   € ô" ×$Ò$¨5Ñ1€Jäœ×(Ò(¨uÑ5Ó6€Mà" mÓ3‘E¼×9JÑ9J×9^Ñ9^Ó9`€MÜZ_Ð`jÔZkÓlÒZkÐUV”e—k’k $¨}ÄEÇKÁKÔPÑZk€NÐlÜ‡O‚OØÜ�Š�d�V M¼¿¹ÑEØòñ ,:Ó:ª> a˜‘d—i‘i–k©>€NÐ:ð Ðùò mùò ;s   Á%.C2ÃC7)Údataclassesr   Útypingr   r   rE   Útorch.distributedrF   ru   Úutilsr   r=   Úloggerr	   rN   rX   rb   rm   ÚdictrK   rB   ÚlistrJ   ÚContextParallelInputTypeÚContextParallelOutputTypeÚContextParallelModelPlanÚProcessGroupr…   r1   r'   r$   Ú<module>r‘      s\  ðõ$ "ß )ã Ý  å ö Øñ 
�HÓ	€ð ÷pGð pGó ðpGðf ÷$&ð $&ó ð$&ðN ÷)Nð )Nó ð)NñX �$Ñ÷Ið Ió ðIñ0 �$Ñ÷jð jó ðjð0  Øˆ#�IÐ# dÐ+?Ñ&@Ñ@À5ÐI]Ð_bÐIbÑCcÑcÐcñÐ ð 2°DÐ9NÑ4OÑOÐRWÐXmÐorÐXrÑRsÑsÐ ð   Ð%=Ð@YÑ%YÐ YÑZÐ ðV ˜cð  ¨$×*;Ñ*;ð  ÀÀSÁ	õ  r'   