+
    –°³je\ ã                   ó  a € R@ tX0 t ^ RIt^ RIt^ RIt^ RIt^ RIt^ RIt^ RIHt ^ RI	H
t
 ^ RIHt ^ RIHtHtHt ^ RIt^ RIHu Ht ^ RIHu Hu Ht ^ RIHt ^ RIHt ^ RIHt ^ R	IH t H!t!H"t"H#t#H$t$ ^ R
I%H&t& ^ RI'H(t( ^ RI)H*t*H+t+H,t,H-t-H.t.H/t/ ^ RI0H1t1H2t2 ^ RI3H4t4 ^ RI5H6t6 ]Pn                  ! ]84      t9Rs:] ^ k Rs;] ^k R R lt<]Pz                  RAR R ll4       t>]Pz                  RAR R ll4       t?]P€                  ! RRR7       ! R R4      4       tA]P€                  ! RRR7       ! R R]A4      4       tBR R ltCR R  ltDR! R" ltE]F! 4       tG] ^k R# R$ ltHR% R& ltI/ tJ] ^k R' R( ltKR) R* ltL ! R+ R,4      tMRBR- R. lltN]RBR/ R0 ll4       tOR1RR2RR3R/R4 R5 lltPR1R/R6 R7 lltQ ! R8 R9]4      tR ! R: R;]4      tS ! R< R=]P¨                  Pª                  4      tV ! R> R?]P¨                  Pª                  4      tWR# )Cé    N)Údefaultdict)ÚSequence)Úcache)ÚAnyÚcastÚ	TypedDict)Ú_are_we_tracing)Ú_MeshLayout©Úone_step_redistribute_cost)Ú_StridedShardNotDecodableErrorÚDTensorSpecÚ
ShardOrderÚShardOrderEntryÚ
TensorMeta)Úassert_no_mixed_partial_types)Ú
DeviceMesh)Ú_is_shard_likeÚ_StridedShardÚPartialÚ	PlacementÚ	ReplicateÚShard)ÚFloatLikeTypeÚIntLikeType)Úget_active_debug_mode)Únot_noneFc                ó0   € V ^8„  d   QhR\         R\        /# )é   ÚcostÚreturn)r   Úfloat)Úformats   "Úg/home/luca/screen-checking/.venv/lib/python3.14/site-packages/torch/distributed/tensor/_redistribute.pyÚ__annotate__r%   9   s   € ÷ Cñ C¤mð C¼ñ Có    c                 óä  € \        V \        4      '       d   V # \        V \        P                  4      '       d   V P                  P
                  pM\        V 4      # VP                  pV'       g   \        V4      # \        V P                  P                  4      pVP                  pVP                  V4      '       d   \        VP                  V4      4      # \        VP                  VR R7      4      # )N)Úfallback)Ú
isinstancer"   ÚtorchÚSymFloatÚnodeÚexprÚfree_symbolsr   Ú	shape_envÚvar_to_hint_overrideÚissubsetÚxreplaceÚoptimization_hint)r    r-   r.   r/   Úhint_overridess   &    r$   Ú_redistribute_cost_sort_keyr5   9   s³   € Ü�$œ×ÒØˆÜ�$œŸ™×'Ò'Ø�y‰y�~‰~‰ä�T‹{Ðà×$Ñ$€LßÜ�T‹{Ðä˜Ÿ™×,Ñ,Ó-€IØ×3Ñ3€NØ×Ñ˜^×,Ò,Ü�T—]‘] >Ó2Ó3Ð3ä�×,Ñ,¨T¸DÐ,ÓAÓBÐBr&   Tc                ó$   € V ^8„  d   QhR\         /# )r   Úenabled©Úbool)r#   s   "r$   r%   r%   N   s   € ÷ 98ñ 98¬dñ 98r&   c              #  ó:   "  € \         pV s  Rx € Vs R#   Ts i ; i5i)uÌ  
Context manager to control the redistribution planning strategy for DTensor operations.

This context manager allows you to choose between two algorithms for computing the
sequence of collective operations needed to redistribute a DTensor from one placement
to another:

- **Graph-based**: Uses Dijkstra's algorithm to find the minimum-cost path
  through all possible placement transformations. This approach considers the global
  cost of all collective operations and finds the optimal sequence. Best for complex
  redistribution patterns where reducing communication cost and memory overhead is critical.

- **Greedy**: Uses a heuristic approach that makes locally optimal choices
  at each step. This is faster to compute but may not produce the globally optimal
  transformation sequence. Best for simple redistribution patterns or when planning
  speed is more important than optimal communication.

**Default Behavior (without this context manager):**

When this context manager is NOT used, the algorithm selection follows this priority:

1. **Non-default shard orders**
   â†’ Always use graph-based algorithm (required for correctness)

2. **Explicit `use_graph_based_transform` parameter** to `_gen_transform_infos_non_cached`
   â†’ Use the specified algorithm (True = graph-based, False = greedy)

3. **No explicit parameter** (default case)
   â†’ Use greedy algorithm for faster planning

**Behavior with this context manager:**

This context manager overrides the default selection by setting the global flag
`_FORCE_MIN_COST_REDISTRIBUTION_PLAN`, which takes precedence over the explicit
`use_graph_based_transform` parameter (but not over non-default shard order requirements).

**Cache Considerations:**

The redistribution planner caches transform info for performance via the `@cache`
decorator on `_gen_transform_infos`. If you need to change the algorithm selection
for the same input specs, clear the cache using `_gen_transform_infos.cache_clear()`
to ensure the new setting takes effect and doesn't reuse cached results from a
previous run.

Args:
    enabled (bool): If True, forces the use of the graph-based algorithm.
                   If False, forces the use of the greedy algorithm.
                   Default: True
N)Ú#_FORCE_MIN_COST_REDISTRIBUTION_PLAN)r7   Ú	old_values   & r$   Ú use_min_cost_redistribution_planr=   M   s'   é € ôj 4€IØ*1Ð'ð8Ûà.7Ò+ø¨iÑ+üó   ‚	Œ �”˜c                ó$   € V ^8„  d   QhR\         /# )r   Údisabledr8   )r#   s   "r$   r%   r%   ‹   s   € ÷ Añ A¼$ñ Ar&   c              #  ó:   "  € \         pV s  Rx € Vs R#   Ts i ; i5i)a£  
Context manager to disable the transform optimization pass that merges
consecutive same-type collectives into single flattened operations.

When the optimization is disabled, ``_optimize_transform_infos`` becomes a
no-op and returns the original list of ``_TransformInfo`` objects unchanged.
This is useful for debugging or isolating issues related to the flattened
collective merging logic.

The flag can also be set directly::

    torch.distributed.tensor._redistribute._DISABLE_REDISTRIBUTE_TRANSFORM_OPTIMIZATION = True

Args:
    disabled (bool): If True (default), disables the optimization.
                     If False, explicitly enables it (the normal default).
N)Ú,_DISABLE_REDISTRIBUTE_TRANSFORM_OPTIMIZATION)r@   r<   s   & r$   Ú+disable_redistribute_transform_optimizationrC   Š   s'   é € ô* =€IØ3;Ð0ðAÛà7@Ò4ø°yÑ4ür>   ©ÚfrozenÚslotsc                   óD   a € ] tR t^§t o R tV 3R lR ltV 3R ltRtV tR# )Ú_TransformInfoc                óœ   € V P                   ^ 8  d   \        hV P                  ^ ,          V P                  ^,          8X  d   \        R4      hR# )r   zQTransformInfo should only be created if it is an op with some effect, not a no-opN)Úmesh_dimÚAssertionErrorÚsrc_dst_placements©Úselfs   &r$   Ú__post_init__Ú_TransformInfo.__post_init__®   sH   € Ø�=‰=˜1ÔÜ Ð Ø×"Ñ" 1Õ%¨×)@Ñ)@ÀÕ)CÔCÜ Øcóð ñ Dr&   c                ó.   <€ V ^8„  d   QhRS[ R,          /# ©r   r!   N©Ústr)r#   Ú__classdict__s   "€r$   r%   Ú_TransformInfo.__annotate__¶   s   ø€ ÷ ñ ¡ d¥
ñ r&   c                ój  € V P                   w  rVP                  4       '       d   VP                  4       '       d   R# VP                  4       '       d   \        V4      '       d   R# \        V4      '       d   VP                  4       '       d   R# \        V4      '       d   \        V4      '       d   R# R# )zÄ
Return a key for grouping transforms by communication type.

Returns None for local ops (no communication needed), or a string
that identifies the collective type for potential grouping/merging.
Ú
all_reduceÚreduce_scatterÚ
all_gatherÚ
all_to_allN)rL   Ú
is_partialÚis_replicater   )rN   ÚsrcÚdsts   &  r$   Ú_comm_type_keyÚ_TransformInfo._comm_type_key¶   s‚   € ð ×*Ñ*‰ˆØ�>‰>×Ò × 0Ñ 0× 2Ò 2ÙØ�^‰^×Ò¤.°×"5Ò"5Ù#Ü˜C× Ò  S×%5Ñ%5×%7Ò%7ÙÜ˜C× Ò ¤^°C×%8Ò%8Ùñ r&   c                ód   <€ V ^8„  d   Qh/ S[ ;R&   S[S[S[3,          ;R&   S[S[,          ;R&   # )r   rJ   rL   Úlogical_shape)ÚintÚtupler   r   r   )r#   rU   s   "€r$   r%   rV   §   s8   ø‡ ‚ á�Mñ ñ ™i©Ð2Õ3Ñ3ñ ñ
 ™KÕ(Ñ(ò r&   © N)	Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__rO   r`   Ú__annotate_func__Ú__static_attributes__Ú__classdictcell__©rU   s   @r$   rH   rH   §   s   ø‡ € ò÷ð ÷ ƒ r&   rH   c                   óF   a € ] tR t^Ët o RtRtV 3R lR ltV 3R ltRtV t	R# )Ú_FlattenedTransformInfoa   
Represents a flattened transform that combines multiple mesh dimensions
into a single collective operation using a flattened DeviceMesh.

Note: inherits the fields from _TransformInfo. Gets an __init__ with parent fields, followed by child fields,
and runs parent validation (post_init)
Nc                ó   <€ V ^8„  d   QhRR/# rR   rf   )r#   rU   s   "€r$   r%   Ú$_FlattenedTransformInfo.__annotate__Ý   s   ø€ ÷ ñ ˜tñ r&   c                ó¢   € \         P                  V 4       V P                  e,   V P                  ^8”  g   \        RV P                   24      hR # R # )Nz"avg_scale must be > 1 if set, got )rH   rO   Ú	avg_scalerK   rM   s   &r$   rO   Ú%_FlattenedTransformInfo.__post_init__Ý   sL   € Ü×$Ñ$ TÔ*Ø�>‰>Ò%Ø—>‘> AÔ%Ü$Ø8¸¿¹Ð8HÐIóð ñ &ñ &r&   c                ó`   <€ V ^8„  d   Qh/ S[ ;R&   S[S[R3,          ;R&   S[R,          ;R&   # )r   Úmesh.Úoriginal_mesh_dimsNrt   ©r   re   rd   )r#   rU   s   "€r$   r%   rr   Ë   s8   ø‡ ‚ ñ Ññ ñ ™c 3˜h�Ñ'ñ ñ  �T�zÑ ò! r&   rf   )
rg   rh   ri   rj   Ú__doc__rt   rO   rk   rl   rm   rn   s   @r$   rp   rp   Ë   s"   ø‡ € ñð !€I÷ð ÷% ƒ r&   rp   c          	      óŽ   € V ^8„  d   QhR\         R\        \        ,          R\        \        \        \        ,          3,          RR/# )r   Útransform_infoÚcurrent_placementsÚshard_order_dictr!   N)rH   Úlistr   Údictrd   )r#   s   "r$   r%   r%   æ   sA   € ÷ .5ñ .5Ü"ð.5äœY�ð.5ô œ3¤¤S¥	˜>Õ*ð.5ð 
ñ	.5r&   c                óÔ  € V P                   w  r4\        V \        4      '       d   V P                  pMV P                  3p\        V\
        \        ,          4      '       d¥   VP                  p\        4       pV FU  p\        W&,          4      ^ 8X  d   \        RV RV  RV RV 24      hVP                  W&,          P                  4       4       KW  	  \        V4      V8X  g$   \        R\        V4       RV RV  RV RV 2
4      h\        V\
        \        ,          4      '       d7   VP                  p	W’9  d   . W)&   V F  p
W),          P                  V
4       K  	  V F  p
WAV
&   K	  	  R# )zk
Update current_placements and shard_order_dict in-place to reflect the
effect of a single transform step.
z?Invalid shard_order update. No entries left to pop for src_dim z. transform_info=z, current_placements=z, shard_order=z^Mismatch between expected and removed mesh dims during shard_order update. Expected to remove z, but removed N)rL   r)   rp   rx   rJ   r   r   ÚdimÚsetÚlenÚ
ValueErrorÚaddÚpopÚappend)r|   r}   r~   Úsrc_placementÚdst_placementÚ	mesh_dimsÚsrc_dimÚremoved_dimÚ_Údst_dimrJ   s   &&&        r$   Ú"_update_shard_order_and_placementsr�   æ   s  € ð $2×#DÑ#DÑ €Mä�.Ô"9×:Ò:Ø"×5Ñ5‰	à#×,Ñ,Ð.ˆ	ä�-¤¬Õ!6×7Ò7Ø×#Ñ#ˆÜ“eˆÛˆAÜÐ#Õ,Ó-°Ô2Ü ØUØ�iÐ0°Ð0@ð A*Ø*<Ð)=ð >#Ø#3Ð"4ð6óð ð �O‰OÐ,Õ5×9Ñ9Ó;Ö<ñ ô �9‹~ Ô,Üð.ä�y“>Ð" .°°ð >"Ø"0Ð!1ð 2&Ø&8Ð%9ð :Ø/Ð0ð2óð ô �-¤¬Õ!6×7Ò7Ø×#Ñ#ˆØÔ*Ø(*ÐÑ%Û!ˆHØÕ%×,Ñ,¨XÖ6ñ "ó ˆØ'4˜8Ó$ó r&   c                ód   € V ^8„  d   QhR\         R\        \        R3,          R\         R,          /# ©r   rw   r‹   .r!   Nry   )r#   s   "r$   r%   r%     s1   € ÷ ñ Ü
ðÜ!&¤s¨C x¥ðä�$Õñr&   c                ór  a€ V P                  4       pV P                  oSf   R# \        ;QJ d    . V3R lV 4       F  NK  	  5M! V3R lV 4       4      pV P                  V4      p\	        VP                  4       .4      pVP                  P                  4        F  pVP                  V8X  g   K  Vu # 	  R# )zÙ
Query for an explicitly created flattened mesh using layout comparison.

Searches root_mesh._flatten_mapping for a mesh whose layout matches
the expected flattened layout for the given dims. Pure Python layout math.
Nc              3   ó6   <"  € T F  pSV,          x € K  	  R # 5i©Nrf   )Ú.0ÚiÚmesh_dim_namess   & €r$   Ú	<genexpr>Ú5_get_flattened_mesh_by_layout_impl.<locals>.<genexpr>'  s   øé € Ð;±¨A�n Q×'Ò'³ùs   ƒ)	Ú_get_root_meshr˜   re   Ú_get_slice_mesh_layoutr
   ÚcollapseÚ_flatten_mappingÚvaluesÚ_layout)rw   r‹   Ú	root_meshÚ	dim_namesÚsliced_layoutÚexpected_layoutÚflattened_meshr˜   s   &&     @r$   Ú"_get_flattened_mesh_by_layout_implr¦     s£   ø€ ð ×#Ñ#Ó%€IØ×(Ñ(€NàÒÙ÷ ”Ô;±Ó;—‘Ô;±Ó;Ó;€Ið ×/Ñ/°	Ó:€MÜ! =×#9Ñ#9Ó#;Ð"<Ó=€Oð $×4Ñ4×;Ñ;Ö=ˆØ×!Ñ! _Ö4Ø!Ò!ñ >ñ r&   c                ód   € V ^8„  d   QhR\         R\        \        R3,          R\         R,          /# r’   ry   )r#   s   "r$   r%   r%   6  s1   € ÷ ?ñ ?Ü
ð?Ü!&¤s¨C x¥ð?ä�$Õñ?r&   c                ó  € ^ RI p\        4       '       dk   VP                  P                  P                  '       dE   \        W4      f   R# ^ RIHp VP                  P                  P                  V \        V4      4      # \        W4      # )a*  
Query for an explicitly created flattened mesh using layout comparison.

When tracing with compile_on_one_rank, delegates to a custom op so the
flattened mesh appears as a call_function node derived from mesh (a graph
input) rather than as a get_attr constant holding an unpicklable
ProcessGroup.
N)Údevice_mesh)Útorch.compiler.configr	   ÚcompilerÚconfigÚcompile_on_one_rankr¦   Útorch.distributed._opsr©   ÚopsÚ_get_flattened_submeshr   )rw   r‹   r*   rŽ   s   &&  r$   Ú_get_flattened_mesh_by_layoutr±   6  sd   € ó !ä×Ò˜UŸ^™^×2Ñ2×F×FÐFô .¨dÓ>ÒFÙÝ;à�y‰y×$Ñ$×;Ñ;¸DÄ$ÀyÃ/ÓRÐRä-¨dÓ>Ð>r&   c                ó¾   € V ^8„  d   QhR\         R\        \        R3,          R\        \        R3,          R\        \        R3,          R\        R\        R\        R	R
/# )r   r©   r‹   .Úsrc_placementsÚdst_placementsÚnum_opsÚ	comm_typeÚreasonr!   N)r   re   rd   r   rT   )r#   s   "r$   r%   r%   S  sr   € ÷ 9ñ 9Üð9ä”S˜#�X�ð9ô œ) S˜.Õ)ð9ô œ) S˜.Õ)ð	9ô
 ð9ô ð9ô ð9ð 
ñ9r&   c                óÄ  € \        V 4      W3pV\        9   d   R# \        P                  V4       V P                  pVe1   V U	u. uF  q˜V	,          NK  	  p
p	RP	                  R V
 4       4      pMRRP	                  R V 4       4       RV  2pRpVR8X  d   R	V R
2pM&VR8X  d   RpMVR8X  d   RV R2pM\        RV 24      h\        P                  WÂW4W]4       R# u up	i )a  
Warn once per (mesh, dims, reason) about inability to flatten operations.

Args:
    device_mesh: The device mesh being used
    mesh_dims: Tuple of mesh dimensions that could not be flattened
    src_placements: Source placements for the redistribution
    dst_placements: Target placements for the redistribution
    num_ops: Number of sequential operations that will be performed
    comm_type: Type of collective operation (e.g., "reduce_scatter")
    reason: Either "no_flattened_mesh" or "uneven_tensor_shape"
Nz, c              3   ó.   "  € T F  pR V R 2x € K  	  R# 5i)Ú"Nrf   )r–   Únames   & r$   r™   Ú:_warn_flatten_optimization_not_possible.<locals>.<genexpr>p  s   é € Ð?±Y¨T˜q   a�[³Yùs   ‚zdims c              3   ó8   "  € T F  p\        V4      x € K  	  R # 5ir•   rS   )r–   Úds   & r$   r™   r¼   r  s   é € Ð$?±Y°¤S¨§V V³Yùó   ‚z of a%  While redistributing from %s to %s, %d sequential %s operations will be performed. This is suboptimal: multiple collective operations have higher latency (separate kernel launches and synchronization points) and may give inconsistent results between ranks due to different reduction orders. %sÚno_flattened_meshz&To optimize, flatten mesh dimensions [z0] so DTensor can use a single operation instead.Úuneven_tensor_shapeÚnon_ascending_mesh_dimsz0it is not possible to merge non-ascending order z operations.zUnexpected reason: )zÀ Unfortunately, because the tensor dimension is not evenly divisible by the product of the mesh dim sizes that would need to be flattened for the optimization to work, it can not be optimized.)ÚhashÚ_warned_flatten_issuesr†   r˜   ÚjoinrK   ÚloggerÚwarning)r©   r‹   r³   r´   rµ   r¶   r·   Ú	cache_keyr˜   r¾   r¢   Údims_strÚcommon_warningÚ
reason_msgs   &&&&&&&       r$   Ú'_warn_flatten_optimization_not_possiblerÌ   S  s  € ô* �kÓ" IÐ6€IØÔ*Ô*ÙÜ×Ñ˜yÔ)à ×/Ñ/€NØÒ!Ù09Ó:±	¨1 A×&Ð&±	ˆ	Ð:Ø—9‘9Ñ?±YÓ?Ó?‰à˜4Ÿ9™9Ñ$?±YÓ$?Ó?Ð@ÀÀ[ÀMÐRˆð	`ð ð Ð$Ô$Ø=¸h¸ZÐGwÐx‰
Ø	Ð(Ô	(ð
‰
ð 
Ð,Ô	,à>¸y¸kÈÐVñ 	ô Ð2°6°(Ð;Ó<Ð<ä
‡N�NØ¨Àöùò7 ;s   ÁCc                óÊ   € V ^8„  d   QhR\         \        ,          R\        R\        \        R3,          R\        \        R3,          R\         \        \
        ,          ,          /# )r   Útransform_infosr©   r³   .r´   r!   )r   rH   r   re   r   rp   )r#   s   "r$   r%   r%   �  sc   € ÷ pñ pÜœ.Õ)ðpäðpô œ) S˜.Õ)ðpô œ) S˜.Õ)ð	pô
 
Œ.Ô2Õ
2Õ3ñpr&   c           	     ól  aaa€ \        V 4      ^8  d   V # \        '       d   V # \        0 R	m4      oR V3R llpR R loR VV3R llp. p^ pV\        V 4      8  Ed@   W,          pVP                  4       p	V! V	4      '       g   VP	                  V4       V^,          pKS  VP
                  p
V.pV^,           pV\        V 4      8  dd   V! W,          P                  4       4      '       dB   S! W,          P
                  V
4      '       d#   VP	                  W,          4       V^,          pKs  V! V4      w  rÞVe   VP	                  V4       MMVP                  V4       VR
9   d6   \        \        R V 4       4      4      p\        SVVV\        V4      V	V4       TpEKP  \        P                  RW4       V# )at  
Optimize transform infos by merging consecutive same-type collectives into
a single flattened operation when a matching flattened DeviceMesh exists.

Merging requirements:
- Operations must be consecutive in the transform list (no reordering).
  Notably, redistributing from P, P, P -> R, S, R is not optimized here and cannot be optimized due to
  optimization needing to fuse non-contiguous reductions, leaving this pattern vulnerable to numerics issues and
  suboptimal perf
- Operations must have the same comm type (e.g., all allgather or all reduce_scatter)
- Operations must have identical src_dst_placements (e.g., can't merge
  Partial->Shard(0) with Partial->Shard(1))
- A flattened mesh covering the relevant dimensions must exist
- For reduce_scatter, tensor dim must be evenly divisible by flattened mesh size

For nested sharding, the merged operation uses the logical_shape from the
outermost mesh dimension (smallest mesh_dim index) which represents the
global tensor shape needed for correct padding/unpadding.

TODO:
- all_to_all operations are excluded from merging, but it may be possible to merge them in some cases.

c                ó>   € V ^8„  d   QhR\         R,          R\        /# )r   ÚkeyNr!   )rT   r9   )r#   s   "r$   r%   Ú/_optimize_transform_infos.<locals>.__annotate__µ  s   € ÷ +ñ +œ# �*ð +¬ñ +r&   c                ó   <€ V S9   # )z:Check if a comm type key represents a mergeable operation.rf   )rÑ   ÚMERGEABLE_COMM_TYPESs   &€r$   Úis_mergeableÚ/_optimize_transform_infos.<locals>.is_mergeableµ  s   ø€ àÐ*Ñ*Ð*r&   c                ó€   € V ^8„  d   QhR\         \        \        3,          R\         \        \        3,          R\        /# )r   Úp1Úp2r!   )re   r   r9   )r#   s   "r$   r%   rÒ   ¹  s8   € ÷ 
ñ 
Ü”)œYÐ&Õ'ð
Ü-2´9¼iÐ3GÕ-Hð
ä	ñ
r&   c                ó"  € W8X  d   R# V w  r#Vw  rEW58w  d   R# VP                  4       '       d   VP                  4       '       g   R# \        \        V4      p\        \        V4      pRR0pVP                  V9   ;'       d    VP                  V9   # )z¿
Check if two src_dst_placements can be merged.

Allows merging of Partial("sum") and Partial("avg") since they can be
combined: perform sum reduction, then scale by avg mesh dims afterward.
TFÚsumÚavg)r\   r   r   Ú	reduce_op)	rØ   rÙ   Úsrc1Údst1Úsrc2Údst2Úpartial1Úpartial2Úmergeable_reduce_opss	   &&       r$   Úare_placements_mergeableÚ;_optimize_transform_infos.<locals>.are_placements_mergeable¹  s“   € ð Œ8Ùà‰
ˆØ‰
ˆð Œ<Ùð —‘×!Ò! d§o¡o×&7Ò&7Ùô œ Ó&ˆÜœ Ó&ˆØ % u˜~Ðà×ÑÐ"6Ñ6÷ ;ð ;Ø×"Ñ"Ð&:Ñ:ð	
r&   c                ó„   € V ^8„  d   QhR\         \        ,          R\        \        R,          \        R,          3,          /# )r   Úinfosr!   N)r   rH   re   rp   rT   )r#   s   "r$   r%   rÒ   Ù  s9   € ÷ i
ñ i
Ü”NÕ#ði
ä	Ô&¨Õ-¬s°T­zÐ9Õ	:ñi
r&   c           	     ó‚  <aa€ \        V 4      ^8  d   R# V ^ ,          P                  oV ^ ,          P                  4       p\        ;QJ d     VV3R lV  4       F  '       d   K   RM	  RM! VV3R lV  4       4      '       g   \	        R4      h\
        ;QJ d    . R V  4       F  NK  	  5M! R V  4       4      p\        \        V4      4      pVR8X  d
   W#8w  d   R# MVR8X  d   W#RRR1,          8w  d   R# \        SV4      pVf   R# Sw  rVVR8X  d-   \        \        V4      P                  o\        V V3R	 lR
7      pM”VR8X  do   \        \        V4      P                  o\        V V3R lR
7      pVP                  S,          p\        P                  ! V3R lV  4       4      p	W‰,          ^ 8w  d   R# MVR8X  d   V ^ ,          pM\        RV 24      hRp
TpVP!                  4       '       d5   \        P                  ! V3R lV  4       4      pV^8”  d   Tp
\#        R4      pW¶3p\%        ^ VVP                  VVV
R7      R3# )a»  
Try to create a flattened transform from 2+ same-type transforms.

Returns (result, failure_reason) where:
- result is the FlattenedTransformInfo if successful, None otherwise
- failure_reason is None if successful, or one of:
  - "too_few_transforms": Less than 2 transforms provided
  - "no_flattened_mesh": No flattened mesh exists for the required dimensions
  - "uneven_tensor_shape": For reduce_scatter, tensor dim not evenly divisible
Nc              3   óJ   <"  € T F  pS! VP                   S4      x € K  	  R # 5ir•   )rL   )r–   Úinforå   Úfirst_placementss   & €€r$   r™   ÚJ_optimize_transform_infos.<locals>.try_create_flattened.<locals>.<genexpr>í  s)   øé € ð 
á�ñ % T×%<Ñ%<Ð>N×OÐOÛùs   ƒ #FTz5All transforms must have mergeable src_dst_placementsc              3   ó8   "  € T F  qP                   x € K  	  R # 5ir•   ©rJ   )r–   rë   s   & r$   r™   rí   ô  s   é € Ð:±E¨DŸ-ž-³Eùr¿   rY   rZ   c                 ó*   <€ V P                   S,          # r•   ©rc   ©ÚxÚaffected_dims   &€r$   Ú<lambda>ÚI_optimize_transform_infos.<locals>.try_create_flattened.<locals>.<lambda>  ó   ø€ °a·o±oÀlÖ6Sr&   )rÑ   c                 ó*   <€ V P                   S,          # r•   rñ   rò   s   &€r$   rõ   rö     r÷   r&   c              3   óZ   <"  € T F   pSP                  VP                  4      x € K"  	  R # 5ir•   )ÚsizerJ   ©r–   rë   r©   s   & €r$   r™   rí     s&   øé € ð 2Ù<A°D�× Ñ  §¡×/Ð/»Eùs   ƒ(+rX   z0Unsupported comm type for try_create_flattened: c              3   ó¾   <"  € T FR  p\        \        VP                  ^ ,          4      P                  R8X  g   K5  SP	                  VP
                  4      x € KT  	  R# 5i)r   rÜ   N)r   r   rL   rÝ   rú   rJ   rû   s   & €r$   r™   rí   -  sL   øé € ð á!�DÜœ ×!8Ñ!8¸Õ!;Ó<×FÑFÈ%ÑOô 0�× Ñ  §¡×/Ð/Û!ùs
   ƒ2Aº#ArÛ   )rJ   rL   rc   rw   rx   rt   )NÚtoo_few_transforms)NrÂ   éÿÿÿÿ)NrÀ   )NrÁ   )r„   rL   r`   ÚallrK   re   Úsortedr±   r   r   r‚   Úmaxrc   ÚmathÚprodÚNotImplementedErrorr\   r   rp   )rè   r¶   r‹   Úsorted_mesh_dimsr¥   r^   r_   Úoutermost_infoÚtensor_dim_sizeÚeffective_shard_mesh_sizert   Ú
merged_srcÚscaleÚmerged_placementsrô   rì   rå   r©   s   &             @@€€r$   Útry_create_flattenedÚ7_optimize_transform_infos.<locals>.try_create_flattenedÙ  sK  ú€ ô ˆu‹:˜Œ>Ø-Ð-ð ! �8×6Ñ6ÐØ˜!•H×+Ñ+Ó-ˆ	ß‹sõ 
áó
�s�sŠsõ 
áó
÷ 
ò 
ô !ØGóð ÷ ”EÑ:±EÓ:—E‘EÑ:±EÓ:Ó:ˆ	Ü ¤¨	Ó!2Ó3Ðð Ð(Ô(ð Ô,Ø6Ð6ð -à˜,Ô&ð ©T¨r¨TÕ2Ô2Ø6Ð6ä6°{ÐDTÓUˆØÒ!Ø,Ð,ð $‰ˆØ˜Ô$ä¤ sÓ+×/Ñ/ˆLÜ  Ô,SÔT‰NØÐ*Ô*Ü¤ sÓ+×/Ñ/ˆLÜ  Ô,SÔTˆNØ,×:Ñ:¸<ÕHˆOÜ(,¯	ª	ô 2Ù<Aó2ó )Ð%ð Õ:¸aÔ?Ø2Ð2ð @à˜,Ô&à" 1�X‰Nä%ØBÀ9À+ÐNóð ð
 ˆ	Øˆ
Ø�>‰>×ÒÜ—I’Iô á!óó ˆEð
 �qŒyØ!�	Ü$ U›^�
à'Ð-Ðô $ØØ#4Ø,×:Ñ:Ø#Ø#3Ø#ôð ð

ð 
	
r&   c              3   ó8   "  € T F  qP                   x € K  	  R # 5ir•   rï   )r–   Úgs   & r$   r™   Ú,_optimize_transform_infos.<locals>.<genexpr>o  s   é € Ð(C¹U¸¯®»Uùr¿   z5_optimize_transform_infos original: %s, optimized: %s>   rZ   rX   rY   )rÀ   rÁ   rÂ   )r„   rB   Ú	frozensetr`   rˆ   rL   Úextendre   r   rÌ   rÆ   Údebug)rÎ   r©   r³   r´   rÕ   r  Úresultr—   rë   Úcurrent_keyr}   ÚgroupÚjÚ	flattenedÚfailure_reasonr‹   rÔ   rå   s   &f&&            @@r$   Ú_optimize_transform_infosr  �  s¯  ú€ ô: ˆ?Ó˜aÔØÐç3Ó3ØÐô %Ò%SÓTÐ÷+ð +õ
÷@i
ñ i
ðX >@€FØ	€Aà
Œc�/Ó"Õ
"ØÕ!ˆØ×)Ñ)Ó+ˆñ ˜K×(Ò(Ø�M‰M˜$ÔØ��FˆAÙð
 "×4Ñ4ÐØ'+ fˆØ��Eˆà”�OÓ$Ô$Ù˜_Õ/×>Ñ>Ó@×AÒAÙ(ØÕ"×5Ñ5Ð7I÷ò ð �L‰L˜Õ+Ô,Ø��FŠAñ %9¸Ó$?Ñ!ˆ	ØÒ Ø�M‰M˜)Õ$ð �M‰M˜%Ô àð "ô ô
 "¤&Ñ(C¹UÓ(CÓ"CÓD�	Ü7ØØØ"Ø"Ü˜“JØØ"ôð ‹Ü
‡L�LØ?Àôð €Mr&   c                ó4   € V ^8„  d   QhR\         R\        RR/# )r   r©   Údtensor_metar!   ÚDTensorRedistributePlanner©r   r   )r#   s   "r$   r%   r%   ‰  s&   € ÷ %ñ %Üð%äð%ð "ñ%r&   c                óÀ   € \        4       '       d   \        W4      # \        P                  ! V 4      V3pV\        9  d   \        W4      pV\        V&   \        V,          # )aÑ  
Factory function to get or create a DTensorRedistributePlanner instance.
This function provides transparent caching of planner instances based on
device mesh and dtensor meta. Multiple calls with the same parameters
will return the same cached instance for better performance.
Args:
    device_mesh: The device mesh for the planner
    dtensor_meta: TensorMeta of the DTensor to redistribute
Returns:
    A DTensorRedistributePlanner instance (potentially cached)
)r	   r  ÚweakrefÚrefÚ_planner_cache)r©   r  rÈ   Úplanners   &&  r$   Úget_redistribute_plannerr$  ‰  sR   € ô ×ÒÜ)¨+ÓDÐDä—’˜[Ó)¨<Ð8€IØœÔ&Ü,¨[ÓGˆØ$+Œ�yÑ!ä˜)Õ$Ð$r&   c                ó   € V ^8„  d   QhRR/# rR   rf   )r#   s   "r$   r%   r%   £  s   € ÷ ñ ¨$ñ r&   c                 ó.   € \         P                  4        R# )z8Clear the cache of DTensorRedistributePlanner instances.N)r"  Úclearrf   r&   r$   Ú clear_redistribute_planner_cacher(  £  s   € ä×ÑÖr&   c                   óT  a € ] tR tRt o Rt]P                  ! RRR7       ! R R4      4       tR t]	V 3R lR	 l4       t
]	V 3R
 lR l4       t]	R V 3R lR ll4       tV 3R lR ltV 3R lR ltV 3R lR ltV 3R lR ltV 3R lR ltV 3R lR ltV 3R lR ltV 3R lR ltRtV tR# )!r  i¨  ac  
This class is used to plan the collective calls to transform the local shard
of the DTensor from its current spec to the target spec.
Suppose there are N tensor dimensions and M mesh dimensions, the total
possible state size will be (N+2)*M*M!.
Note: Use get_redistribute_planner() factory function instead of direct
instantiation for automatic caching.
TrD   c                   ó    a € ] tR tRt o ]P
                  ! RRRRR7      tR tR tR t	V 3R lR	 lt
V 3R
 lR ltV 3R lR ltV 3R ltRtV tR# )Ú$DTensorRedistributePlanner.DistStatei²  NF)ÚdefaultÚinitÚreprÚcomparec                óX   € \         P                  ! V P                  V P                  4      # r•   )r   Úformat_shard_order_strÚ
placementsÚtensor_dim_to_mesh_dimrM   s   &r$   Ú__str__Ú,DTensorRedistributePlanner.DistState.__str__º  s%   € Ü×5Ò5Ø—‘Ø×+Ñ+óð r&   c                ó"   € V P                  4       # r•   )r4  rM   s   &r$   Ú__repr__Ú-DTensorRedistributePlanner.DistState.__repr__À  s   € Ø—<‘<“>Ð!r&   c                óP   € \         P                  V R V P                  4       4       R# )Ú_hashN)ÚobjectÚ__setattr__Ú_compute_hashrM   s   &r$   rO   Ú2DTensorRedistributePlanner.DistState.__post_init__Ã  s"   € ä×ÑØØØ×"Ñ"Ó$ör&   c                ó    <€ V ^8„  d   QhRS[ /# ©r   r!   ©rd   )r#   rU   s   "€r$   r%   Ú1DTensorRedistributePlanner.DistState.__annotate__Ë  s   ø€ ÷ 	Rñ 	R™cñ 	Rr&   c                óV   € V P                   e   V P                   # V P                  4       # r•   )r:  r=  rM   s   &r$   Ú__hash__Ú-DTensorRedistributePlanner.DistState.__hash__Ë  s#   € Ø!%§¡Ò!7�4—:‘:ÐQ¸T×=OÑ=OÓ=QÐQr&   c                ó    <€ V ^8„  d   QhRS[ /# r@  rA  )r#   rU   s   "€r$   r%   rB  Î  s   ø€ ÷ 	ñ 	¡3ñ 	r&   c                óD   € \        V P                  V P                  34      # r•   )rÃ   r2  r3  rM   s   &r$   r=  Ú2DTensorRedistributePlanner.DistState._compute_hashÎ  s$   € Üà—O‘OØ×/Ñ/ðóð r&   c                ó&   <€ V ^8„  d   QhRS[ RS[/# )r   Úotherr!   )r;  r9   )r#   rU   s   "€r$   r%   rB  Ö  s   ø€ ÷ 	ñ 	¡ð 	©4ñ 	r&   c                óâ   € \        V\        P                  4      '       g   R # V P                  VP                  8w  d   R # V P                  V P
                  3VP                  VP
                  38H  # )F)r)   r  Ú	DistStater:  r2  r3  )rN   rJ  s   &&r$   Ú__eq__Ú+DTensorRedistributePlanner.DistState.__eq__Ö  sd   € Ü˜eÔ%?×%IÑ%I×JÒJÙØ�z‰z˜UŸ[™[Ô(Ùà—‘Ø×+Ñ+ðð × Ñ Ø×,Ñ,ðñð r&   c                ó`   <€ V ^8„  d   Qh/ S[ S[R3,          ;R&   S[;R&   S[R,          ;R&   # )r   .r2  r3  Nr:  )re   r   r   rd   )r#   rU   s   "€r$   r%   rB  ²  s9   ø‡ ‚ á™) S˜.Õ)Ñ)ñ ñ !+Ñ*ñ ñ �T�zñ 	
ò	 r&   rf   )rg   rh   ri   rj   ÚdataclassesÚfieldr:  r4  r7  rO   rD  r=  rM  rk   rl   rm   rn   s   @r$   rL  r+  ²  sW   ø‡ € ð (×-Ò-Ø˜u¨5¸%ô
ˆò	ò	"ò	÷	Rð 	R÷	ð 	÷	ð 	÷I ƒ r&   rL  c                ó®   a € \        V\        \        ,          4      '       d3   \        ;QJ d    . V 3R lV 4       F  NK  	  5# ! V 3R lV 4       4      # V# )z<Convert a nested list structure to a nested tuple structure.c              3   óF   <"  € T F  pSP                  V4      x € K  	  R # 5ir•   )Ú	_to_tuple)r–   ÚitemrN   s   & €r$   r™   Ú7DTensorRedistributePlanner._to_tuple.<locals>.<genexpr>æ  s   øé € Ð<¹!°$˜Ÿ™¨×-Ð-»!ùs   ƒ!)r)   r   re   )rN   ró   s   f&r$   rT  Ú$DTensorRedistributePlanner._to_tupleã  s;   ø€ ä�aœ¤�×&Ò&ß”5Ô<¹!Ó<—5Ð<�5Ô<¹!Ó<Ó<Ð<Øˆr&   c                óL   <€ V ^8„  d   QhRS[ S[S[S[,          3,          RS[/# ©r   ró   r!   )r€   rd   r   r   )r#   rU   s   "€r$   r%   Ú'DTensorRedistributePlanner.__annotate__ê  s(   ø€ ÷ 
ñ 
™t¡C©©c­ NÕ3ð 
¹
ñ 
r&   c                ó¶   € \         ;QJ d+    . R \        V P                  4       4       4       F  NK  	  5# ! R \        V P                  4       4       4       4      # )zConvert dict to ShardOrderc              3   óf   "  € T F'  w  rV'       g   K  \        V\        V4      R 7      x € K)  	  R# 5i))Ú
tensor_dimr‹   N)r   re   )r–   rÑ   Úvalues   &  r$   r™   ÚADTensorRedistributePlanner._dict_to_ShardOrder.<locals>.<genexpr>ì  s-   é € ð 
á/‘
�Üô DŒO s´e¸E³l×CÑCÛ/ùs   ‚1“1)re   r   Úitems)ró   s   &r$   Ú_dict_to_ShardOrderÚ.DTensorRedistributePlanner._dict_to_ShardOrderé  sL   € ÷ Œuñ 
ä$ Q§W¡W£YÔ/ó
�uð 	
ˆuñ 
ä$ Q§W¡W£YÔ/ó
ó 
ð 	
r&   c                óL   <€ V ^8„  d   QhRS[ RS[S[S[S[,          3,          /# rY  )r   r€   rd   r   )r#   rU   s   "€r$   r%   rZ  ó  s(   ø€ ÷ $ñ $™zð $©d±3¹¹S½	°>Õ.Bñ $r&   c                óx   € \        \        4      pV  F$  p\        VP                  4      WP                  &   K&  	  V# )z1Convert ShardOrder to dict with tensor dim as key)r   r   r‹   r]  )ró   Útensor_mesh_dim_dictÚentrys   &  r$   Ú_ShardOrder_to_dictÚ.DTensorRedistributePlanner._ShardOrder_to_dictò  s7   € ô  +¬4Ó0ÐÛˆEÜ59¸%¿/¹/Ó5JÐ ×!1Ñ!1Ó2ñ à#Ð#r&   Nc                óp   <€ V ^8„  d   QhRS[ RS[S[,          RS[S[R3,          RS[R,          RS[RS[/# )	r   rw   rÎ   r‰   .Úsrc_shard_orderNÚ use_strided_shard_as_shard_orderr!   )r   r   rH   re   r   r   r9   rT   )r#   rU   s   "€r$   r%   rZ  û  s`   ø€ ÷ G$ñ G$ÙðG$á!¡.Õ1ðG$ñ ™Y¨˜^Õ,ðG$ñ $ dÕ*ð	G$ñ
 +/ðG$ñ 
ñG$r&   c                óh  € \        V4      V P                  8w  d%   \        R\        V4       RV P                   24      hV'       d   \        P                  ! W RR7      w  r#Vf   \        P
                  ! V4      p\        V4      p\        P                  V4      p\        P                  \        V4      V4      pV.p. p	V Fs  p
\        V
\        4      p\        W¥V4       \        P                  \        V4      \        P                  V4      4      pVP                  V4       V	P                  V4       Ku  	  \!        V^ ,          4      .p\#        V	4       FI  w  rëV'       d   RMRpVP                  V4       VP                  \!        WŽ^,           ,          4      4       KK  	  RP%                  V4      # )aL  
Generate a string representation of the sequence of state transitions
(placements and shard orders) as described by the given transform_info.

Args:
    mesh: The DeviceMesh used for the redistribution.
    transform_infos: A sequence of _TransformInfo objects describing each
        transformation step.
    src_placement: The initial tuple of Placement objects.
    src_shard_order: (Optional) The initial ShardOrder representing
        the mapping of tensor dimensions to mesh dimensions. If None,
        the default shard order is computed from src_placement and mesh.
    use_strided_shard_as_shard_order: If True, normalize _StridedShard
        placements into regular Shard placements with an explicit
        shard_order before stringifying.

Returns:
    A string showing the sequence of DistState transitions, separated by '->'.
zdimensions mismatch z vs T©rk  z-->z->Ú )r„   ÚndimrK   r   Ú&_normalize_placements_into_shard_orderÚcompute_default_shard_orderr   r  rg  rL  re   r)   rp   r�   ra  rˆ   rT   Ú	enumeraterÅ   )rw   rÎ   r‰   rj  rk  Úcur_placementr~   Ú	cur_stateÚ
state_listÚis_flattened_listr|   Úis_flattenedÚ	new_stateÚtrace_partsr—   Ú	separators   &&&&&           r$   Ústringify_transform_infosÚ4DTensorRedistributePlanner.stringify_transform_infosú  s”  € ô6 ˆ}Ó §¡Ô*Ü Ø&¤s¨=Ó'9Ð&:¸$¸t¿y¹y¸kÐJóð ÷ ,ä×BÒBØ!È$ôñ +ˆMð
 Ò"Ü)×EÒEÀmÓTˆOÜ˜]Ó+ˆÜ5×IÑIØó
Ðô /×8Ñ8Ü�-Ó  /ó
ˆ	ð ð
ˆ
ð )+Ðã-ˆNÜ% nÔ6MÓNˆLä.ØÐ/?ôô 3×<Ñ<Ü�mÓ$Ü*×>Ñ>Ð?OÓPóˆIð ×Ñ˜iÔ(Ø×$Ñ$ \Ö2ñ .ô ˜: a�=Ó)Ð*ˆÜ(Ð):Ö;‰OˆAß!-™°4ˆIØ×Ñ˜yÔ)Ø×Ñœs :°!­eÕ#4Ó5Ö6ñ  <ð �w‰w�{Ó#Ð#r&   c                ó*   <€ V ^8„  d   QhRS[ RS[RR/# )r   r©   r  r!   Nr  )r#   rU   s   "€r$   r%   rZ  D  s)   ø€ ÷ $ñ $áð$ñ !ð$ð 
ñ	$r&   c                óú   € Wn         VP                  4       '       g   \        hVf   \        hW n        \	        VP
                  4      V n        \        4       V n        \        4       V n	        V P                  4        R# )z�
Initialize DTensorRedistributePlanner.

Args:
    device_mesh: The device mesh for this planner
    dtensor_meta: TensorMeta of the DTensor to redistribute
N)r©   Ú_is_current_rank_part_of_meshrK   r  r„   ÚshapeÚtensor_dimensionrƒ   Ú"strided_shard_placements_in_targetÚpartial_reduce_ops_in_targetÚsetup_cost_callbacks)rN   r©   r  s   &&&r$   Ú__init__Ú#DTensorRedistributePlanner.__init__D  sd   € ð 'ÔØ×8Ñ8×:Ò:Ü Ð ØÒÜ Ð Ø(ÔÜ # L×$6Ñ$6Ó 7ˆÔÜFIÃeˆÔ/Ü69³eˆÔ)Ø×!Ñ!Ö#r&   c                ó   <€ V ^8„  d   QhRR/# rR   rf   )r#   rU   s   "€r$   r%   rZ  [  s   ø€ ÷ +ñ +à	ñ+r&   c                ó6   a a€ R V 3R lloV3R lpVS n         R# )z­
Set up the cost function for different collective operations.
Uses communication time estimation based on actual tensor sizes and
mesh topology for accurate cost modeling.
c                óD   € V ^8„  d   QhR\         P                  R\        /# )r   Ústater!   )r  rL  r   )r#   s   "r$   r%   ÚEDTensorRedistributePlanner.setup_cost_callbacks.<locals>.__annotate__d  s"   € ÷ 		ñ 		Ü-×7Ñ7ð		äñ		r&   c                 ót   <€ \        SP                  V P                  SP                  V P                  R R7      # )F)rw   r2  Útensor_metaÚshard_orderrk  )r   r©   r2  r  r3  )rŠ  rN   s   &€r$   Ústate_to_specÚFDTensorRedistributePlanner.setup_cost_callbacks.<locals>.state_to_specd  s9   ø€ ô Ø×%Ñ%Ø ×+Ñ+Ø ×-Ñ-Ø!×8Ñ8Ø16ôð r&   c                 ó4   <€ \        S! V 4      S! V4      4      # r•   r   )Ú	src_stateÚ	dst_stater�  s   &&€r$   Úcost_functionÚFDTensorRedistributePlanner.setup_cost_callbacks.<locals>.cost_functiono  s   ø€ Ü-Ù˜iÓ(©-¸	Ó*Bóð r&   N)r”  )rN   r”  r�  s   f @r$   r„  Ú/DTensorRedistributePlanner.setup_cost_callbacks[  s   ù€ ÷		ð 		õ	ð
 +ˆÖr&   c                óT   <€ V ^8„  d   QhRS[ S[R3,          RS[RS[RS[3,          /# )r   r2  .Útensor_mesh_dim_tupler!   r+  )re   r   r   r€   r"   )r#   rU   s   "€r$   r%   rZ  v  sB   ø€ ÷ dñ dá™) S˜.Õ)ðdñ  *ðdñ 
Ð4±eÐ;Õ	<ñ	dr&   c           	     óº  € / p\         P                  V4      pV P                  V P                  V4      V4      pV EF  pVP                  pWG,          R,          p\        W,          \        4      '       g   K=  \        V P                  4       FÅ  p	Wy8X  d   K  WG,          P                  4       p
WI,          P                  V
4       \        V4      p\        V	4      Wº&   V P                  V P                  V4      \         P                  V4      4      pV P                  VV4      W<&   WG,          P                  V
4       WI,          P                  4        KÇ  	  EK  	  V FÈ  pVP                  pWG,          R,          p\        W,          \        4      '       g   K<  WG,          P                  4       p
\        V4      p\        4       Wº&   V P                  V P                  V4      \         P                  V4      4      pWG,          P                  V
4       V P                  VV4      W<&   KÊ  	  \        V4       Fi  w  r�\        V\         4      '       g   K  \        V4      p\        4       W¸&   V P                  V P                  V4      V4      pV P                  VV4      W<&   Kk  	  \        V4       FÆ  w  rí\        V\        4      '       g   K  \        V P                  4       F�  p	\        V4      p\        V	4      W¾&   WI,          P                  V4       V P                  V P                  V4      \         P                  V4      4      pV P                  VV4      W<&   WI,          P                  4        K’  	  KÈ  	  \        V4       FÆ  w  rí\        V\         4      '       g   K  \        V P                  4       F�  p	\        V4      p\        V	4      W¾&   WI,          P                  V4       V P                  V P                  V4      \         P                  V4      4      pV P                  VV4      W<&   WI,          P                  4        K’  	  KÈ  	  \        V4       FË  w  rí\        V\        4      '       g   K  V P"                   Fž  p\        V4      p\!        V4      W¾&   V Uu0 uF'  p\        V\         4      '       g   K  VP$                  kK)  	  pp\'        V4      ^8”  d   VRR08w  d   Ki  V P                  V P                  V4      V4      pV P                  VV4      W<&   K   	  KÍ  	  V FÈ  pVP                  pWG,          R,          p\        W,          \(        4      '       g   K<  WG,          P                  4       p
\        V4      p\        4       Wº&   V P                  V P                  V4      \         P                  V4      4      pWG,          P                  V
4       V P                  VV4      W<&   KÊ  	  V P*                  '       g   V# \        V4       FÀ  w  rí\        V\        4      '       g   K  V P*                   F“  pVP,                  p	\        V4      pVW¾&   WI,          P                  V4       V P                  V P                  V4      \         P                  V4      4      pV P                  VV4      W<&   WI,          P                  4        K•  	  KÂ  	  V# u upi )é   rÛ   rÜ   rþ   )r  rg  rL  rT  r]  r)   r   Úranger�  r‡   rˆ   r   ra  r”  r   rr  r   rƒ  rÝ   r„   r   r‚  r‚   )rN   r2  r˜  Úall_next_statere  Úcur_dist_staterf  Úsrc_tensor_dimÚsrc_mesh_dimÚdst_tensor_dimÚmove_mesh_dimÚnew_placementsÚ
dist_stateÚ	placementrJ   rÝ   ÚpÚpartial_reduce_opsÚstrided_shard_objs   &&&                r$   Úget_next_stateÚ)DTensorRedistributePlanner.get_next_statev  s'  € ðd MOˆä9×MÑMØ!ó 
Ðð Ÿ™Ø�N‰N˜:Ó&Ø!ó
ˆô +ˆEØ"×-Ñ-ˆNØ/Õ?ÀÕCˆLÜ˜jÕ6¼×>Ò>áÜ"'¨×(=Ñ(=Ö">�Ø!Ô3Ùð !5Õ D× HÑ HÓ J�Ø$Õ4×;Ñ;¸MÔJÜ!% jÓ!1�Ü05°nÓ0E�Ñ-Ø!Ÿ^™^Ø—N‘N >Ó2Ü.×BÑBØ,óó�
ð .2×-?Ñ-?Ø"Øó.�Ñ*ð
 %Õ4×;Ñ;¸MÔJØ$Õ4×8Ñ8Ö:ô+ #?ñ +óB +ˆEØ"×-Ñ-ˆNØ/Õ?ÀÕCˆLÜ˜jÕ6¼×>Ò>áØ0Õ@×DÑDÓFˆMÜ! *Ó-ˆNÜ,5«KˆNÑ)ØŸ™Ø—‘˜~Ó.Ü*×>Ñ>Ð?SÓTóˆJð !Õ0×7Ñ7¸ÔFØ)-×);Ñ);ØØó*ˆNÓ&ñ +ô* (1°Ö'<Ñ#ˆLÜ˜i¬×1Ò1ÙÜ! *Ó-ˆNÜ+4«;ˆNÑ(ØŸ™Ø—‘˜~Ó.Ð0EóˆJð *.×);Ñ);ØØó*ˆNÓ&ñ (=ô $-¨ZÖ#8ÑˆHÜ˜i¬×3Ò3ÙÜ"'¨×(=Ñ(=Ö">�ä!% jÓ!1�Ü+0°Ó+@�Ñ(Ø$Õ4×;Ñ;¸HÔEØ!Ÿ^™^Ø—N‘N >Ó2Ü.×BÑBØ,óó�
ð .2×-?Ñ-?Ø"Øó.�Ñ*ð %Õ4×8Ñ8Ö:ó #?ñ $9ô, $-¨ZÖ#8ÑˆHÜ˜i¬×1Ò1ÙÜ"'¨×(=Ñ(=Ö">�ä!% jÓ!1�Ü+0°Ó+@�Ñ(Ø$Õ4×;Ñ;¸HÔEØ!Ÿ^™^Ø—N‘N >Ó2Ü.×BÑBØ,óó�
ð .2×-?Ñ-?Ø"Øó.�Ñ*ð %Õ4×8Ñ8Ö:ó #?ñ $9ô0 $-¨ZÖ#8ÑˆHÜ˜i¬×3Ò3ÙØ!×>Ô>�	Ü!% jÓ!1�Ü+2°9Ó+=�Ñ(ñ *8ó&Ù)7 A¼:ÀaÌ×;Q”K�A—K”K©ð #ð &ô Ð)Ó*¨QÔ.Ð3EÈ%ÐQVÈÔ3WÙà!Ÿ^™^Ø—N‘N >Ó2Ð4Ió�
ð .2×-?Ñ-?Ø"Øó.�Ó*ó ?ñ $9ó: +ˆEØ"×-Ñ-ˆNØ/Õ?ÀÕCˆLÜ˜jÕ6¼×FÒFÙØ0Õ@×DÑDÓFˆMÜ! *Ó-ˆNÜ,5«KˆNÑ)ØŸ™Ø—‘˜~Ó.Ü*×>Ñ>Ð?SÓTóˆJð !Õ0×7Ñ7¸ÔFØ)-×);Ñ);ØØó*ˆNÓ&ñ +ð& ×6×6Ð6Ø!Ð!ô $-¨ZÖ#8ÑˆHÜ˜i¬×3Ò3ÙØ%)×%LÔ%LÐ!Ø!2×!6Ñ!6�ä!% jÓ!1�Ø+<�Ñ(Ø$Õ4×;Ñ;¸HÔEØ!Ÿ^™^Ø—N‘N >Ó2Ü.×BÑBØ,óó�
ð .2×-?Ñ-?Ø"Øó.�Ñ*ð %Õ4×8Ñ8Ö:ó! &Mñ $9ð* ÐùòQ&s   Ò[Ò;[c                óB   <€ V ^8„  d   QhRS[ RS[ RS[S[ S[3,          /# )r   Úcurrent_stater“  r!   )rL  r€   r"   )r#   rU   s   "€r$   r%   rZ  œ  s/   ø€ ÷ ñ Ù&ðÙ3<ðá	‰i™ÐÕ	ñr&   c                óH  € / pV P                  VP                  4      pVP                   Fô  pVP                  pWF,          R,          pVP                  V,          pVP                  V,          p	\	        V\
        4      '       d%   \        V	4      \        J d   V	P                  R8X  g   K€  WF,          P                  4        \        VP                  4      p
WšV&   V P                  \        V
4      V P                  V4      4      pWF,          P                  V4       RW;&   Kö  	  V# )a  Generate explicit-only Shard -> Partial("sum") target steps.

Zero weight means no communication; allocation and copy costs are omitted.
This edge is generated only when Partial("sum") is the requested target,
so path search cannot use it as an intermediate step to another layout.
rÛ   ç        rþ   )rg  r3  r]  r2  r)   r   Útyper   rÝ   r‡   r   rL  re   ra  rˆ   )rN   r«  r“  Únext_statesrŽ  rf  r]  rJ   ÚcurrentÚtargetr2  Ú
next_states   &&&         r$   Ú#_get_shard_to_partial_target_statesÚ>DTensorRedistributePlanner._get_shard_to_partial_target_statesœ  s   € ð JLˆØ×.Ñ.¨}×/SÑ/SÓTˆØ"×9Ô9ˆEØ×)Ñ)ˆJØ"Õ.¨rÕ2ˆHØ#×.Ñ.¨xÕ8ˆGØ×)Ñ)¨(Õ3ˆFä˜7¤E×*Ò*Ü˜“L¤GÓ+Ø×$Ñ$¨Ô-áàÕ#×'Ñ'Ô)Ü˜m×6Ñ6Ó7ˆJØ#)�xÑ ØŸ™Ü�jÓ! 4×#;Ñ#;¸KÓ#HóˆJð Õ#×*Ñ*¨8Ô4Ø&)ˆKÓ#ñ' :ð( Ðr&   c                ó:   <€ V ^8„  d   QhRS[ RS[ RS[R,          /# )r   r’  r“  r!   r+  )rL  r   )r#   rU   s   "€r$   r%   rZ  ¿  s0   ø€ ÷ @
ñ @
Ù"ð@
Ù/8ð@
á	Ð4Õ	5ñ@
r&   c           	     ó4  € ^ RI p^ pRVRW.3.p\        4       pV'       dé   VP                  V4      w   rxršW’8X  d   V
# W–9   d   K-  VP                  V	4       V P	                  V	P
                  V	P                  4      pVP                  V P                  W’4      4       VP                  4        FV  w  rÍWÆ9  g   K  \        \        V4      V,           pW¬.,           pV^,          pVP                  V\        V4      VVVV34       KX  	  Kð  \        RV RV 24      h)zú
Find the min cost path from src_state to dst_state using Dijkstra's
algorithm.

Args:
    src_state: The source state
    dst_state: The destination state

Returns:
    A list of states representing the min cost path from src_state to
    dst_state
Nr­  zNo path found from src_state z to dst_state )Úheapqrƒ   Úheappopr†   r¨  r2  r3  Úupdater³  r`  r   r   Úheappushr5   rK   )rN   r’  r“  r·  ÚcounterÚpqÚvisitedrŽ   r    r«  Úpathr¯  r²  Útransition_costÚnew_costÚnew_paths   &&&             r$   Úfind_min_cost_pathÚ-DTensorRedistributePlanner.find_min_cost_path¿  s0  € ó 	ð ˆð �7˜C ¨KÐ8Ð9ð 	ô “%ˆßØ.3¯m©m¸BÓ.?Ñ+ˆAˆq˜ØÔ)Ø�ØÔ'ÙØ�K‰K˜Ô&à×-Ñ-Ø×(Ñ(Ø×4Ñ4óˆKð ×ÑØ×8Ñ8¸ÓRôð 0;×/@Ñ/@Ö/BÑ+�
ØÖ,Ü#¤C¨›°Õ@�HØ# lÕ2�HØ˜q•L�GØ—N‘NØä7¸ÓAØ#Ø$Ø&Ø$ðö	ó 0Cô Ø+¨I¨;°nÀYÀKÐPó
ð 	
r&   c          	      óT   <€ V ^8„  d   QhRRRS[ RS[S[ R3,          RS[S[,          /# )r   r’  r+  rJ   Úfull_tensor_shape.r!   )rd   re   r   r   )r#   rU   s   "€r$   r%   rZ    s@   ø€ ÷ !ñ !à9ð!ñ ð!ñ !¡ c �?ð	!ñ
 
‰kÕ	ñ!r&   c           	     ó¢  € \        V4      pVP                   EF2  pVP                  pVP                  p\	        V4      ^ 8:  d   \
        hV Fú  pW‚8X  d   K  VP                  V,          p	\        V	\        4      '       dP   V	P                  WF,          V P                  P                  VR7      V P                  P                  V4      4      w  r«Ms\        V	\        4      '       dP   V	P                  WF,          V P                  P                  VR7      V P                  P                  V4      4      w  r«M\        RV	 24      hW¤V&   Kü  	  EK5  	  V# )r   rï   zUnsupported placement type: )r   r3  r]  r‹   r„   rK   r2  r)   r   Úlocal_shard_size_and_offsetr©   rú   Ú_sym_get_coordinater   r…   )rN   r’  rJ   rÅ  Únew_logical_shaperf  r]  r‹   Úmdimr¤  Únew_sizerŽ   s   &&&&        r$   Úget_logical_shapeÚ,DTensorRedistributePlanner.get_logical_shape  s4  € ô 04Ð4EÓ/FÐØ×5Õ5ˆEØ×)Ñ)ˆJØŸ™ˆIÜ�9‹~ Ô"Ü$Ð$Û!�ØÔ#ÙØ%×0Ñ0°Õ6�	Ü˜i¬×/Ò/Ø"+×"GÑ"GØ)Õ5Ø×(Ñ(×-Ñ-°tÐ-Ó<Ø×(Ñ(×<Ñ<¸TÓBó#‘K�H˜aô
   	¬=×9Ò9Ø"+×"GÑ"GØ)Õ5Ø×(Ñ(×-Ñ-°tÐ-Ó<Ø×(Ñ(×<Ñ<¸TÓBó#‘K�H˜aô %Ð'CÀIÀ;Ð%OÓPÐPØ08 *Ó-ô% "ñ 6ð0 !Ð r&   c          	      óV   <€ V ^8„  d   QhRS[ RS[ RS[S[R3,          RS[S[,          /# )r   Úsrc_specÚdst_specrÅ  .r!   )r   re   rd   r   rH   )r#   rU   s   "€r$   r%   rZ  "  sF   ø€ ÷ Gñ GáðGñ ðGñ !¡ c �?ð	Gñ
 
‰nÕ	ñGr&   c           
     óV  € R  R lpV! V4      w  rVV! V4      w  rxV F6  p	\        V	\        4      '       g   K  V P                  P                  V	4       K8  	  \        P
                  ! WW4       F@  p	\        V	\        4      '       g   K  V P                  P                  V	P                  4       KB  	  V P                  WV4      p
V P                  Wx4      p. pV P                  W«4      p\        P                  ! V4       F©  w  rïVP                  VP                  8w  g   K"  Rp\        \        VP                  VP                  4      4       FX  w  pw  ppVV8w  g   K  VR8w  d   \        R4      hTpV P!                  VVV4      pVP#                  \%        VVV3VR7      4       KZ  	  K«  	  V# )c                ól   € V ^8„  d   QhR\         R\        \        \        R3,          \        3,          /# )r   Úspecr!   .)r   re   r   r   )r#   s   "r$   r%   ÚUDTensorRedistributePlanner.generate_graph_based_transform_infos.<locals>.__annotate__+  s/   € ÷ 	9ñ 	9Üð	9ä”5œ C˜Õ(¬*Ð4Õ5ñ	9r&   c                 óò   € V P                   '       d3   \        P                  ! V P                  V P                  R R7      w  rW3# V P
                  f   \        RV  24      hV P                  V P
                  3# )Trm  zMissing shard_order field in )rk  r   rp  r2  rw   rŽ  r…   )rÓ  r¢  rŽ  s   &  r$   Ú_try_normalize_specÚ\DTensorRedistributePlanner.generate_graph_based_transform_infos.<locals>._try_normalize_spec+  su   € ð ×4×4Ð4ä×FÒFØŸ™ØŸ	™	Ø9=ôñ ,�ð &Ð2Ð2à×#Ñ#Ò+Ü$Ð'DÀTÀFÐ%KÓLÐLØ—‘¨×(8Ñ(8Ð8Ð8r&   z@Multiple mesh_dims are different between cur_state and nxt_state©rJ   rL   rc   rþ   )r)   r   r‚  r†   Ú	itertoolsÚchainr   rƒ  rÝ   rL  rÂ  Úpairwiser2  rr  ÚziprK   rÌ  rˆ   rH   )rN   rÏ  rÐ  rÅ  rÖ  r³   rj  r´   Údst_shard_orderr¤  r’  r“  rÎ   Ú
state_pathrt  Ú	nxt_stateÚupdate_mesh_dimrJ   rs  Únxt_placementrc   s   &&&&                 r$   Ú$generate_graph_based_transform_infosÚ?DTensorRedistributePlanner.generate_graph_based_transform_infos"  s’  € õ	9ñ" +>¸hÓ*GÑ'ˆÙ*=¸hÓ*GÑ'ˆó
 (ˆIÜ˜)¤]×3Ô3Ø×7Ñ7×;Ñ;¸IÖFñ (ô #Ÿš¨ÖHˆIÜ˜)¤W×-Ô-Ø×1Ñ1×5Ñ5°i×6IÑ6IÖJñ Ið —N‘N >ÓCˆ	Ø—N‘N >ÓCˆ	Ø02ˆØ×,Ñ,¨YÓBˆ
Ü$-×$6Ò$6°zÖ$BÑ ˆIà×#Ñ# y×';Ñ';Ö;Ø"$�Ü@IÜ˜	×,Ñ,¨i×.BÑ.BÓCöAÑ<�HÑ<˜}¨mð %¨Ö5Ø*¨bÔ0Ü"0Ø bó#ð ð +3˜Ø(,×(>Ñ(>Ø% xÐ1Bó)˜ð (×.Ñ.Ü*Ø)8Ø4AÀ=Ð3QØ.;ôöóAñ	 %Cð0 Ðr&   c                ó<   <€ V ^8„  d   QhRS[ RS[ RS[S[,          /# )r   rÏ  rÐ  r!   )r   r   rH   )r#   rU   s   "€r$   r%   rZ  k  s3   ø€ ÷ ~ñ ~áð~ñ ð~ñ 
‰nÕ	ñ	~r&   c           	     ó‚  € \        VP                  4      pV.p. pV P                  P                  ^8X  dm   VP                  ^ ,          VP                  ^ ,          8w  dB   VP                  \        ^ VP                  ^ ,          VP                  ^ ,          3VR7      4       V# \        VP                  4       FÝ  w  rgWF,          p\        V\        4      '       dª   W`P                  P                  ^,
          8  d‡   V P                  P                  VR7      p	VP                  W‡P                  ,          V	V P                  P                  V4      4      w  r«\        V4      pW¬VP                  &   VP                  V4       KÊ  KÌ  VP                  V4       Kß  	  \        VP                  4      p\        VP                  4      pVP                  ^8”  Ed   \        \!        \#        V4      4      4       F÷  pWß,          pWï,          p\        V\        4      '       d�   VP                  p. . pp\        \%        WÞ4      4       Fc  w  pw  ppWo8¼  d    MVVP'                  V4      '       d   VP                  V4       VP'                  V4      '       g   KR  VP                  V4       Ke  	  VV8w  d   \)        4       pVV8w  g   KÎ  VP                  \        VVV3WO,          R7      4       VWß&   Kù  	  \        \%        WÞ4      4       F;  w  pw  ppVV8w  g   K  VP                  \        VVV3WO,          R7      4       VWß&   K=  	  V# )ap  
Generate the transform infos from the source placements to the target placements.

To transform from source to target placement it might have multiple steps, i.e. it
might decompose Si -> Sj into Si -> R -> Sj.
This would detect if there're mis-aligned/nested shardings between src/dst placements.
E.g. Suppose the redistribution to perform is (Shard(0), Shard(0)) -> (Replicate(), Shard(0)),
in this case Shard(0) -> Shard(0) for mesh dimension 1 actually needs resharding, because in
the former is a nested-sharding of a tensor already sharded dimension 0, whereas
the latter is the first sharding on tensor dimension 0.
rØ  rï   )r   r€  r©   ro  r2  rˆ   rH   rr  r)   r   rú   Ú_local_shard_size_and_offsetr‚   rÈ  Ú
num_shardsÚreversedr›  r„   rÜ  Úis_shardr   )rN   rÏ  rÐ  Úinitial_logical_shapeÚmesh_dims_to_logical_shaperÎ   r—   r^   Úcurrent_logical_shapeÚmesh_dim_sizeÚlocal_shard_sizerŽ   rÉ  r}   Útarget_placementsrJ   r°  r±  Ú	shard_dimÚcurrent_mesh_shardingÚtarget_mesh_shardingÚsr¥  s   &&&                    r$   Úgenerate_greedy_transform_infosÚ:DTensorRedistributePlanner.generate_greedy_transform_infosk  s  € ô$ !% X§^¡^Ó 4ÐØ&;Ð%<Ð"Ø02ˆØ×Ñ× Ñ  AÔ%ð ×"Ñ" 1Õ%¨×)<Ñ)<¸QÕ)?Ô?Ø×&Ñ&Ü"Ø!"à$×/Ñ/°Õ2Ø$×/Ñ/°Õ2ð,ð '<ôô	ð #Ð"ô
   × 3Ñ 3Ö4‰FˆAØ$>Õ$AÐ!Ü˜#œu×%Ò%Ø×'Ñ'×,Ñ,¨qÕ0Ô0à$(×$4Ñ$4×$9Ñ$9À1Ð$9Ó$E�MØ*-×*JÑ*JØ-¯g©gÕ6Ø%Ø×(Ñ(×<Ñ<¸QÓ?ó+Ñ'Ð$ô
 )-Ð-BÓ(CÐ%Ø1A c§g¡gÑ.Ø.×5Ñ5Ð6GÖHñ 1ð +×1Ñ1Ð2GÖHñ 5ô( " (×"5Ñ"5Ó6ÐÜ  ×!4Ñ!4Ó5Ðà×Ñ Õ"ô %¤U¬3Ð/AÓ+BÓ%CÖD�Ø,Õ6�Ø*Õ4�ô ˜f¤e×,Ò,ð !'§
¡
�IØBDÀbÐ+?Ð)Ü%.ÜÐ.ÓBö&™	˜™6˜A˜qð œ=Ù!ØŸ:™: i×0Ò0Ø1×8Ñ8¸Ô;ØŸ:™: i×0Ô0Ø0×7Ñ7¸Ö:ñ&ð -Ð0DÔDô
 "+£˜à˜fÖ$Ø#×*Ñ*Ü&Ø%-Ø07¸Ð/@Ø*DÕ*Nôôð 4:Ð&Ó0ñQ EôZ ,5ÜÐ"Ó6ö,
Ñ'ˆHÑ'�w ð ˜&Ö Ø×&Ñ&Ü"Ø!)Ø,3°VÐ+<Ø&@Õ&Jôôð 06Ð"Ó,ñ,
ð Ðr&   )r”  r©   r  rƒ  r‚  r�  )NF)rg   rh   ri   rj   rz   rP  Ú	dataclassrL  rT  Ústaticmethodra  rg  r{  r…  r„  r¨  r³  rÂ  rÌ  râ  rô  rl   rm   rn   s   @r$   r  r  ¨  sØ   ø‡ € ñð ×Ò $¨dÔ3÷.ð .ó 4ð.ò`ð ÷
ó ð
ð ÷$ó ð$ð ÷G$ñ G$ó ðG$÷R$ð $÷.+ð +÷6dð d÷L	ð ÷F@
ð @
÷D!ð !÷BGð G÷R~ö ~r&   r  c          	      ól   € V ^8„  d   QhR\         R\         R\        R,          R\        \        ,          /# ©r   rÏ  rÐ  Úuse_graph_based_transformNr!   ©r   r9   r   rH   )r#   s   "r$   r%   r%   ì  s9   € ÷ 8ñ 8Üð8äð8ô  $ d�{ð8ô 
Œ.Õñ	8r&   c                 óè  € V P                   pV P                  pVP                  p\        ;QJ d    R  WE3 4       F  '       d   K   RM	  RM! R  WE3 4       4      '       * p\        ;QJ d4    R . V P                  OVP                  O 4       F  '       g   K   RM)	  RM%! R . V P                  OVP                  O 4       4      pV'       g	   V'       d   RpM\
        e   \
        pMVf   RpV P                  f   \        h\        VV P                  4      pV'       d!    VP                  V VV P                  4      p	V	# VP                  W4      p	V	#   \         d    TP                  Y4      p	 T	# i ; i)c              3   óN   "  € T F  p\         P                  ! V4      x € K  	  R # 5ir•   )r   Úis_default_device_order)r–   Úorders   & r$   r™   Ú2_gen_transform_infos_non_cached.<locals>.<genexpr>ö  s%   é € ð $á7ˆEô 	×+Ò+¨E×2Ð2Û7ùs   ‚#%FTc              3   óB   "  € T F  p\        V\        4      x € K  	  R # 5ir•   )r)   r   )r–   r¥  s   & r$   r™   r   ú  s!   é € ð á=ˆAô 	�1”m×$Ð$Û=ùs   ‚)r©   rŽ  rÿ   Úanyr2  r;   r�  rK   r$  râ  r€  r   rô  )
rÏ  rÐ  rú  r©   rj  rÝ  Úhas_non_default_orderÚhas_strided_shardÚdrprÎ   s
   &&&       r$   Ú_gen_transform_infos_non_cachedr  ì  s{  € ð
 ×&Ñ&€KØ×*Ñ*€OØ×*Ñ*€O÷ !$£ñ $à%Ñ7ó$§§¢ñ $à%Ñ7ó$ó !ô Ð÷ ›ñ à=�8×&Ñ&Ð=¨×)<Ñ)<Ñ=óŸŸšñ à=�8×&Ñ&Ð=¨×)<Ñ)<Ñ=óó Ð÷ × 1Ø$(Ñ!Ü	,Ò	8Ü$GÑ!Ø	"Ò	*Ø$)Ð!Ø×ÑÒ#ÜÐÜ
"ØØ×Ñó€C÷ !ð	VØ!×FÑFØØØ—‘óˆOð Ðð ×=Ñ=¸hÓQˆØÐøô	 .ô 	VØ!×AÑAÀ(ÓU‰Oð Ðð		Vús   ÄE ÅE1Å0E1c          	      ól   € V ^8„  d   QhR\         R\         R\        R,          R\        \        ,          /# rù  rû  )r#   s   "r$   r%   r%   (  s9   € ÷ 	ñ 	Üð	äð	ô  $ d�{ð	ô 
Œ.Õñ		r&   c                 ó   € \        V VV4      # r•   )r  )rÏ  rÐ  rú  s   &&&r$   Ú_gen_transform_infosr	  '  s   € ô +ØØØ!óð r&   Úasync_oprú  Úis_explicitc                ó¢   € V ^8„  d   QhR\         P                  R\        R\        R\        R\        R,          R\        R\         P                  /# )	r   Úlocal_tensorÚcurrent_specÚtarget_specr
  rú  Nr  r!   )r*   ÚTensorr   r9   )r#   s   "r$   r%   r%   4  sc   € ÷ ñ Ü—,‘,ðäðô ðô
 ðô  $ d�{ðô ðô ‡\�\ñr&   c               ó  € VP                   VP                   8w  d   \        R4      hVP                  f   \        R4      h\	        VP
                  4       \	        VP
                  4       T pVP                   pVP                  4       '       g   V # \        4       '       d   \        VVV4      pM\        VVV4      p\        VVVP
                  VP
                  4      p	\        4       p
V
e`   V
P                  V VP
                  VP
                  \        P                  VV	VP
                  VP                  VP                  4      VR7      M\         P"                  ! 4       pT;_uu_ 4        V	 EF÷  p\%        V\&        4      '       d   VP                   pMTpVP(                  pVP*                  w  pp\%        V\,        4      '       g   \%        V\,        4      '       d   W×Jd   \/        R4      hVP1                  VR7      pVV8X  d   T pK�  V^8X  d   T pK¨  VP3                  4       '       dû   VP5                  4       '       d[   \7        \8        V4      pVP;                  WV4      p\%        V\&        4      '       d!   VP<                  e   WlP<                  ,          pEM�VP?                  4       '       d/   \7        \@        V4      pVPC                  WWìPD                  4      pEMK\%        V\,        4      '       d   VPC                  WWìPD                  4      pEM\G        RV RV R	24      hVP?                  4       '       Ed�   \7        \@        V4      pVP5                  4       '       d\   \7        \8        V4      pVPI                  WVV4      p\%        V\&        4      '       d!   VP<                  e   WlP<                  ,          pEMmVP3                  4       '       d$   VPK                  WWíPM                  V4      4      pEM4VP?                  4       '       dW   \7        \@        V4      pVPN                  VPN                  8w  d*   VPQ                  V VVVPD                  VPN                  4      pEMÈ\%        V\,        4      '       dB   VPC                  WWìPD                  4      pVPK                  VVVVPM                  V4      4      pEMq\        R
V RV 24      hVP5                  4       '       dÕ   VP3                  4       '       d%   \7        \8        V4      pVPS                  WV4      pEM\U        V4      '       dm   \%        V\@        4      '       d%   \W        V4      \8        Jg   VPX                  R8w  d   \G        RV RV R	24      hVP[                  V VVVPD                  4      pEM“VV8w  d   \/        RV RV R24      hT pEMv\%        V\,        4      '       Ed`   VP5                  4       '       dG   \7        \8        V4      pVP;                  WV4      pVP]                  VW~VPM                  V4      4      pEMVP3                  4       '       d#   VP]                  WWçPM                  V4      4      pMËVP?                  4       '       dP   \7        \@        V4      pVPC                  WWìPD                  4      pVP]                  VW~VPM                  V4      4      pMf\%        V\,        4      '       d@   VPC                  WWìPD                  4      pVP]                  VW~VPM                  V4      4      pM\        R
V RV 24      hV'       g1   \%        V\^        P`                  4      '       d   VPc                  4       pTp EKú  	  RRR4       V#   + '       g   i     T# ; i)zï
This redistribute the local tensor (torch.Tensor) from the current DTensorSpec to
the target DTensorSpec, which involves the necessary collective calls to transform
the local shard of the DTensor from its current spec to the target spec.
z)Cross device mesh comm not supported yet!NzUuse_strided_shard_as_shard_order should be initialized in DTensorSpec.__post_init__())r  z:_StridedShard redistribute assumes no flattened transformsrï   zredistribute from z to z not supported yetzUnexpected placement z& for redistribute to target placement rÛ   z&Redistribution from one partial type (z) to another (z) is unsupported.)2rw   r  rk  r…   r   r2  r  r	   r  r	  r  r   Úrecord_redistribute_callsr  r{  rŽ  Ú
contextlibÚnullcontextr)   rp   rJ   rL   r   rK   rú   r]   r\   r   r   Ú_reduce_valuert   ré  r   Ú_to_replicate_tensorrc   ÚRuntimeErrorÚ_reduce_shard_valueÚ_replicate_to_shardrÈ  r‚   Ú_to_new_shard_dimÚ_partition_valuer   r®  rÝ   Ú_to_partial_tensorÚ_replicate_to_strided_shardÚfuncolÚAsyncCollectiveTensorÚwait)r  r  r  r
  rú  r  Únew_local_tensorr©   rÎ   Úoptimized_transform_infosÚ
debug_modeÚredistribute_contextr|   Úmesh_to_user—   r°  r±  Ú
num_chunksÚpartial_specÚcurrent_placementÚtarget_placementÚ
shard_specÚ
replicateds   &&&$$$                 r$   Úredistribute_local_tensorr,  4  s/  € ð  ×Ñ˜K×,Ñ,Ô,ä!Ð"MÓNÐNà×4Ñ4Ò<ÜØcó
ð 	
ô " ,×"9Ñ"9Ô:Ü! +×"8Ñ"8Ô9à#ÐØ×#Ñ#€Kà×4Ñ4×6Ò6ð Ðä×ÒÜ9ØØØ%ó
‰ô /ØØØ%ó
ˆô !:ØØØ×ÑØ×Ñó	!Ðô 'Ó(€Jð  Ò!ð 	×,Ñ,ØØ×#Ñ#Ø×"Ñ"Ü&×@Ñ@ØØ)Ø×'Ñ'Ø×(Ñ(Ø×=Ñ=óð $ð 	-ô 	
ô ×#Ò#Ó%ð ÷$ 
Ò	Ü7ˆNä˜.Ô*A×BÒBØ,×1Ñ1‘à)�Ø×'Ñ'ˆAØ,×?Ñ?‰OˆG�Vô
 ˜'¤=×1Ò1´ZÀÌ×5VÒ5VØÓ1Ü(ØTóð ð %×)Ñ)°1Ð)Ó5ˆJà˜&Ô à#/Ð Ùà˜QŒð $0Ð Ùà×"Ñ"×$Ò$à×%Ñ%×'Ò'Ü#'¬°Ó#9�LØ'3×'AÑ'AØ$°1ó(Ð$ô
 # >Ô3J×KÒKØ*×4Ñ4Ò@à+;×>VÑ>VÕ+VÐ(ùØ×%Ñ%×'Ò'Ü(,¬U°GÓ(<Ð%Ø'8×'MÑ'MØ$°1×6RÑ6Ró(Ò$ô   ¬×7Ò7Ø'.×'CÑ'CØ$°1×6RÑ6Ró(Ò$ô 'Ø,¨W¨I°T¸&¸ÐASÐTóð ð —‘×"Ó"ä#'¬¨vÓ#6Ð Ø×%Ñ%×'Ò'Ü#'¬°Ó#9�LØ'3×'GÑ'GØ$°1Ð6Fó(Ð$ô
 # >Ô3J×KÒKØ*×4Ñ4Ò@à+;×>VÑ>VÕ+VÐ(ùØ×)Ñ)×+Ò+à'7×'KÑ'KØ$°1×6UÑ6UÐVWÓ6Xó(Ò$ð ×%Ñ%×'Ò'Ü!%¤e¨WÓ!5�JØ!—~‘~Ð)9×)=Ñ)=Ô=Ø+5×+GÑ+GØ(Ø'ØØ*×8Ñ8Ø,×0Ñ0ó,Ð(ùô   ¬×7Ò7à!(×!=Ñ!=Ø$°1×6RÑ6Ró"�Jð (8×'KÑ'KØ"Ø#ØØ#×7Ñ7¸Ó:ó	(Ò$ô %Ø/°¨yÐ8^Ð_eÐ^fÐgóð ð ×"Ñ"×$Ò$Ø×'Ñ'×)Ò)Ü#'¬°Ó#8�LØ'3×'DÑ'DØ$°1ó(Ò$ô $ G×,Ò,ä& w´×6Ò6Ü ›<¬wÓ6Ø!×+Ñ+¨uÔ4ä*Ø0°°	¸¸f¸XÐEWÐXóð ð (/×'AÑ'AØ$Ø#ØØ&×4Ñ4ó	(Ò$ð  &Ô(Ü,ØDÀWÀIÈ^Ð\bÐ[cÐctÐuóð ð (4Ò$Ü˜F¤M×2Ó2à×%Ñ%×'Ò'ä#'¬°Ó#9�LØ!-×!;Ñ!;Ø$°1ó"�Jð (.×'IÑ'IØ" K°K×4SÑ4SÐTUÓ4Vó(Ò$ð ×)Ñ)×+Ò+à'-×'IÑ'IØ$°1×6UÑ6UÐVWÓ6Xó(Ñ$ð ×%Ñ%×'Ò'ä(,¬U°GÓ(<Ð%Ø!2×!GÑ!GØ$°1×6RÑ6Ró"�Jð (.×'IÑ'IØ" K°K×4SÑ4SÐTUÓ4Vó(Ñ$ô   ¬×7Ò7ð ")×!=Ñ!=Ø$°1×6RÑ6Ró"�Jð (.×'IÑ'IØ" K°K×4SÑ4SÐTUÓ4Vó(Ñ$ô %Ø/°¨yÐ8^Ð_eÐ^fÐgóð ÷ ¤
Ø ¤&×">Ñ">÷!ò !ð $4×#8Ñ#8Ó#:Ð Ø+‹Lñ[ 8÷ 
ð^ Ð÷_ 
Ö	ð^ Ðús\   Å)C ]2È*]2É A/]2Ê0B
]2Ì;B]2Ï8]2ÐC]2Ó]2Ó5C*]2× A]2Ø<7]2Ù4B<]2Ü17]2Ý2^	c          
      ót   € V ^8„  d   QhRRR\         R\        P                  R\        P                  R\        /# )r   Úgrad_outputúdtensor.DTensorÚprevious_specÚ	out_dtypeÚop_dtyper
  )r   r*   Údtyper9   )r#   s   "r$   r%   r%   6  sI   € ÷ [ñ [Ø"ð[äð[ô �{‰{ð	[ô
 �k‰kð[ô ñ[r&   c          
     óœ  € W0P                   P                  8w  dÄ   V P                   P                  VR7      p\        V P                  P
                  V P                  P                  \        V P                  V P                  4       VR7      V P                  P                  R7      p\        VP
                  VP                  VP                  VP                  R7      pMV P                   pV P                  p. p\        VP                  VP                  4       Fn  w  r‰\        V4      '       g   VP                  4       '       d2   V	P                  4       '       d   VP!                  \#        4       4       K]  VP!                  V	4       Kp  	  \        VP
                  \%        V4      VP                  VP                  R7      p\'        VVVVR7      p
V
P                  V8w  d   V
P                  V4      p
\        VP
                  \%        V4      \        V P                  V P                  4       V
P                  R7      VP                  R7      pW«3# )ao  
Common function for redistributing a distributed tensor during backward
and twice-backward backpropagation steps.

Args:
    grad_output: The output gradient tensor.
    previous_spec: DTensorSpec prior to redistribution.
    out_dtype: dtype to cast the returned gradient to. Pinned by autograd
            to match the dtype of the input of the node above this one.
    op_dtype: dtype to run the backward collective at.
    async_op: whether to perform the DTensor redistribute operation
            asynchronously or not. Default: False

Returns:
    A :class:`torch.Tensor` object.
    A :class:`DTensorSpec` object.
©r3  ©r€  Ústrider3  ©rw   r2  r�  rk  )r2  r�  rk  )r
  ©r�  rk  )Ú_local_tensorr3  Útor   Ú_specr©   r2  r   r€  r7  rk  r�  rÜ  r   r]   r\   rˆ   r   re   r,  )r.  r0  r1  r2  r
  r  r  Únormalized_placementsr°  r±  ÚoutputrÓ  s   &&$$$       r$   Ú_redistribute_backwardr?  6  sö  € ð2 ×,Ñ,×2Ñ2Ô2Ø"×0Ñ0×3Ñ3¸(Ð3ÓCˆÜ"Ø×"Ñ"×.Ñ.Ø"×(Ñ(×3Ñ3Ü"Ø!×'Ñ'Ø"×)Ñ)Ó+Øôð
 .9×->Ñ->×-_Ñ-_ô	
ˆô $Ø×*Ñ*Ø$×/Ñ/Ø$×0Ñ0Ø-:×-[Ñ-[ô	
‰ð #×0Ñ0ˆØ"×(Ñ(ˆð .0ÐÜ˜|×6Ñ6¸×8PÑ8PÖQ‰ˆÜ˜7×#Ò# w×';Ñ';×'=Ò'=À6×CTÑCT×CVÒCVØ!×(Ñ(¬«Ö5à!×(Ñ(¨Ö0ñ	 Rô  Ø×!Ñ!ÜÐ.Ó/Ø!×-Ñ-Ø)6×)WÑ)Wô	€Mô 'ØØØØô	€Fð ‡|�|�yÔ Ø—‘˜9Ó%ˆäØ×!Ñ!ÜÐ#Ó$ÜØ×#Ñ#Ø×%Ñ%Ó'Ø—,‘,ô
ð
 *7×)WÑ)Wô	€Dð ˆ<Ðr&   c                   ó,   a € ] tR tRt o V 3R ltRtV tR# )Ú_BackwardDtypeConfigi”  c                óZ   <€ V ^8„  d   Qh/ S[ P                  ;R&   S[ P                  ;R&   # )r   r2  r1  )r*   r3  )r#   rU   s   "€r$   r%   Ú!_BackwardDtypeConfig.__annotate__”  s#   ø‡ ‚ Ù�k‰kÑñ á�{‰{Ñò r&   rf   N©rg   rh   ri   rj   rk   rl   rm   rn   s   @r$   rA  rA  ”  ó   ø‡ ‡ „ r&   rA  c                   ó,   a € ] tR tRt o V 3R ltRtV tR# )Ú_DtypeConfigi™  c                óf   <€ V ^8„  d   Qh/ S[ P                  ;R&   S[ P                  ;R&   S[;R&   # )r   r2  r1  Úbackward_options)r*   r3  rA  )r#   rU   s   "€r$   r%   Ú_DtypeConfig.__annotate__™  s0   ø‡ ‚ Ù�k‰kÑñ á�{‰{Ññ ñ +Ñ*ò r&   rf   NrD  rn   s   @r$   rG  rG  ™  rE  r&   rG  c                   óX   a € ] tR tRt o ]V 3R lR l4       t]V 3R lR l4       tRtV tR# )ÚRedistributeiŸ  c          
      óJ   <€ V ^8„  d   QhRRRS[ RS[S[R3,          RS[RS[/# )r   Úinputr/  r©   r2  .r
  Údtype_config)r   re   r   r9   rG  )r#   rU   s   "€r$   r%   ÚRedistribute.__annotate__¡  sO   ø€ ÷ H
ñ H
ð !ðH
ñ  ð	H
ñ
 ™) S˜.Õ)ðH
ñ ðH
ñ #ñH
r&   c           
     ón  € W@n         VR ,          pVR,          V n        VR,          V n        VR,          pVR,          pWqP                  P                  8w  dy   VP                  P                  VR7      p	\        VVP                  P                  \        VP                  VP                  4       VR7      VP                  P                  R7      p
MVP                  p	VP                  p
W n        V
P                  V8w  d)   \        W#V
P                  R7      p\        V	V
VVRR7      pMT	pT
pVP                  V8w  dY   VP                  V4      p\        VVP                  \        VP                  VP                  4       VR7      VP                  R	7      p\         P"                  ! VVVP$                  R
7      # )rI  r2  r1  r5  r6  r8  )r�  T)r
  r  r9  ©Úrequires_grad)r
  Úbwd_op_dtypeÚbwd_out_dtyper:  r3  r;  r   r<  r2  r   r€  r7  rk  r  r�  r,  ÚdtensorÚDTensorrS  )ÚctxrN  r©   r2  r
  rO  Úbwdr2  r1  r  r  r  r>  s   &&&&&&       r$   ÚforwardÚRedistribute.forward   sŽ  € ð  ŒØÐ-Õ.ˆØ˜z�?ˆÔØ Õ,ˆÔà 
Õ+ˆØ  Õ-ˆ	à×*Ñ*×0Ñ0Ô0Ø ×.Ñ.×1Ñ1¸Ð1ÓAˆLÜ&Ø Ø Ÿ;™;×1Ñ1Ü&ØŸ+™+Ø Ÿ<™<›>Ø"ôð
 27·±×1]Ñ1]ô	‰Lð !×.Ñ.ˆLØ Ÿ;™;ˆLà'Ôà×"Ñ" jÔ0Ü%Ø°\×5MÑ5MôˆKô /ØØØØ!Ø ô‰Fð "ˆFØ&ˆKà�<‰<˜9Ô$Ø—Y‘Y˜yÓ)ˆFÜ%ØØ×&Ñ&Ü&ØŸ+™+Ø Ÿ<™<›>Ø#ôð
 2=×1]Ñ1]ô	ˆKô �ŠàØà×-Ñ-ô
ð 	
r&   c                ó   <€ V ^8„  d   QhRR/# )r   r.  r/  rf   )r#   rU   s   "€r$   r%   rP  ì  s   ø€ ÷ 
ñ 
Ð#4ñ 
r&   c                ó’   € \         P                  VV P                  V P                  V P                  V P
                  4      pVR R R R 3# r•   )ÚNestedRedistributeÚapplyr  r
  rT  rU  )rX  r.  Úoutput_dtensors   && r$   ÚbackwardÚRedistribute.backwardë  sR   € ä+×1Ñ1ØØ×ÑØ�L‰LØ×ÑØ×Ñó
ˆð ØØØØð
ð 	
r&   rf   N)	rg   rh   ri   rj   r÷  rZ  ra  rl   rm   rn   s   @r$   rL  rL  Ÿ  s.   ø‡ € Ø÷H
ó ðH
ðT ÷
ó ö
r&   rL  c                   ó\   a € ] tR tRt o Rt]V 3R lR l4       t]V 3R lR l4       tRtV t	R# )	r^  iý  a“  
This class is used to make the redistribution of a DTensor twice-differentiable.
This is called during the `Redistribute.forward`.
Therefore, `NestedRedistribute.forward` is called during the first backward pass,
and `NestedRedistribute.backward` is called during the second backward pass.

Note: `NestedRedistribute.backward` is not differentiable, and therefore triple
backward is not yet supported.
c          
      ó^   <€ V ^8„  d   QhRRRS[ RS[RS[P                  RS[P                  /# )r   r.  r/  r0  r
  r2  r1  )r   r9   r*   r3  )r#   rU   s   "€r$   r%   ÚNestedRedistribute.__annotate__	  sG   ø€ ÷  
ñ  
ð 'ð 
ñ #ð	 
ñ
 ð 
ñ —+‘+ð 
ñ —;‘;ñ 
r&   c                óÆ   € W0n         VP                  P                  V n        W@n        \        VVVVVR 7      w  rgWpn        \        P                  ! VVVP                  R7      # ))r1  r2  r
  rR  )
r
  r:  r3  Úoriginal_dtyper2  r?  r  rV  rW  rS  )rX  r.  r0  r
  r2  r1  r>  rÓ  s   &&&&&&  r$   rZ  ÚNestedRedistribute.forward  sg   € ð  ŒØ(×6Ñ6×<Ñ<ˆÔØŒä-ØØØØØô
‰ˆð  Ôô �ŠàØà%×3Ñ3ô
ð 	
r&   c                ó   <€ V ^8„  d   QhRR/# )r   Úgrad2_outputr/  rf   )r#   rU   s   "€r$   r%   re  ,  s   ø€ ÷ 
ñ 
Ð$5ñ 
r&   c                ó˜   € V P                   p\        P                  VVV P                  V P                  V P
                  4      pVR R R R R 3# r•   )r  r^  r_  r
  r2  rg  )rX  rj  r0  r`  s   &&  r$   ra  ÚNestedRedistribute.backward+  sZ   € à×(Ñ(ˆô ,×1Ñ1ØØØ�L‰LØ�L‰LØ×Ñó
ˆð ØØØØØð
ð 	
r&   rf   N)
rg   rh   ri   rj   rz   r÷  rZ  ra  rl   rm   rn   s   @r$   r^  r^  ý  s3   ø‡ € ñð ÷ 
ó ð 
ðD ÷
ó ö
r&   r^  c                óˆ  € V ^8„  d   Qh/ ^ \         9   d   \        R,          ;R&   ^\         9   d
   \        ;R&   ^\         9   d8   \        \        \        \        \        R3,          \
        3,          ,          ;R&   ^\         9   d=   \        \        \        P                  \        ,          \        3,          R3,          ;R&   # )r   Nr;   rB   .rÄ   r  r"  )Ú__conditional_annotations__r9   rƒ   re   rd   rT   r€   r   ÚReferenceTyper   r   )r#   s   "r$   r%   r%      sŸ   € × Ñ ÷Z 8Ò 7¤T¨D¥[Ñ 7ñ[ ÷f ;Ò :¬dÑ :ñg ÷Z
 FÒ EœœE¤#¤u¬S°#¨X¥¼Ð";Õ<Õ=Ñ Eñ[
 ÷@ò ”Ü	Œ'×
Ñ
¤
Õ
+¬ZÐ
7Õ8Ø ð"õñ òA r&   )Tr•   )Yrn  r  rP  rÙ  Úloggingr  r   Úcollectionsr   Úcollections.abcr   Ú	functoolsr   Útypingr   r   r   r*   Ú)torch.distributed._functional_collectivesÚdistributedÚ_functional_collectivesr  Útorch.distributed.tensor._apiÚtensorÚ_apirV  r	   Útorch.distributed._mesh_layoutr
   Ú*torch.distributed.tensor._collective_utilsr   Ú&torch.distributed.tensor._dtensor_specr   r   r   r   r   Útorch.distributed.tensor._utilsr   Ú$torch.distributed.tensor.device_meshr   Ú(torch.distributed.tensor.placement_typesr   r   r   r   r   r   Útorch.typesr   r   Útorch.utils._debug_moder   Útorch.utils._typing_utilsr   Ú	getLoggerrg   rÆ   r;   rB   r5   Úcontextmanagerr=   rC   rö  rH   rp   r�   r¦   r±   rƒ   rÄ   rÌ   r  r"  r$  r(  r  r  r	  r,  r?  rA  rG  ÚautogradÚFunctionrL  r^  r%   )rn  s   @r$   Ú<module>rˆ     s  øð÷ Ð Û Û Û Û Û Ý #Ý $Ý ß 'Ñ 'ã ß :Ð :ß /Ó /Ý EÝ 6Ý Q÷õ õ JÝ ;÷÷ ÷ 3Ý 9Ý .ð 
×	Ò	˜8Ó	$€ð 48Ð #Ó 7ð 6;Ð ,Ó :õCð( ×Ñö98ó ð98ðx ×ÑöAó ðAð8 ×Ò˜d¨$Ô/÷ ð  ó 0ð ðF ×Ò˜d¨$Ô/ô˜nó ó 0ðõ4.5õbõ>?ñ4 ADÃÐ Ó Eõ9õxpðn ð ó õ%õ4÷
Añ A÷H8ðv ö	ó ð	ðð
 ðð .2ðð ÷ðD[ð ÷[ô|˜9ô ô
+�9ô +ô[
�5—>‘>×*Ñ*ô [
ô|C
˜Ÿ™×0Ñ0ö C
r&   