Ë
    L²jš ã                  ó:  — d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlm	Z	 d dl
mZ d dlmZmZ d dlZd dlmZ d dlmZ d dlmZ d	d
lmZmZmZ d	dlmZ erd	dlmZmZ d	dlmZm Z m!Z!m"Z" d	dl#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z* d	dl+m,Z,  ejZ                  e.«      Z/ej`                  jc                  e.d«      Z2erd dl3m4Z4 	 	 dEd„Z5dFd„Z6dFd„Z7	 	 	 	 dFd„Z8	 	 	 	 dFd„Z9e G d„ d«      «       Z:dGd„Z;dHd„Z<dId„Z=dJdKd„Z>d„ Z?dLd„Z@d„ ZA	 	 	 	 dMd „ZB	 	 	 	 dNd!„ZC	 	 	 	 dOd"„ZDd#„ ZEd$„ ZFd%„ ZG	 	 	 	 	 	 	 	 dPd&„ZH	 	 	 	 	 	 	 	 	 	 dQd'„ZI	 	 	 	 	 	 	 	 	 	 	 	 dRd(„ZJ	 	 	 	 	 	 	 	 	 	 	 	 	 	 dSd)„ZK	 	 	 	 	 	 	 	 	 	 	 	 	 	 dTd*„ZL	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dUd+„ZM	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dVd,„ZN	 	 	 	 	 	 	 	 	 	 dWd-„ZO	 	 	 	 dXd.„ZP	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dYd/„ZQ	 	 	 	 dZd0„ZR	 	 	 	 	 	 	 	 	 	 d[d1„ZS	 	 	 	 d\d2„ZTe G d3„ d4«      «       ZU	 	 	 	 dXd5„ZV	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d]d6„ZW	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d^d7„ZX	 	 	 	 	 	 	 	 	 	 	 	 	 	 dTd8„ZY	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d_d9„ZZ	 	 	 	 	 	 	 	 	 	 dWd:„Z[	 	 	 	 d`d;„Z\dFd<„Z]dad=„Z^d>„ Z_d?„ Z`	 	 	 	 dFd@„ZadbdA„ZbdcdB„ZcdC„ Zd	 	 	 	 	 	 	 	 dddD„Zey)eé    )ÚannotationsN)Údefaultdict)Ú	dataclass)ÚAnyÚTYPE_CHECKING)Útrace_structured)ÚStorageWeakRef)Ú
OrderedSeté   )ÚconfigÚconfig_commsÚir)ÚWeakDep)ÚIRNodeÚ	Operation)Úestimate_peak_memory_allocfreeÚFreeableInputBufferÚget_freeable_input_bufÚSNodeMemory)Úcontains_collectiveÚcontains_waitÚfind_recursive_deps_of_nodeÚfind_recursive_users_of_nodeÚis_collectiveÚis_fallback_opÚis_wait)ÚVÚoverlap)ÚBaseSchedulerNodec                óR  — ddl m} i }i }| D ]&  }|j                  «       ||<    ||«      €Œ||   ||<   Œ( dd lm} ddlm} |j                  «       } |«       }t        |«      D �	cg c]  }	g ‘Œ }
}	|j                  |
t        |j                  «       «      |«       t        j                  t        j                  |
«      d¬«      j                  j                  «       }t!        |j#                  «       «      D ]  \  }}||   ||<   Œ | D ]  }||v r||   ||<   ||   |_        Œ y c c}	w )Nr   )Ú_get_mm_like_fn)Ú_get_default_group)Údim)Útorch._inductor.schedulerr!   Úget_estimated_runtimeÚtorch.distributedÚdistributedÚ"torch.distributed.distributed_c10dr"   Úget_world_sizeÚrangeÚall_gather_objectÚlistÚvaluesÚtorchÚmedianÚtensorÚtolistÚ	enumerateÚkeysÚoverride_estimated_runtime)Úsnodesr!   Úruntime_estimationsÚruntime_estimations_for_mmsÚsnodeÚdistr"   Ú
world_sizeÚpgÚ_Ú$gathered_runtime_estimations_for_mmsÚ"median_runtime_estimations_for_mmsÚidxs                úT/var/www/html/ia-enhanced/venv/lib/python3.12/site-packages/torch/_inductor/comms.pyÚ6align_runtime_estimations_across_all_distributed_ranksrA   4   s[  € õ :àÐØ"$Ðàò LˆØ%*×%@Ñ%@Ó%BÐ˜EÑ"Ù˜5Ó!Ñ-Ø1DÀUÑ1KÐ'¨Ò.ðLõ
 %ÝEà×$Ñ$Ó&€JÙ	Ó	€Bä˜*Ó%ö?ØŠð?Ð(ð ?ð 	×ÑØ,ÜÐ(×/Ñ/Ó1Ó2Ø
ôô
 */¯©Ü�‰Ð9Ó:Àô*ç�f�V‰V‹Xð 'ô  Ð ;× @Ñ @Ó BÓCò U‰
ˆˆUØ-OÐPSÑ-TÐ# EÒ*ðUð ò FˆØÐ/Ñ/Ø)DÀUÑ)KÐ Ñ&Ø+>¸uÑ+EˆÕ(ñFùò?s   Á&	D$c                ó    — t        | ddd¬«      S )z7
    Greedily schedules waits as late as possible.
    FT©Úraise_commsÚ
sink_waitsÚreorder_for_overlap©Ú_schedule_for_comm©r5   s    r@   rE   rE   Z   s   € ô Ø˜E¨dÈôð ó    c                ó    — t        | ddd¬«      S )z8
    Greedily schedules comms as early as possible.
    TFrC   rG   rI   s    r@   rD   rD   c   s   € ô Ø˜D¨UÈôð rJ   c                ó    — t        | ddd¬«      S )aÀ  
    This achieves the following overall scheduling procedure:
        Step 1: Given that we've currently scheduled comm N, we now schedule all compute nodes
            that are required for comm N + 1 but do not depend on comm N, to run at the same time with comm N.
        Step 2: If all those compute nodes are sufficient to overlap comm N, we're done.
            Otherwise, we now need to look elsewhere to find compute that overlaps with comm N.
            We prioritize compute nodes that are needed sooner.
        Step 3: We schedule the compute nodes dependent on comm N and required for comm N + 1.
        Step 4: We schedule comm N + 1.
        Repeat this for subsequent comm nodes.
    TrC   rG   rI   s    r@   Úreorder_compute_for_overlaprM   l   s   € ô Ø˜D¨TÀtôð rJ   c                ó"   — t        | «      \  }}|S )a  
    Reorders communication ops relative to computation ops to improve communication-compute overlapping and hide comm
    latency.  Stops moving a particular op if it reaches a point that would have increased the peak memory footprint.

    Currently, follows these heuristics (subject to change or tune):
    - never reorders collectives relative to one another, for SPMD safety
    - has an option for per-collective prefetch limit, but does not enable it by default
    - limits the total number of reorder steps to some factor of the graph size to prevent worst-case quadratic
      performance

    Prerequisite: sink_comms_and_waits - ensure comm and wait nodes are scheduled as late as possible, respecting data
    dependencies.  That allows reorder_communication_preserving_peak_memory to take a best case peak-memory snapshot,
    and then monotonically improve latency by moving collectives backward in time.

    Peak memory impact is computed in an iterative fashion.  First, memory use at each timestep is computed, and global
    peak memory is computed as a max over timesteps.  Then, when swapping any two adjacent nodes, only the curr-memory
    for the earlier of the nodes after the swap is affected.  This enables checking step by step whether a swap is
    peak-memory-safe, and bailing out if not.  Example:

    0   n0      C0
    1   n1      C0 + Allocs(n1) - Frees(n1)
    2   n2      C0 + Allocs(n1) - Frees(n1) + Allocs(n2) - Frees(n2)

    0   n0      C0
    1   n2      C0 + Allocs(n2) - Frees(n2)    <-- After moving n2 to Time 1, only time1 memory changes
    2   n1      C0 + Allocs(n2) - Frees(n2) + Allocs(n1) - Frees(n1)

    )Ú6_reorder_communication_preserving_peak_memory_internal)r5   Úreordered_snodesÚ
node_statss      r@   Ú,reorder_communication_preserving_peak_memoryrR      s   € ô@ 	?¸vÓFñ !Ð�jð ÐrJ   c                  ó    — e Zd ZU dZdZded<   dZded<   dZded<   d	Zded
<   dZ	ded<   dZ
ded<   dZded<   dZded<   dZded<   ed„ «       Zy)ÚReorderInfozE
    Debug info describing how an individual snode was reordered
    ÚNoneÚstrÚlimiting_factorr   ÚintÚmovesÚgroupedÚ Úgrouped_infoç      ð¿ÚfloatÚ	comm_timeÚ	comp_timeÚinitial_exposedÚfinal_exposedÚoverlap_infoc                ó4   — | j                   | j                  z
  S ©N©ra   rb   ©Úselfs    r@   ÚimprovementzReorderInfo.improvementµ   ó   € à×#Ñ# d×&8Ñ&8Ñ8Ð8rJ   N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__rW   Ú__annotations__rY   rZ   r\   r_   r`   ra   rb   rc   Úpropertyri   © rJ   r@   rT   rT   ¥   st   … ñð "€O�SÓ!Ø€Eˆ3ƒNØ€GˆSÓØ€L�#ÓØ€IˆuÓØ€IˆuÓØ!€O�UÓ!Ø€M�5ÓØ€L�#Óàñ9ó ñ9rJ   rT   c                ó¤   — | €yt        | t        j                  j                  j                  j
                  «      ryt        | dd «      x}rd|v ryy)NFTÚpython_kernel_nameÚextern_kernels)r   r.   ÚopsÚatenÚ#_scaled_dot_product_flash_attentionÚdefaultÚgetattr)Únoders   s     r@   Úis_gemm_liker{   º   sX   € Ø€|ØäØÜ�	‰	�‰×:Ñ:×BÑBôð ô & dÐ,@À$ÓGÐGÐÐGØ
Ð0Ñ
0ØØrJ   c                óˆ   — ddl m} t        | |«      rt        d„ | j                  D «       «      S t        | j                  «      S )Nr   ©ÚGroupedSchedulerNodec              3  ó2   K  — | ]  }t        |«      –— Œ y ­wre   )Úcontains_gemm_like)Ú.0Úxs     r@   ú	<genexpr>z%contains_gemm_like.<locals>.<genexpr>Ï   s   è ø€ Ò?¨QÔ% a×(Ñ?ùs   ‚)r$   r~   Ú
isinstanceÚanyr5   r{   rz   )r8   r~   s     r@   r€   r€   Ë   s4   € Ý>ä�%Ð-Ô.ÜÑ?°%·,±,Ô?Ó?Ð?ä˜EŸJ™JÓ'Ð'rJ   c                ó„   — ddl m} t        | |«      r&| j                  r| j                  D ]
  } ||«       Œ y  || «       y )Nr   r}   )r$   r~   r„   Útemp_groupingr5   )r8   Úfnr~   Ú_snodes       r@   Ú_temp_group_visit_leavesrŠ   Ô   s;   € Ý>ä�%Ð-Ô.°5×3FÒ3FØ—l‘lò 	ˆFÙˆv�Jñ	ñ 	ˆ5�	rJ   c                ó    — d}| j                   D ]<  }|r|dz  }||j                  «       z  }|sŒ |t        | j                  «       «      › z  }Œ> |S )Nr[   r<   )r5   Úget_namer,   Úget_buffer_names)r8   Ú	with_bufsÚretÚns       r@   Ú_group_namer‘   Þ   s[   € Ø
€CØ�\‰\ò 7ˆÙØ�3‰JˆCØˆq�z‰z‹|ÑˆÚØ”d˜5×1Ñ1Ó3Ó4Ð5Ñ6‰Cð7ð €JrJ   c                ó>   — t        | t        «      xr | j                  S re   )r„   r   Úis_fake)Úds    r@   Ú_is_fake_depr•   é   s   € Ü�aœÓ!Ò/ a§i¡iÐ/rJ   c                óf   — dj                  | D �cg c]  }|j                  «       ‘Œ c}«      S c c}w )Nú~)ÚjoinrŒ   )ÚgnsÚgns     r@   Ú_group_namesr›   í   s%   € Ø�8‰8¨SÖ1 r�R—[‘[•]Ò1Ó2Ð2ùÒ1s   �.c                ó˜   — t        | |«      }t        | ||«      \  }}}}t        t        | |«      «      }d|d<   t	        |«      }	||||||	fS )z*Initialize memory tracking data structures)r   r   N)r   r   ÚdictÚzipÚ_build_candidate_buffer_map)
r5   Úgraph_inputsÚgraph_outputsÚname_to_freeable_input_bufÚpeak_memoryÚsnodes_curr_memoryÚsnodes_allocfreeÚbuf_to_snode_last_useÚ_curr_memoryÚcandidate_buffer_maps
             r@   Ú_initialize_memory_trackingr©   ñ   sz   € ä!7¸ÀÓ!MÐä&ØÐ.°ó	
ñ M€KÐ#Ð%5Ð7Lô
 œ˜FÐ$6Ó7Ó8€Là€L�Ñô 7Ð7LÓMÐð 	ØØØØ"Øðð rJ   c                ó¤   — i }i }t        | «      D ]5  \  }}|dkD  r| |dz
     nd||<   |t        | «      dz
  k  r| |dz      nd||<   Œ7 | d   }|||fS )z/Create double-linked list structure from snodesr   r   N)r2   Úlen)r5   Ú_prevÚ_nextÚir8   Ú_heads         r@   Ú_initialize_double_linked_listr°   
  s{   € ð €EØ€EÜ˜fÓ%ò F‰ˆˆ5Ø()¨Aª�v˜a !™e’}°4ˆˆe‰Ø()¬C°«K¸!©OÒ(;�v˜a !™e’}ÀˆˆeŠðFð �1‰I€EØ�%˜ÐÐrJ   c                ó¢   — t        t        «      }| D ]1  }|j                  j                  D ]  }||   j	                  |«       Œ Œ3 t        |«      S )a}  
    Build inverted index: node -> set of buffers where node appears in successors.

    This optimization reduces buffer iteration from O(total_buffers) to O(buffers_per_node).
    Since buffer successors are immutable during reordering, this map doesn't need updates.

    Returns:
        dict mapping each node to the set of buffers that have this node in their successors
    )r   r
   Ú
mpi_bufferÚ
succ_nodesÚaddr�   )r¦   Únode_to_candidate_bufsÚbufÚ	succ_nodes       r@   rŸ   rŸ     s`   € ô CNÜóCÐð %ò 7ˆàŸ™×2Ñ2ò 	7ˆIØ" 9Ñ-×1Ñ1°#Õ6ñ	7ð7ô
 Ð&Ó'Ð'rJ   c           	     ój   — | D �ci c]#  }|t        d„ |j                  «       D «       «      “Œ% c}S c c}w )zê
    Pre-compute output name sets for all nodes.

    This optimization avoids creating OrderedSet objects repeatedly during
    exposed time calculations.

    Returns:
        dict mapping each node to a set of its output names
    c              3  ó<   K  — | ]  }|j                  «       –— Œ y ­wre   ©rŒ   ©r�   Úos     r@   rƒ   z/_precompute_node_output_sets.<locals>.<genexpr>@  s   è ø€ ÒD¨1˜!Ÿ*™*Ÿ,ÑDùó   ‚)r
   Úget_outputs)r5   r8   s     r@   Ú_precompute_node_output_setsr¿   3  s<   € ð SYöØINˆŒzÑD°×0AÑ0AÓ0CÔDÓDÑDòð ùò s   …(0c                óX   — t        | «      rt        j                  S t        j                  S re   )r   r   Ú*reorder_sink_runtime_estimations_comm_multÚ.reorder_sink_runtime_estimations_non_comm_mult©r8   s    r@   Ú_op_runtime_estimate_multrÄ   D  s$   € ô ˜5Ô!Ü×FÑFÐFä×FÑFÐFrJ   c                ó@   — t        | j                  dd«      x}rd|v ryy)zÎ
    Filtering out ops that contain Collective and Wait inside and considered as Collectives.
    See contains_collective function.
    If the op contains Wait inside - consider as Synchronous compute.
    rs   Nz-torch.ops._dtensor.shard_dim_alltoall.defaultFT)ry   rz   )r8   rs   s     r@   Úis_async_collectiverÆ   M  s-   € ô % U§Z¡ZÐ1EÀtÓLÐLÐÐLØ:Ð>PÑPØàrJ   c                ó"   — t        | t        «      S re   )r   rÆ   rÃ   s    r@   Úcontains_async_collectiverÈ   Z  s   € Ü˜uÔ&9Ó:Ð:rJ   c                óN   — g }| }	 |�|j                  |«       ||k(  r	 |S ||   }Œ!)aA  
    Traverse doubly-linked list from head to tail and return nodes as a list.

    Args:
        head: Starting node of the segment
        tail: Ending node of the segment (inclusive)
        next_dict: Dictionary mapping each node to its next node

    Returns:
        List of nodes from head to tail (inclusive)
    )Úappend)ÚheadÚtailÚ	next_dictr�   r�   s        r@   Ú_group_nodes_from_linked_listrÎ   ^  s@   € ð  €CØ€AØ
Øˆ=Ø�J‰J�qŒMØ�Š9Øà€Jð �a‰Lˆð rJ   c                ó2   — ||    }||   }t        ||z  «      S )zr
    Check if a wait node corresponds to a given collective node.
    Uses pre-computed sets for O(1) lookup.
    )Úbool)Úcollective_snodeÚ
wait_snodeÚnode_output_setsÚnode_dep_setsÚcollective_outsÚ
unmet_depss         r@   Ú!_is_corresponding_collective_waitr×   y  s)   € ð 'Ð'7Ñ8€OØ˜zÑ*€JÜ�
˜_Ñ,Ó-Ð-rJ   c                ó¨  ‡‡— ‰|    }dŠ||    }d}g }||    }	|	�µ||	   }
|
|z  r|d|	j                  «       › d�z  }n“t        |	«      r#t        |	«      sn||j                  |	«       ||	   }	ŒRt	        |	«      rd}|D ]  }t        | |	||«      sŒd} n |rn<‰}d
ˆˆfd„}t        |	|«       ‰}|d|	j                  «       › d	||z
  › d�z  }||	   }	|	�Œµ|‰|fS )zÛ
    Calculate exposed communication time by iterating directly over linked list.
    Avoids O(N) list construction for each call.

    The collective_snode is the starting point, iteration continues via next_dict.
    ç        r[   z->W[ú]FTc                ó   •— ‰‰|    z  Šy re   rq   ©r‰   r`   Úruntimess    €€r@   Úaccumulate_timez9_coll_exposed_communication_time.<locals>.accumulate_time·  ó   ø€ à˜ &Ñ)Ñ)‰IrJ   ú+ú[©r‰   r   ÚreturnrU   )rŒ   r   rÈ   rÊ   r   r×   rŠ   )rÑ   rÍ   rÝ   rÓ   rÔ   r_   rÕ   rc   Úcollectives_foundr8   rÖ   Úhas_wait_for_collectives_foundÚ_collÚcomp_time_beforerÞ   Úcomp_time_afterr`   s     `             @r@   Ú _coll_exposed_communication_timeré   ˆ  sD  ù€ ð Ð)Ñ*€IØ€IØ&Ð'7Ñ8€OØ€LØ13ÐàÐ&Ñ'€EØ
Ð
Ø" 5Ñ)ˆ
à˜Ò'Ø˜d 5§>¡>Ó#3Ð"4°AÐ6Ñ6ˆLØä˜uÔ%Ü,¨UÔ3Øà!×(Ñ(¨Ô/Ø! %Ñ(�ØÜ˜ÔØ-2Ð*Ø*ò �Ü4Ø$ eÐ-=¸}õð 6:Ð2Ùðñ .Øà$Ðö	*ô 	! ¨Ô8Ø#ˆØ˜!˜EŸN™NÓ,Ð-¨Q¨ÐAQÑ/QÐ.RÐRSÐTÑTˆà˜%Ñ ˆðG Ñ
ðJ �i Ð-Ð-rJ   c                ó®  ‡‡— d}dŠd}g }||    }	|	�Àt        |	«      r|j                  |	«       t        |	«      r]t        |	| ||«      r‰|	   }|d|	j	                  «       › d�z  }nnt        |	«      sdŠ||	   }	Œg|D ]  }
t        |	|
||«      sŒdŠ n ||	   }	Œ†‰}dˆˆfd„}t        |	|«       ‰}|d|	j	                  «       › d||z
  › d�z  }||	   }	|	�ŒÀ|‰|fS )	zò
    Calculate exposed communication time for a wait operation by iterating
    directly over linked list backwards. Avoids O(N) list construction.

    Iterates from wait_snode backwards using prev_dict to find corresponding collective.
    rÙ   r[   z->C[rÚ   c                ó   •— ‰‰|    z  Šy re   rq   rÜ   s    €€r@   rÞ   z9_wait_exposed_communication_time.<locals>.accumulate_timeó  rß   rJ   rà   rá   râ   )r   rÊ   r   r×   rŒ   rÈ   rŠ   )rÒ   rË   Ú	prev_dictrÝ   rÓ   rÔ   r_   rc   Úwaits_foundr8   Úwrç   rÞ   rè   r`   s      `          @r@   Ú _wait_exposed_communication_timerï   Ä  s>  ù€ ð €IØ€IØ€LØ+-€Kà�jÑ!€EØ
Ð
Ü˜ÔØ×Ñ˜uÔ%Ü˜uÔ%Ü0Ø�zÐ#3°]ôð % U™O�	Ø $ u§~¡~Ó'7Ð&8¸Ð :Ñ:�Øä,¨UÔ3Ø�	Ø! %Ñ(�Øà$ò �AÜ8Ø˜qÐ"2°Mõð %(˜	Ùðð " %Ñ(�Øà$Ðö	*ô 	! ¨Ô8Ø#ˆØ˜!˜EŸN™NÓ,Ð-¨Q¨ÐAQÑ/QÐ.RÐRSÐTÑTˆà˜%Ñ ˆðG Ñ
ðJ �i Ð-Ð-rJ   c                ól   — ||    }|r|||<   |||<   ||   }|r| ||<   ||| <   ||| <   | ||<   || k(  r|S |S )a�  
    Swap positions of candidate and group in doubly-linked list.

    Transforms:
    candidate_prev -> candidate -> group_head...group_tail -> group_tail_next
    Into:
    candidate_prev -> group_head...group_tail -> candidate -> group_tail_next

    Args:
        candidate: Node to swap with group
        group_head: First node of group
        group_tail: Last node of group
        prev_dict: Dictionary mapping nodes to their previous nodes
        next_dict: Dictionary mapping nodes to their next nodes
        head: Current head of the linked list

    Returns:
        New head of the linked list (may change if candidate was the head)
    rq   )Ú	candidateÚ
group_headÚ
group_tailrì   rÍ   rË   Úcandidate_prevÚgroup_tail_nexts           r@   Ú _perform_double_linked_list_swaprö      ss   € ð8 ˜yÑ)€NÙØ$.ˆ	�.Ñ!Ø*€IˆjÑð   
Ñ+€OÙØ%.ˆ	�/Ñ"Ø*€IˆiÑð &€IˆiÑØ%€IˆjÑð ˆyÒØÐØ€KrJ   c                ón  — i }d}	|s)t        ||z
  ||   d   |z
  |j                  z   «      }	|	|fS | }
|D ]R  }||   d   |
z   }|||<   t        |	|«      }	|j                  |«      }|€Œ3|D ]  }|
|j                  j                  z  }
Œ ŒT ||   d   |
z   |j                  z   }||| <   t        |	|«      }	|	|fS )a  
    Calculate potential peak memory after swapping candidate with group (reorder version).

    Computes new memory levels for all affected nodes and returns the potential
    peak memory along with cached post-allocation memory values for each node.

    Args:
        candidate: Node being moved
        gns: Group nodes
        group_tail: Last node of group
        group_peak_memory: Current peak memory within the group
        candidate_delta_mem: Net memory change from candidate (alloc - free)
        candidate_allocfree: Candidate's allocation/free info
        group_n_to_bufs_after_swap_dealloc_by_candidate: Buffers whose deallocation moves to candidate
        curr_memory: Current memory state dict

    Returns:
        Tuple of (potential_peak_memory, post_alloc_update_dict)
    r   r   )ÚmaxÚ
size_allocÚgetr²   Ú	size_free)rñ   r™   ró   Úgroup_peak_memoryÚcandidate_delta_memÚcandidate_allocfreeÚ/group_n_to_bufs_after_swap_dealloc_by_candidateÚcurr_memoryÚ_post_alloc_updateÚpotential_peakÚmem_after_reorder_deltarš   Úgn_post_alloc_memÚbufsr¶   Úcandidate_mem_post_allocs                   r@   Ú(_calculate_potential_peak_memory_reorderr  1  s+  € ð> 8:ÐØ€NÙ:äØÐ 3Ñ3Ø˜
Ñ# AÑ&Ø!ñ"à!×,Ñ,ñ-ó
ˆð Ð1Ð1Ð1ð %8Ð#7ÐØò 	DˆØ'¨™O¨AÑ.Ð1HÑHÐØ!2Ð˜2ÑÜ˜^Ð->Ó?ˆà>×BÑBÀ2ÓFˆØÑØò D�à'¨3¯>©>×+CÑ+CÑCÑ'ñDð	Dð 	�JÑ Ñ"Ø
!ñ	"à
×
(Ñ
(ñ	)ð ð
 %=Ð�yÑ!Ü˜Ð)AÓB€NØÐ-Ð-Ð-rJ   c
                óþ  — |sK|D ]  }
||
   }|d   |z
  |d   |z
  f||
<   Œ ||   d   |j                   z   }||j                  z
  }||f|| <   y|j                  «       D ]  }|D ]  }| ||<   Œ	 Œ d}|D ]R  }||   }t        d„ ||   D «       «      }||z  }|	|   xj                  |z  c_        ||	|   j                  z
  }||f||<   ŒT ||    }|	|    xj                  |z  c_        ||	|    j                  z
  }||f|| <   y)aN  
    Update memory tracking structures after swap (reorder version).

    Updates curr_memory, buf_to_snode_last_use, and snodes_allocfree dictionaries
    to reflect the new memory state after swapping candidate with group.

    Args:
        candidate: Node that was moved
        gns: Group nodes
        group_tail: Last node of group
        candidate_delta_mem: Net memory change from candidate (alloc - free)
        candidate_allocfree: Candidate's allocation/free info
        group_n_to_bufs_after_swap_dealloc_by_candidate: Buffers whose deallocation moves to candidate
        post_alloc_update: Cached post-allocation memory values
        curr_memory: Current memory state dict (mutated)
        buf_to_snode_last_use: Buffer to last-use node mapping (mutated)
        snodes_allocfree: Node allocation/free info dict (mutated)
    r   r   Nc              3  óH   K  — | ]  }|j                   j                  –— Œ y ­wre   ©r²   rû   ©r�   r¶   s     r@   rƒ   z=_update_memory_tracking_after_swap_reorder.<locals>.<genexpr>­  s"   è ø€ ò 2
àð �N‰N×$Õ$ñ2
ùó   ‚ ")rù   rû   r-   Úsum)rñ   r™   ró   rý   rþ   rÿ   Úpost_alloc_updater   r¦   r¥   rš   ÚcmÚ_candidate_post_alloc_memÚ_candidate_post_free_memr  r¶   Ú"size_free_to_move_to_candidate_sumr�   Ú_gn_post_alloc_memÚsize_free_to_move_to_candidateÚgn_post_free_memÚcandidate_post_free_mems                         r@   Ú*_update_memory_tracking_after_swap_reorderr  t  s¥  € ñ< ;Øò 	ˆBØ˜R‘ˆBà�1‘Ð+Ñ+Ø�1‘Ð+Ñ+ðˆK˜ŠOð	ð ˜
Ñ# AÑ&Ð)<×)GÑ)GÑGð 	"ð &Ð(;×(EÑ(EÑEð 	!ð &Ø$ð"
ˆ�IÑð 	ð @×FÑFÓHò 3ˆØò 	3ˆCØ)2Ð! #Ò&ñ	3ð3ð /0Ð&Øò 
@ˆØ"3°AÑ"6ÐÜ.1ñ 2
àFÀqÑIô2
ó /
Ð&ð 	+Ð.LÑLÐ*à˜Ñ×%Ò%Ð)GÑGÕ%Ø 2Ð5EÀaÑ5H×5RÑ5RÑ RÐØ,Ð.>Ð?ˆ�AŠð
@ð !2°)Ñ <ÐØ�YÑ×)Ò)Ð-OÑOÕ)à!Ð$4°YÑ$?×$IÑ$IÑIð ð 	"Øð€K�	ÒrJ   c                ó¸   — t        t        «      }|j                  | t        «       «      }t        |«      }|D ]   }||   }||v sŒ||   j	                  |«       Œ" |S )aŽ  
    Find buffers whose last use will change after swapping candidate with group.

    When we swap [candidate [group]] to [[group] candidate], some buffers that
    were last used by a group node will now be last used by candidate instead.
    This affects memory deallocation timing.

    Args:
        candidate: The node being moved
        gns: Group nodes being swapped with candidate
        buf_to_snode_last_use: Mapping of buffers to their current last-use nodes
        candidate_buffer_map: Pre-computed map of node -> buffers using that node

    Returns:
        Dict mapping group nodes to buffers that will change their last-use node
    )r   r,   rú   r
   rÊ   )	rñ   r™   r¦   r¨   rÿ   Úcandidate_bufsÚgns_setr¶   Úsnode_last_uses	            r@   Ú#_find_buffers_with_changed_last_user  Á  so   € ô0 	”DÓð 4ð *×-Ñ-¨i¼»ÓF€NÜ˜‹o€Gàò XˆØ.¨sÑ3ˆØ˜WÒ$Ø;¸NÑK×RÑRÐSVÕWðXð
 ;Ð:rJ   c                óœ   — t         j                  s t        | «      rdd| j                  «       › �fS t         j                  st        | «      ryy)aa  
    Check if a candidate node can be grouped with collective during reordering.

    This pass processes collectives left to right, so we avoid grouping with
    already-processed collectives based on configuration.

    Args:
        candidate: Node to check for groupability

    Returns:
        Tuple of (is_groupable, reason_if_not_groupable)
    Fzcandidate contains_collective )Fr€   ©TN)r   Ú(reorder_iterative_group_with_collectivesrÈ   rŒ   Ú)reorder_iterative_use_runtime_estimationsr€   ©rñ   s    r@   Ú_is_node_groupable_for_reorderr"  è  sO   € ô$ ×@Ò@Ü$ YÔ/àØ0°×1CÑ1CÓ1EÐ0FÐGðð ô ×AÒAÜ˜iÔ(Ø.ØrJ   c                ó  ‡— | }|D �ci c]  }|||   j                   “Œ }	}t        |	D �cg c]  }|	|   ‘Œ	 c}«      }
t        |D �cg c]  }||   j                  ‘Œ c}«      }d|
› d|› d�Šg d¢}|j                  «       D ��cg c]Ž  \  }}t	        |«      |j
                  dz  |j                  dz  |j                  dz  |j                  dz  |j                   dz  |j                  |j                  |j                  |j                  |j                  g‘Œ� }}}t        j                  j                  d«      rddlm} ‰ |||¬	«      z  Šn8‰d
z  Š‰t#        |«      dz   z  Š‰dj%                  t'        t"        |«      «      z  Št)        |d|«      }t+        |«      |k(  sJ ‚t-        |||«      \  }}}}‰d|› �z  Š‰d|› �z  Št.        j1                  ‰«       t3        dd„ ˆfd„¬«       |S c c}w c c}w c c}w c c}}w )aÉ  
    Format reordering statistics, log them, and return final node list.

    Computes improvement metrics, creates a formatted table (using tabulate if
    available), validates the reordered node count, recalculates peak memory,
    and logs all information.

    Args:
        stats: Per-node reordering statistics
        head: Head of the reordered linked list
        next_dict: Linked list next pointers
        original_snodes_num: Original number of nodes (for validation)
        peak_memory: Initial peak memory before reordering
        name_to_freeable_input_buf: Buffer memory tracking info
        graph_outputs: Graph output names

    Returns:
        Final reordered list of scheduler nodes
    zAreorder_communication_preserving_peak_memory improved overlap by z
 ns after z reorders.
)zCollective nodeúcomm_time(us)úcomp_time(us)úinitial exposed(us)úfinal exposed(us)úimprovement(us)úlimiting factorrY   rZ   r\   rc   ç     @�@Útabulater   ©r+  ©Úheadersú>Please `pip install tabulate` to nicely render overlap stats.
ú
Nz
 peak_memory_before:z
 peak_memory_after:Úartifactc                 ó   — dddœS )NrR   Ústring©ÚnameÚencodingrq   rq   rJ   r@   ú<lambda>z2_format_and_log_reordering_stats.<locals>.<lambda>a  s   € ØBØ ñ
€ rJ   c                 ó   •— ‰ S re   rq   )Úreorder_log_strs   €r@   r7  z2_format_and_log_reordering_stats.<locals>.<lambda>e  s   ø€ ˜?€ rJ   ©Úmetadata_fnÚ
payload_fn)ri   r  rY   ÚitemsÚnode_summaryr_   r`   ra   rb   rW   rZ   r\   rc   Ú	importlibÚutilÚ	find_specr+  rV   r˜   ÚmaprÎ   r«   r   Úoverlap_logÚinfor   )ÚstatsrË   rÍ   Úoriginal_snodes_numr£   r¢   r¡   rQ   r8   ri   Útotal_improvementÚtotal_movesr.  Ú	node_infoÚrowsr+  Ú
new_snodesÚnew_peak_memoryr<   r9  s                      @r@   Ú _format_and_log_reordering_statsrM    sF  ø€ ð8 €JØEOÖP¸E�5˜* UÑ+×7Ñ7Ñ7ÐP€KÐPÜ¸[ÖI°E˜[¨Ó/ÒIÓJÐÜ¸JÖG°5�z %Ñ(×.Ó.ÒGÓH€Kð LÐL]ÐK^ð _Ø�˜lð	,ð ò€Gð6 !+× 0Ñ 0Ó 2÷ñ ˆE�9ô ˜ÓØ×Ñ #Ñ%Ø×Ñ #Ñ%Ø×%Ñ%¨Ñ+Ø×#Ñ# cÑ)Ø×!Ñ! CÑ'Ø×%Ñ%Ø�O‰OØ×ÑØ×"Ñ"Ø×"Ñ"ò	
ð€Dñ ô  ‡~�~×Ñ 
Ô+Ý%à™8ØØô
ñ 	
‰ð
 	ØMñ	
ˆð 	œ3˜w›<¨$Ñ.Ñ.ˆØ˜4Ÿ9™9¤S¬¨d£^Ó4Ñ4ˆä.¨t°T¸9ÓE€JÜˆz‹?Ð1Ò1Ð1Ð1Ü=ØÐ.°ó Ñ€O�Q˜˜1ð Ð/°¨}Ð=Ñ=€OØÐ.¨Ð.?Ð@Ñ@€Oä×Ñ�_Ô%ÜØñ
ó +õð ÐùòK QùÚIùÚGùó&s   ˆG,ªG1ÁG6ÂBG;c                ó¬  — d}| D ]  }t        |«      sŒd} n |s| i fS t        | «      }t        t        j                  j
                  j                  «       «      }t        t        j                  j                  «       «      }t        | ||«      \  }}}}	}
}| D �ci c]  }|t        |«      t        |«      z  “Œ }}| D �ci c]#  }|t        d„ |j                  «       D «       «      “Œ% }}| D �ci c]  }|t        d„ |j                  D «       «      “Œ! }}i }d}t        | «      \  }}}t        j                   }d}|}t        j"                  }d}|��½||   ��·||   }|r�n®t%        |«      s|}Œ |�||k\  r�n—|dz  }t'        «       x}||<   t)        |||||«      \  }}}||_        ||_        ||z
  x|_        |_        ||_        ||   }|}|} i }!d}"||   d   }#t        ||   «      }$t        ||   «      }%|��t        j4                  r4|j0                  t        j6                   |j*                  z  k  r	d	|_        �nÇt        j:                  st        |«      r	d
|_        �n£|$|%z
  }&|&sd}'n||   }(t=        |(|&z  «      }'|'rýt?        |«      \  })}*|)r¡|}|$jA                  ||   «       |%jA                  ||   «       t        j4                  r9tC        |«      rtE        ||||||«      \  }}}+||f|!|<   t%        |«      s|"||   z  }"tG        |#||   d   «      }#|xjH                  dz  c_$        ||   }�Œ;d|jK                  «       › d|j                  «       D �,cg c]  },|,jK                  «       ‘Œ c},› d|*› �}-|-|_        �n‡t        j4                  �rWt%        |«      sã||   }.|.dkD  �rAt        |!«      dkD  �r2tG        d|j*                  |j,                  z
  «      }/tG        d|j*                  |j,                  z
  |.z
  «      }0|0|/z
  }1|!jM                  «       D ].  \  }2}3tG        d|2|3z
  «      }4tG        d|2|3z
  |.z   «      }5|1|5|4z
  z  }1Œ0 |1dkD  rd|.› d|1› �|_        �n®|!jO                  «       D ]  \  }6\  }2}3|2|3|.z
  f|!|6<   Œ ni|"dkD  rdt)        |||||«      \  }}}+tG        d||z
  «      }/tG        d||z
  |"z   «      }0|0|/z
  }1|1dkD  r&d|jK                  «       › d|"› d|1› d|› d|› �
|_        �ntQ        || |«      }7||   }8|8jR                  |8jT                  z
  }9tW        ||7|	|«      }:tY        ||7| |#|9|8|:|«      \  };}<|;|z
  |t        jZ                  z  kD  rd|;› d|› �|_        nª|xj\                  dz  c_.        |dz  }t_        ||| |||«      }t)        |||||«      \  }}}||_        ||_        ||_        ||z
  |_        ta        ||7| |9|8|:|<||	|«
       |r/ddl1m2}=  |=||7tg        |7«      tQ        |d|«      |
||||d|:«      }|rn	||   }|��Œ|}|�||   ��Œ·t        jh                  stQ        |d|«      }>|>|fS tk        ||||||
|«      }>|>|fS c c}w c c}w c c}w c c},w )z�
    Internal testing helper that also returns debug info.
    Returns:
        - reordered snodes list
        - dict {snode: ReorderInfo}
    FTc              3  ó<   K  — | ]  }|j                  «       –— Œ y ­wre   rº   r»   s     r@   rƒ   zI_reorder_communication_preserving_peak_memory_internal.<locals>.<genexpr>�  ó   è ø€ ÒC¨!˜Ÿ™ŸÑCùr½   c              3  óL   K  — | ]  }t        |«      rŒ|j                  –— Œ y ­wre   ©r•   r5  ©r�   r”   s     r@   rƒ   zI_reorder_communication_preserving_peak_memory_internal.<locals>.<genexpr>“  ó   è ø€ ò 
Ø¼LÈ½OˆA�F�Fñ
ùó   ‚$“$r   Nr   rÙ   ú unexposed by runtime estimationszcollective orderingú$data dependency detected
 candidate:z(outs:z)
 non_group_reason:úcandidate has compute z,, group contains waits, total_exposed_delta z
candidate z is collective, group_runtime:z, exposed_delta:z c_comm_time:z c_comp_time:úpeak memory new:ú	 vs base:©Ú!_debug_iterative_memory_recomputerR   )6r   r«   r
   r   Úgraphr    r3   Úget_output_namesr©   Úestimate_op_runtimerÄ   Ú	frozensetr¾   Úunmet_dependenciesr°   r   Ú(reorder_iterative_debug_limit_to_reorderÚ(reorder_iterative_debug_memory_recomputerÈ   rT   ré   r_   r`   ra   rb   rc   r   Ú)reorder_iterative_extra_comm_comp_overlaprW   Ú,reorder_iterative_unsafe_collectives_reorderrÐ   r"  Úupdater   rï   rø   rZ   rŒ   r-   r=  rÎ   rù   rû   r  r  Ú$reorder_iterative_peak_memory_budgetrY   rö   r  Úcomms_debugr\  r›   Úreorder_sink_verbose_loggingrM  )?r5   Úhas_collectivesr8   rF  r    r¡   r£   r§   r¥   r¦   r¢   r¨   rÝ   rÓ   rÔ   rE  rH  r¬   r­   r¯   Ú debug_num_collectives_to_reorderÚnum_processed_collectivesÚcurrÚ debug_iterative_memory_recomputeÚiterative_recompute_errorÚ
_next_currrD  r_   r`   rc   rñ   rò   ró   Úgroup_waitsÚgroup_runtimerü   Úgroup_unmet_deps_namesÚgroup_output_namesÚdata_deps_namesÚdata_depÚcandidate_out_namesÚis_groupable_resultÚgrouping_reasonr<   r¼   ÚmsgÚ	c_runtimeÚexposed_beforeÚexposed_afterÚexposed_deltaÚgw_comm_timeÚgw_comp_timeÚgw_exposed_beforeÚgw_exposed_afterÚgwr™   rþ   rý   rÿ   r  r  r\  rK  s?                                                                  r@   rO   rO   k  s…  € ð €OØò ˆÜ˜uÕ%Ø"ˆOÙðñ Ø�rˆzÐä˜f›+Ðä$.¬q¯w©w×/CÑ/C×/HÑ/HÓ/JÓ$K€LÜ%/´·±×0HÑ0HÓ0JÓ%K€Mô 	$ F¨L¸-ÓHñØØØØØ"Øð
 ö0àð 	Ô" 5Ó)Ô,EÀeÓ,LÑLÑLð0€Hð 0ð RXöAØHMˆŒyÑC¨u×/@Ñ/@Ó/BÔCÓCÑCðAÐð Að ö	>ð ð 	Œyñ 
Ø!×4Ñ4ô
ó 
ñ 	
ð>€Mð >ð 35€Eà€Kä8¸Ó@Ñ€Eˆ5�%ô 	×=Ñ=ð %ð &'ÐØ%*€Dä×=Ñ=ð %ð !&Ðà
Ñ
˜u T™{Ñ6Ø˜4‘[ˆ
Ù$Ùä(¨Ô.ØˆDØà+Ð7Ø%Ð)IÒIáØ! QÑ&Ð!ä(›]Ð*ˆˆu�T‰{Ü-MØ�%˜Ð#3°]ó.
Ñ*ˆ	�9˜lð #ˆŒØ"ˆŒØ4=À	Ñ4IÐIˆÔ˜tÔ1Ø(ˆÔà˜$‘Kˆ	Øˆ
Øˆ
ØˆØˆØ(¨Ñ.¨qÑ1Ðô ",¨M¸$Ñ,?Ó!@ÐÜ'Ð(8¸Ñ(>Ó?ÐàÑ#Ü×EÒEØ×"Ñ"Ü×IÑIÐIØ—.‘.ñ!ò!ð (J�Ô$Ùô !×MÒMÜ'¨	Ô2à'<�Ô$Ùð 5Ð7IÑIˆOÙ"Ø ‘ð '7°yÑ&AÐ#ÜÐ 3°oÑ EÓF�áÜ7UØó8Ñ4Ð# _ñ 'Ø!*�Jð +×1Ñ1°-À	Ñ2JÔKØ&×-Ñ-Ð.>¸yÑ.IÔJä#×MÒMÜ(¨Ô3Ü6VØ )Ø %Ø %Ø (Ø 0Ø -ó7Ñ3˜I y°!ð 6?À	Ð5I˜K¨	Ñ2Ü8¸ÔCØ)¨X°iÑ-@Ñ@˜Mä(+Ø)¨<¸	Ñ+BÀ1Ñ+Eó)Ð%ð —L’L AÑ%•LØ % iÑ 0�IÙð(Ø(1×(:Ñ(:Ó(<Ð'=¸VÐ[d×[pÑ[pÓ[rÖDsÐVWÀQÇZÁZÅ\ÒDsÐCtð u/Ø/>Ð.?ðAð ð
 ,/�DÔ(Ùä×EÓEä0°Ô;Ø (¨Ñ 3�Ià  1“}¬¨[Ó)9¸AÓ)=ä),¨Q°·±ÀÇÁÑ0OÓ)P˜ä(+Ø˜tŸ~™~°·±Ñ>ÀÑJó)˜ð )6¸Ñ(F˜Ø:E×:LÑ:LÓ:Nò RÑ6˜L¨,ä03°A°|ÀlÑ7RÓ0SÐ-ä/2Ø ! <°,Ñ#>ÀÑ#Jó0Ð,ð *Ð-=Ð@QÑ-QÑQ™MðRð )¨1Ò,à"8¸¸ð DNØN[È_ð!^ð !Ô0ñ "ð "-×!2Ñ!2Ó!4ò"ñ ! ñ %Ø ,Ø ,ð %1Ø$0°9Ñ$<ð3" ¨B¢ñ	"ð % qÒ(Ü2RØ% u¨hÐ8HÈ-ó3Ñ/˜	 9¨aô *-¨Q°	¸IÑ0EÓ)F˜ä(+¨A¨y¸9Ñ/DÀ}Ñ/TÓ(U˜Ø(5¸Ñ(F˜Ø(¨1Ò,à",¨Y×-?Ñ-?Ó-AÐ,Bð C2Ø2?°ð A2Ø2?°ÀÈiÈ[ÐXeÐfoÐepð!rð !Ô0ñ
 "ô ,IØ˜J¨ó,ˆCð 0@À	Ñ/JÐà#×.Ñ.Ð1D×1NÑ1NÑNð  ô  4Ø˜sÐ$9Ð;Oóð <ô 9ØØØØ%Ø'Ø'ØCØ ó	ñ /ˆNÐ.ð  Ñ,Ø¤× QÑ QÑQòRð ' ~Ð&6°iÀ¸}ÐMð Ô$ð Ø�JŠJ˜!‰O�JØ˜1ÑˆKä4Ø˜: z°5¸%ÀóˆEô 2RØ�e˜XÐ'7¸ó2Ñ.ˆI�y ,ð 'ˆDŒNØ&ˆDŒNØ ,ˆDÔØ!*¨YÑ!6ˆDÔä6ØØØØ#Ø#Ø?Ø"ØØ%Ø ôñ 0õ Ká,MØØÜ  Ó%Ü1°%¸¸uÓEØ.Ø!ØØ Ø$ØBØCó-Ð)ñ -ØØ˜jÑ)ˆIðC Ò#ðD ˆðK Ð
˜u T™{Ò6ôN ×4Ò4Ü2°5¸$ÀÓFˆ
Ø˜5Ð Ð ä1ØØØØØØ"Øó€Jð �uÐÐùòo	0ùòAùò>ùòp Ets   ÂYÂ?(YÃ-$YÍY
c                óö  ‡‡‡‡‡‡‡‡‡‡‡‡— i }i Ši i i cŠŠŠt        | «      D ]y  \  }}|j                  «       D ]  }|||<   Œ	 |j                  «       D ]  }|‰|<   Œ	 |‰|j                  «       <   |j                  «       }	t        j
                  ‰|	<   d‰|	<   |‰|	<   Œ{ d}
| D ]€  }|rZt        |«      rO|
‰|j                  «       <   |j                  D ]'  }‰|   j                  «       }t        ‰|   |
«      ‰|<   Œ) |
dz  }
Œ_|sŒbt        |«      sŒnd‰|j                  «       <   Œ‚  G ˆˆˆˆfd„d«      Š| D �ci c]  }|t        d„ |j                  D «       «      “Œ! c}Šg Št        t        «      Š| D �ci c]  }|t        |«      “Œ c}Š‰j                  «       D ]J  \  }}t        |«      dk(  rt!        j"                  ‰ ‰|«      «       |D ]  }‰|   j%                  |«       Œ ŒL g Šˆˆˆˆˆfd„Šˆfd„Šˆˆˆˆfd„}‰r@t!        j&                  ‰«      j(                  }|rt        |«      r	 ||«       n ‰|«       ‰rŒ@‰j+                  «       D ]  }t        |«      dk(  rŒJ d	‰› �«       ‚ ‰S c c}w c c}w )
aÂ  
    Schedule `snodes` for various comm optimization objectives.

    Args:
        snodes: the nodes to be scheduled.
        raise_comms: whether to greedily schedule collectives as early as possible
        sink_wait: whether to greedily schedule waits as late as possible
        reorder_compute_for_overlap: whether to reorder compute nodes to
            optimize for compute/communication overlapping.

    Returns:
        The new schedule order.

    Some notes on the synergy between different options:
        - `raise_comms` provides more overlapping oppurtunies for `reorder_compute_for_overlap`.
        - When both `raise_comms` and `sink_waits` is `True`, `raise_comms` is prioritized.
    r   r   c                  ó&   •— e Zd Zdˆ ˆˆˆfd„Zd„ Zy)ú$_schedule_for_comm.<locals>.Runnablec                ó¤   •— || _         t        t        |j                  «       «      «      }‰|   j	                  «       }‰|   ‰|   ‰|   f| _        y re   )r8   ÚnextÚiterÚget_operation_namesrŒ   Úscore)rh   r8   r5  Ú
fused_nameÚname_to_fused_nodeÚscores_0Úscores_1Úscores_2s       €€€€r@   Ú__init__z-_schedule_for_comm.<locals>.Runnable.__init__  sV   ø€ ØˆDŒJÜœ˜U×6Ñ6Ó8Ó9Ó:ˆDØ+¨DÑ1×:Ñ:Ó<ˆJà˜Ñ$Ø˜Ñ$Ø˜Ñ$ðˆD�JrJ   c                ó4   — | j                   |j                   k  S re   ©r‹  )rh   Úothers     r@   Ú__lt__z+_schedule_for_comm.<locals>.Runnable.__lt__  s   € Ø—:‘: §¡Ñ+Ð+rJ   N)rã   rU   )rk   rl   rm   r‘  r•  )r�  rŽ  r�  r�  s   €€€€r@   ÚRunnabler†    s   ø„ ÷	ð 	ó	,rJ   r–  c              3  ó4   K  — | ]  }|j                   –— Œ y ­wre   )r5  )r�   Údeps     r@   rƒ   z%_schedule_for_comm.<locals>.<genexpr>  s   è ø€ ÒG s˜#Ÿ(�(ÑGùs   ‚c                óê   •— ‰j                  | «       | j                  «       D ]N  }‰|   D ]D  } ‰|    j                  |«       t        ‰|    «      dk(  sŒ)t	        j
                  ‰ ‰| «      «       ŒF ŒP y)zU
        Schedules `snode` and put all unblocked nodes onto the ready queue.
        r   N)rÊ   r�   Úremover«   ÚheapqÚheappush)r8   Úbuf_namer–  Úbuffer_usersÚreadyÚ	scheduledrÖ   s     €€€€€r@   Úschedulez$_schedule_for_comm.<locals>.schedule#  sv   ø€ ð 	×Ñ˜ÔØ×.Ñ.Ó0ò 	;ˆHØ% hÑ/ò ;�Ø˜5Ñ!×(Ñ(¨Ô2Ü�z %Ñ(Ó)¨QÓ.Ü—N‘N 5©(°5«/Õ:ñ;ñ	;rJ   c                 óº   •— ‰D � cg c].  } t        | j                  «      st        | j                  «      s| ‘Œ0 }} t        |«      dk(  ryt	        |d„ ¬«      S c c} w )zh
        Return the next node in the ready queue that's neither a collective or
        a wait.
        r   Nc                ó   — | j                   S re   r“  ©r‚   s    r@   r7  zG_schedule_for_comm.<locals>.get_overlapping_candidate.<locals>.<lambda>:  s
   € ¨Q¯W©W€ rJ   ©Úkey)r   r8   r   r«   Úmin)r‚   Ú
candidatesrŸ  s     €r@   Úget_overlapping_candidatez5_schedule_for_comm.<locals>.get_overlapping_candidate.  s]   ø€ ð ö
àÜ& q§w¡wÔ/¼ÀaÇgÁgÔ8Nò ð
ˆ
ð 
ô
 ˆz‹?˜aÒØÜ�:Ñ#4Ô5Ð5ùò
s   †3Ac                ó  •— t        | «      sJ ‚ ‰| «       ‰|    }|dkD  rM ‰«       x}�D‰j                  |«        ‰|j                  «       |‰|j                     z  }|dkD  r
 ‰«       x}�ŒDt        j                  ‰«       y)zÈ
        Schedules collective node `snode`, along with one or more compute nodes
        to overlap with it. The strategy is described in the comment of
        `reorder_compute_for_overlap`.
        r   N)r   rš  r8   r›  Úheapify)r8   Úcollective_costrñ   r©  rŸ  r¡  Úsnode_to_costs      €€€€r@   Úschedule_collective_for_overlapz;_schedule_for_comm.<locals>.schedule_collective_for_overlap<  s‹   ø€ ô # 5Ô)Ð)Ð)Ù�Œà'¨Ñ.ˆà˜aÒÙ7Ó9Ð9�ÐFà�L‰L˜Ô#á�Y—_‘_Ô%à˜}¨Y¯_©_Ñ=Ñ=ˆOð ˜aÒÙ7Ó9Ð9�ÑFô 	�‰�eÕrJ   z;Detected unscheduled nodes. Nodes with unmet dependencies: )r2   r�   rŠ  rŒ   ÚsysÚmaxsizer   Ú	ancestorsr§  r   r
   ra  r   r_  r=  r«   r›  rœ  r´   Úheappopr8   r-   )r5   rD   rE   rF   Úbuf_name_to_snoder?   r8   r�  Úop_nameÚ	node_nameÚcomm_idxÚancestorÚanc_fused_nameÚdepsr˜  r®  r–  rž  r©  r�  rŸ  r¡  r   rŽ  r�  r�  r­  rÖ   s                   @@@@@@@@@@@@r@   rH   rH   Ã  s¼  ÿû€ ðL ÐØÐØ#% r¨2Ð €Hˆh˜Ü Ó'ò "‰
ˆˆUØ×.Ñ.Ó0ò 	0ˆHØ*/Ð˜hÒ'ð	0ð ×0Ñ0Ó2ò 	0ˆGØ*/Ð˜wÒ'ð	0à/4Ð˜5Ÿ>™>Ó+Ñ,à—N‘NÓ$ˆ	Ü!Ÿk™kˆ�ÑØˆ�ÑØ!ˆ�Òð"ð €HØò +ˆÙÔ.¨uÔ5Ø)1ˆH�U—^‘^Ó%Ñ&Ø!ŸO™Oò S�Ø!3°HÑ!=×!FÑ!FÓ!H�Ü+.¨x¸Ñ/GÈÓ+R�˜Ò(ðSð ˜‰M‰HÚœM¨%Õ0Ø)*ˆH�U—^‘^Ó%Ò&ð+÷,ö ,ð  ö<àð 	ŒzÑG¨e×.FÑ.FÔGÓGÑGò<€Jð
 €EÜ=HÌÓ=T€LØDJÖK¸5�UÔ/°Ó6Ñ6ÒK€Mà!×'Ñ'Ó)ò )‰ˆˆtÜˆt‹9˜Š>Ü�N‰N˜5¡(¨5£/Ô2Øò 	)ˆCØ˜Ñ×!Ñ! %Õ(ñ	)ð)ð €I÷	;ð 	;ô6÷ñ* Ü—‘˜eÓ$×*Ñ*ˆÙÔ#6°uÔ#=Ù+¨EÕ2á�UŒOò ð ×!Ñ!Ó#ò 
ˆÜ�4‹y˜A‹~ð 	
ØIÈ*ÈÐVó	
ˆ~ð
ð ÐùòU<ùò Ls   Ä9$I1Å5I6c           	     óz  — t         j                  j                  «       s| S | D �cg c]  }t        |«      sŒ|‘Œ }}t	        dt        |«      «      D ]b  }t        t        ||   j                  «       «      «      }||dz
     j                  «       D ]"  }||   j                  t        ||d¬«      «       Œ$ Œd | S c c}w )zÌ
    Decide global ordering of comms, by just enforcing the ordering that's in the input graph
    (might not be the same ordering as the eager mode program).
    TODO: Come up with a better approach
    r   T©Úmutating_bufr“   )r.   r'   Úis_availabler   r*   r«   rˆ  r‰  r�   Úadd_fake_depr   )ÚnodesÚname_to_bufr�  r�   Ú
comm_nodesr®   r¼  r¶   s           r@   Údecide_global_ordering_of_commsrÂ  _  s·   € ô ×Ñ×)Ñ)Ô+Øˆà"Ö=˜Ô&9¸!Õ&<’!Ð=€JÐ=ä�1”c˜*“oÓ&ò ˆäœD ¨A¡×!?Ñ!?Ó!AÓBÓCˆØ˜a !™eÑ$×5Ñ5Ó7ò 	ˆCØ�q‰M×&Ñ&Ü˜¨,ÀÔEõñ	ðð €Lùò >s
   ¥B8¶B8c                  óª   — e Zd ZU dZded<   dZded<   dZded<   dZded<   d	Zded
<   dZ	ded<   dZ
ded<   dZded<   dZded<   d	Zded<   ed„ «       Zy)ÚSinkWaitInfor   rX   rZ   r[   rV   r\   rY   Ú
moves_inforU   rW   r]   r^   r_   r`   ra   rb   rc   c                ó4   — | j                   | j                  z
  S re   rf   rg   s    r@   ri   zSinkWaitInfo.improvement„  rj   rJ   N)rk   rl   rm   rZ   ro   r\   rY   rÅ  rW   r_   r`   ra   rb   rc   rp   ri   rq   rJ   r@   rÄ  rÄ  w  sw   … à€GˆSÓØ€L�#ÓØ€Eˆ3ƒNØ€J�ÓØ!€O�SÓ!Ø€IˆuÓØ€IˆuÓØ!€O�UÓ!Ø€M�5ÓØ€L�#Óàñ9ó ñ9rJ   rÄ  c                ó$  — t        | «      rdd| j                  «       › �fS t        | «      rdd| j                  «       › �fS t        j                  s@t        | «      rdd| j                  «       › �fS t        | «      rdd| j                  «       › �fS y)aP  
    Check if a candidate node can be grouped during sink_waits pass.

    Sink Waits traverses waits right to left, so we don't group with
    processed waits on the right or with async collectives.

    Args:
        candidate: Node to check for groupability

    Returns:
        Tuple of (is_groupable, reason_if_not_groupable)
    Fzcandidate contains wait ú$candidate contains_async_collective zcandidate contains collective zcandidate contains gemm_like r  )r   rŒ   rÈ   r   Ú&sink_iterative_use_runtime_estimationsr   r€   r!  s    r@   Ú!_is_node_groupable_for_sink_waitsrÊ  ‰  s¸   € ô" �YÔØÐ0°×1CÑ1CÓ1EÐ0FÐGÐGÐGÜ  Ô+àØ2°9×3EÑ3EÓ3GÐ2HÐIð
ð 	
ô
 ×>Ò>ô
 ˜yÔ)àØ0°×1CÑ1CÓ1EÐ0FÐGðð ô ˜iÔ(àØ/°	×0BÑ0BÓ0DÐ/EÐFðð ð rJ   c	                ód  — |d   }	||	   d   ||	   j                   z
  }
|sC|
|j                   z   }|||j                  z
  f|| <   |D ]  }||   }|d   |z   |d   |z   f||<   Œ y| g|¢D ]F  }||   }||   xj                  |j                  |d«      z  c_        ||||   j                  z
  f||<   ŒH y)a  
    Update memory tracking structures after swap (sink_waits version).

    Updates curr_memory and snodes_allocfree dictionaries to reflect the new
    memory state after swapping candidate with group.

    Args:
        candidate: Node that was moved
        gns: Group nodes
        candidate_delta_mem: Net memory change from candidate (alloc - free)
        candidate_allocfree: Candidate's allocation/free info
        group_n_to_bufs_after_swap_dealloc_instead_of_candidate: Buffers whose deallocation moves from candidate to group
        post_alloc_update: Cached post-allocation memory values
        size_free_delta_update: Cached size-free delta values
        curr_memory: Current memory state dict (mutated)
        snodes_allocfree: Node allocation/free info dict (mutated)
    r   r   N)rù   rû   rú   )rñ   r™   rý   rþ   Ú7group_n_to_bufs_after_swap_dealloc_instead_of_candidater  Úsize_free_delta_updater   r¥   rò   Úpre_group_memÚcandidate_post_allocrš   r  r�   Ú
post_allocs                   r@   Ú-_update_memory_tracking_after_swap_sink_waitsrÑ  ´  s  € ð8 �Q‘€JØ 
Ñ+¨AÑ.Ð1AÀ*Ñ1M×1XÑ1XÑX€MÙBØ,Ð/B×/MÑ/MÑMÐà Ø Ð#6×#@Ñ#@Ñ@ð"
ˆ�IÑð ò 	ˆBØ˜R‘ˆBà�1‘Ð+Ñ+Ø�1‘Ð+Ñ+ðˆK˜ŠOð	ð 	àÐ˜#Ðò 
ˆØ& qÑ)ˆ
Ø˜Ñ×%Ò%Ð)?×)CÑ)CÀAÀqÓ)IÑIÕ%àØÐ)¨!Ñ,×6Ñ6Ñ6ð
ˆ�AŠñ
rJ   c	                óú  — ||   d   ||   j                   z
  }	i }
i }d}|s!t        ||z   |	|j                   z   «      }||
|fS |	|j                   z   }||
| <   |}t        d„ t        j                  j                  |j                  «       «      D «       «      }| || <   ||z   }|D ]S  }||   d   |z   }||
|<   t        ||«      }d}||v r*||   }|D ]  }||j                  j                  z  }Œ |||<   ||z  }ŒU ||
|fS )a�  
    Calculate potential peak memory after swapping candidate with group (sink_waits version).

    Computes new memory levels for all affected nodes and returns the potential
    peak memory along with cached post-allocation and size-free delta values.

    Args:
        candidate: Node being moved
        gns: Group nodes
        group_head: First node of group
        group_peak_memory: Current peak memory within the group
        candidate_delta_mem: Net memory change from candidate (alloc - free)
        candidate_allocfree: Candidate's allocation/free info
        group_n_to_bufs_after_swap_dealloc_instead_of_candidate: Buffers whose deallocation moves from candidate to group
        curr_memory: Current memory state dict
        snodes_allocfree: Allocation/free info for all nodes

    Returns:
        Tuple of (potential_peak_memory, post_alloc_update_dict, size_free_delta_update_dict)
    r   c              3  óH   K  — | ]  }|j                   j                  –— Œ y ­wre   r
  r  s     r@   rƒ   z>_calculate_potential_peak_memory_sink_waits.<locals>.<genexpr>  s"   è ø€ ò &àð 	�‰× Õ ñ&ùr  )	rù   rø   r  Ú	itertoolsÚchainÚfrom_iterabler-   r²   rû   )rñ   r™   rò   rü   rý   rþ   rÌ  r   r¥   rÎ  r  Ú_size_free_delta_updater  rÏ  Úcandidate_size_free_to_moveÚ	delta_memrš   Úgn_post_allocÚgn_size_free_to_addr  r¶   s                        r@   Ú+_calculate_potential_peak_memory_sink_waitsrÜ  é  s{  € ð>   
Ñ+¨AÑ.Ð1AÀ*Ñ1M×1XÑ1XÑX€Mà79ÐØ<>Ðà€NÙBäØÐ 3Ñ3ØÐ/×:Ñ:Ñ:ó
ˆð Ð1Ð3JÐJÐJà(Ð+>×+IÑ+IÑIÐØ$8Ð�yÑ!Ø)€NÜ"%ñ &ä—?‘?×0Ñ0ØC×JÑJÓLó
ô&ó #Ðð +FÐ)EÐ˜IÑ&Ø#Ð&AÑA€IØò 
)ˆØ# B™¨Ñ*¨YÑ6ˆØ!.Ð˜2ÑÜ˜^¨]Ó;ˆØÐØÐHÑHØJÈ2ÑNˆDØò @�Ø# s§~¡~×'?Ñ'?Ñ?Ñ#ð@à*=Ð# BÑ'ØÐ(Ñ(‰	ð
)ð Ð-Ð/FÐFÐFrJ   c                ól   — ||   }|r| ||<   ||| <   ||    }|r|||<   |||<   | ||<   ||| <   ||k(  r| S |S )aÁ  
    Swap positions of candidate and group in doubly-linked list (sink_waits version).

    Transforms (moves candidate to the left):
    group_head_prev -> group_head...group_tail -> candidate -> candidate_next
    Into:
    group_head_prev -> candidate -> group_head...group_tail -> candidate_next

    Args:
        candidate: Node to swap with group
        group_head: First node of group
        group_tail: Last node of group
        prev_dict: Dictionary mapping nodes to their previous nodes
        next_dict: Dictionary mapping nodes to their next nodes
        head: Current head of the linked list

    Returns:
        New head of the linked list (may change if group_head was the head)
    rq   )rñ   rò   ró   rì   rÍ   rË   Úgroup_head_prevÚcandidate_nexts           r@   Ú+_perform_double_linked_list_swap_sink_waitsrà  /  ss   € ð8   
Ñ+€OÙØ%.ˆ	�/Ñ"Ø*€IˆiÑð ˜yÑ)€NÙØ$.ˆ	�.Ñ!Ø*€IˆjÑð &€IˆjÑØ%€IˆiÑð �TÒØÐØ€KrJ   c                ó*  ‡— g d¢}| j                  «       D ��	cg c]™  \  }}	t        |«      |	j                  dz  |	j                  dz  |	j                  dz  |	j
                  dz  |	j                  dz  |	j                  |	j                  |	j                  |	j                  |	j                  |	j                  g‘Œ› }
}}	dŠt        j                  j                  d«      rddlm} ‰ ||
|¬«      z  Šn8‰dz  Š‰t#        |«      d	z   z  Š‰d	j%                  t'        t"        |
«      «      z  Št(        j+                  ‰«       t-        |d
|«      }t/        |«      |k(  sJ ‚t1        |||«      \  }}}}‰d|› �z  Š‰d|› �z  Št3        dd„ ˆfd„¬«       |S c c}	}w )aÉ  
    Format sink_waits statistics, log them, and return final node list.

    Computes improvement metrics, creates a formatted table (using tabulate if
    available), validates the reordered node count, recalculates peak memory,
    and logs all information.

    Args:
        stats: Per-node sink_waits statistics
        head: Head of the reordered linked list
        next_dict: Linked list next pointers
        original_snodes_num: Original number of nodes (for validation)
        peak_memory: Initial peak memory before reordering
        name_to_freeable_input_buf: Buffer memory tracking info
        graph_outputs: Graph output names

    Returns:
        Final reordered list of scheduler nodes
    )z	Wait noder$  r%  r&  r'  r(  r)  rZ   r\   rY   rÅ  rc   r*  r[   r+  r   r,  r-  r/  r0  Nz*
 sink_waits_iterative peak_memory_before:z)
 sink_waits_iterative peak_memory_after:r1  c                 ó   — dddœS )NÚsink_waits_iterative_infor3  r4  rq   rq   rJ   r@   r7  z2_format_and_log_sink_waits_stats.<locals>.<lambda>±  s   € Ø/Ø ñ
€ rJ   c                 ó   •— ‰ S re   rq   )Úlog_strs   €r@   r7  z2_format_and_log_sink_waits_stats.<locals>.<lambda>µ  s   ø€ ˜7€ rJ   r:  )r=  r>  r_   r`   ra   rb   ri   rW   rZ   r\   rY   rÅ  rc   r?  r@  rA  r+  rV   r˜   rB  rC  rD  rÎ   r«   r   r   )rE  rË   rÍ   rF  r£   r¢   r¡   r.  r8   rD  rJ  r+  rK  rL  r<   rå  s                  @r@   Ú _format_and_log_sink_waits_statsræ  `  s±  ø€ ò8€Gð: !Ÿ;™;›=÷ñ ˆE�4ô ˜ÓØ�N‰N˜SÑ Ø�N‰N˜SÑ Ø× Ñ  3Ñ&Ø×Ñ Ñ$Ø×Ñ˜sÑ"Ø× Ñ Ø�L‰LØ×ÑØ�J‰JØ�O‰OØ×Ñò	
ð€Dñ ð" €GÜ‡~�~×Ñ 
Ô+Ý%à‘8ØØô
ñ 	
‰ð
 	ÐTÑTˆØ”3�w“< $Ñ&Ñ&ˆØ�4—9‘9œS¤ d›^Ó,Ñ,ˆÜ×Ñ�WÔÜ.¨t°T¸9ÓE€JÜˆz‹?Ð1Ò1Ð1Ð1Ü=ØÐ.°ó Ñ€O�Q˜˜1ð Ð<¸[¸MÐJÑJ€GØÐ;¸OÐ;LÐMÑM€GÜØñ
ó #õð Ðùó[s   ™BFc                óö   — t        t        «      }|j                  | t        «       «      }|D ]J  }||   }|| k7  rŒ|j                  j
                  }d}	|D ]	  }
|
|v sŒ|
}	Œ |	€Œ7||	   j                  |«       ŒL |S )a­  
    Find buffers whose last use will change after swapping in sink_waits pass.

    When we swap [group] candidate to candidate [group], some buffers that
    were last used by candidate will now be last used by a group node instead.
    This is the opposite direction from the reorder version.

    Args:
        candidate: The node being moved (currently last use)
        gns: Group nodes being swapped with candidate
        buf_to_snode_last_use: Mapping of buffers to their current last-use nodes
        candidate_buffer_map: Pre-computed map of node -> buffers using that node

    Returns:
        Dict mapping group nodes to buffers that will change their last-use node
    N)r   r,   rú   r
   r²   r³   rÊ   )rñ   r™   r¦   r¨   rÌ  r  r¶   r  r³   Úlast_succ_gnrš   s              r@   Ú._find_buffers_with_changed_last_use_sink_waitsré  º  sª   € ô0 	”DÓð <ð *×-Ñ-¨i¼»ÓF€Nàò 
ˆØ.¨sÑ3ˆØ˜YÒ&Øð —^‘^×.Ñ.ˆ
ØˆØò 	"ˆBØ�ZÒØ!‘ð	"ð ÐØð 	@ÀÑM×TÑTØõ	
ð%
ð, CÐBrJ   c                óþ  — t        | «      }|dk(  r| i fS t        t        j                  j                  j                  «       «      }t        t        j                  j                  «       «      }t        | ||«      \  }}}}}}	t        | «      \  }
}}i }| D �ci c]  }|t        |«      t        |«      z  “Œ }}| D �ci c]#  }|t        d„ |j                  «       D «       «      “Œ% }}| D �ci c]  }|t        d„ |j                  D «       «      “Œ! }}| d   }t        «       }t        j                  }t        j                   }d}|��÷|
|   ��ñ|
|   }|r�nè|�t        |«      |k\  r�nÖt#        |«      r||vs|}Œ6|j%                  |«       t'        «       x}||<   t)        |||
|||«      \  }}}||z
  x|_        |_        ||_        ||_        ||_        ||   }|}|}i }d} ||   d   }!t        ||   «      }"t5        |«      }#|��.t        j6                  r4|j,                  t        j8                   |j.                  z  k  r	d|_        �nê|"sd}$n||   }%t=        |%|"z  «      }$t        j>                  s%tA        |«      rd|jC                  «       › �|_        �n�|#xr t5        |«      }&|$s|&rötE        |«      \  }'}(|'r›|}|"jG                  ||   «       |#xs t5        |«      }#t        j6                  r8t5        |«      r-tI        |||||«      \  }}})||f||<   tA        |«      s| ||   z  } tK        |!||   d   «      }!|xjL                  d	z  c_&        ||   }�ŒR|$s,t        jN                  s9|&r7d
|jC                  «       › �|_        �n±d|jC                  «       › d|(› �|_        �n”t        j6                  �rAtQ        |jR                  «      rIt)        |||
|||«      \  }}})tK        d||z
  «      }*tK        d||z
  | z   «      }+|+|*kD  rd|*› d|+› �|_        �n%tA        |«      sØ||   },|,dkD  rÎt        |«      dkD  rÀtK        d|j.                  |j0                  z
  «      }-tK        d|j.                  |j0                  z
  |,z
  «        |jU                  «       D ]*  \  }.}/|-tK        d|.|/z
  «      tK        d|.|/z
  |,z   «      z
  z  }-Œ, |-dkD  rd|,› d|-› �|_        �ng|jW                  «       D ]  \  }0\  }.}/|.|/|,z
  f||0<   Œ tY        |||«      }1||   }2|2jZ                  |2j\                  z
  }3t_        ||1||	«      }4ta        ||1||!|3|2|4||«	      \  }5}6}7|5|z
  |t        jb                  z  kD  rd|5› d|› �|_        nË|xjd                  d	z  c_2        |xjf                  d|jC                  «       › �z  c_3        ti        ||||
||«      }t)        |||
|||«      \  }}}||_        ||_        ||z
  |_        ||_        tk        ||1|3|2|4|6|7||«	       |r/d	dl6m7}8  |8||1tq        |1«      tY        |d |«      |||||d|4«      }|rn	||   }|��Œ.|}|�|
|   ��Œñt        jr                  stY        |d |«      }9|9|fS tu        |||||||«      }9|9|fS c c}w c c}w c c}w )Nr   c              3  ó<   K  — | ]  }|j                  «       –— Œ y ­wre   rº   r»   s     r@   rƒ   z1_sink_waits_iterative_internal.<locals>.<genexpr>  rP  r½   c              3  óL   K  — | ]  }t        |«      rŒ|j                  –— Œ y ­wre   rR  rS  s     r@   rƒ   z1_sink_waits_iterative_internal.<locals>.<genexpr>  rT  rU  éÿÿÿÿFrÙ   rV  rÈ  r   z$collective ordering
 with candidate:rW  z
 non_group_reason:z"candidate is wait, exposed_before:z vs exposed_after:rX  z2, group contains collectives, total_exposed_delta rY  rZ  rà   r[  Úsink_waits_iterative);r«   r
   r   r]  r    r3   r^  r©   r°   r_  rÄ   r`  r¾   ra  r   rc  Ú(sink_waits_iterative_debug_limit_to_sinkr   r´   rÄ  rï   ra   rb   r_   r`   rc   r   rÉ  Ú&sink_iterative_extra_comm_comp_overlaprW   rÐ   Ú*sink_waits_iterative_swap_with_collectivesrÈ   rŒ   rÊ  rf  ré   rø   rZ   Ú/sink_waits_iterative_unsafe_collectives_reorderr   rz   r-   r=  rÎ   rù   rû   ré  rÜ  Ú!sink_iterative_peak_memory_budgetrY   rÅ  rà  rÑ  rh  r\  r›   ri  ræ  ):r5   rF  r    r¡   r£   r§   r¥   r¦   r¢   r¨   r¬   r­   r¯   rE  r8   rÝ   rÓ   rÔ   rm  Úprocessed_waitsrn  Údebug_num_sink_waits_to_reorderro  Ú
_prev_currrD  r_   r`   rc   rñ   rò   ró   Úgroup_collsrr  rü   rt  Úgroup_contains_collectiverv  Úcandidate_dep_namesÚboth_contain_commsÚ_is_groupableÚgroupable_reasonr<   r|  r}  r{  r~  Úgc_comm_timeÚgc_comp_timeÚgcr™   rþ   rý   rÌ  r  r  r×  r\  rK  s:                                                             r@   Ú_sink_waits_iterative_internalr   ñ  s‚  € ô ˜f›+ÐØ˜aÒØ�rˆzÐÜ$.¬q¯w©w×/CÑ/C×/HÑ/HÓ/JÓ$K€LÜ%/´·±×0HÑ0HÓ0JÓ%K€Mô 	$ F¨L¸-ÓHñØØØØØ"Øô 9¸Ó@Ñ€Eˆ5�%à35€Eð ö0àð 	Ô" 5Ó)Ô,EÀeÓ,LÑLÑLð0€Hð 0ð RXöAØHMˆŒyÑC¨u×/@Ñ/@Ó/BÔCÓCÑCðAÐð Að ö	>ð ð 	Œyñ 
Ø!×4Ñ4ô
ó 
ñ 	
ð>€Mð >ð &,¨B¡Z€Dä “l€Oä×=Ñ=ð %ô 	×=Ñ=ð $ð !&ÐØ
Ñ
˜u T™{Ñ6Ø˜4‘[ˆ
Ù$Ùà+Ð7Ü�OÓ$Ð(GÒGáä˜dÔ#¨°OÑ(CØˆDØà×Ñ˜DÔ!Ü)›^Ð+ˆˆu�T‰{Ü-MØ�%˜ Ð*:¸Mó.
Ñ*ˆ	�9˜lð 5>À	Ñ4IÐIˆÔ˜tÔ1Ø"ˆŒØ"ˆŒØ(ˆÔà˜$‘Kˆ	Øˆ
Øˆ
ØˆØˆØ(¨Ñ.¨qÑ1Ðô (Ð(8¸Ñ(>Ó?ÐÜ$7¸Ó$=Ð!àÑ#Ü×BÒBØ×"Ñ"Ü×FÑFÐFÈÏÉÑWòXð (J�Ô$Ùñ &Ø ‘ð '4°IÑ&>Ð#ÜÐ 3Ð6HÑ HÓI�ô  ×JÒJÜ,¨YÔ7à>¸y×?QÑ?QÓ?SÐ>TÐUð Ô(ñ ð ";ò "Ô?RØó@Ðñ Ñ-Ü2SØó3Ñ/�Ð/ñ !Ø!*�Jð '×-Ñ-Ð.>¸yÑ.IÔJà1ÒSÔ5HÈÓ5Sð .ô
 %×KÒKÜ/°	Ô:ä2RØ% u¨hÐ8HÈ-ó3Ñ/˜	 9¨að 3<¸YÐ1G˜ IÑ.Ü8¸ÔCØ)¨X°iÑ-@Ñ@˜Mä(+Ø)¨<¸	Ñ+BÀ1Ñ+Eó)Ð%ð —L’L AÑ%•LØ % iÑ 0�IÙÙ!ä(×XÒXÙ.ð1Ø1:×1CÑ1CÓ1EÐ0FðHð Ô,ñ ð(Ø(1×(:Ñ(:Ó(<Ð'=Ø.Ð/?Ð.@ðBð Ô(ñ
 ä×BÓBÜ˜9Ÿ>™>Ô*ô /OØ!ØØØ Ø(Ø%ó/Ñ+�I˜y¨!ô &)¨¨I¸	Ñ,AÓ%B�Nä$'¨¨9°yÑ+@À=Ñ+PÓ$Q�Mð % ~Ò5ð/Ø/=Ð.>Ð>PÐQ^ÐP_ðað Ô,ñ ô 1°Ô;ð !)¨Ñ 3�Ià  1’}¬¨[Ó)9¸AÒ)=ô ),ØØ ŸN™N¨T¯^©^Ñ;ó)˜ô
 ˜Q §¡°·±Ñ ?À)Ñ KÓLÑLØ:E×:LÑ:LÓ:Nò Ñ6˜L¨,à)¬S°°LÀ<Ñ4OÓ-PÔSVØ ! <°,Ñ#>ÀÑ#JóTñ .ñ ™Mðð
 )¨1Ò,à"8¸¸ð D8Ø8E°ð!Hð !Ô0ñ "ð "-×!2Ñ!2Ó!4ò"ñ ! ñ %Ø ,Ø ,ð %1Ø$0°9Ñ$<ð3" ¨B¢ð	"ô ,IØ˜J¨ó,ˆCð 0@À	Ñ/JÐà#×.Ñ.Ð1D×1NÑ1NÑNð  ô ?Ø˜sÐ$9Ð;Oóð Dô <ØØØØ%Ø'Ø'ØKØ Ø$ó
ñ HˆNÐ.Ð0Gð  Ñ,Ø¤× NÑ NÑNòOð ' ~Ð&6°iÀ¸}ÐMð Ô$ð à�JŠJ˜!‰O�JØ�OŠO  9×#5Ñ#5Ó#7Ð"8Ð9Ñ9�Oä?Ø˜: z°5¸%ÀóˆEô 2RØ�e˜U HÐ.>Àó2Ñ.ˆI�y ,ð 'ˆDŒNØ&ˆDŒNØ!*¨YÑ!6ˆDÔØ ,ˆDÔä9ØØØ#Ø#ØGØ"Ø'ØØ ô
ñ 0ÝJá,MØØÜ  Ó%Ü1°%¸¸uÓEØ.Ø!ØØ Ø$Ø*ØKó-Ð)ñ -Øà˜jÑ)ˆIðQ Ò#ðR ˆðY Ð
˜u T™{Ò6ô\ ×4Ò4Ü2°5¸$ÀÓFˆ
Ø˜5Ð Ð ä1ØØØØØØ"Øó€Jð �uÐÐùòo	0ùòAùò>s   ÂY0Â;(Y5Ã)$Y:c                ó   — t        | «      d   S )a£  
    Similarly to reorder_communication_preserving_peak_memory this pass will try to iteratively
    push Wait nodes later, recomputing estimated peak memory before each swap,
    and preventing peak memory regressions.

    Pass will be applied to every Wait node. If there are immediate dependencies with next node,
    pass will try to group them together and on the next step to swap the group with next candidate.

    If _inductor.config_comms.sink_iterative_use_runtime_estimations is set True,
    pass will stop reordering of Wait once corresponding Collective is unexposed,
    based on runtime estimations.

    inductor.config_comms.sink_iterative_peak_memory_budget allows to tune how much pass
    can regress initial peak memory.
    E.g.:
    sink_iterative_peak_memory_budget == 0.0 - No regression of initial peak memory is allowed
    sink_iterative_peak_memory_budget == 0.2 - Pass can improve comm-compute overlap, sacrificing
    20% of initial peak memory value.

    inductor.config_comms.sink_iterative_extra_comm_comp_overlap config allows to more aggressively
    sink waits, stopping only when overlap_compute >= (1 + extra_comm_comp_overlap) * comm_time
    r   )r   rI   s    r@   rî  rî  @  s   € ô. *¨&Ó1°!Ñ4Ð4rJ   c                ó°   — t         j                  dk(  r| j                  «       }|S t        t         j                  «      sJ ‚t        j                  | «      }|S )z;
    Returns estimated op runtime in milliseconds (ms)
    rx   )r   r_  r%   Úcallable)r8   Úruntimes     r@   r_  r_  Z  sR   € ô ×!Ñ! YÒ.Ø×-Ñ-Ó/ˆð €Nô œ×2Ñ2Ô3Ð3Ð3Ü×,Ñ,¨UÓ3ˆØ€NrJ   c           
     ób  — | j                  «       }t        |«      dk(  �rŸd}t        | j                  t        j
                  t        j                  f«      r‡d| j                  «       D �cg c]  }|j                  «       ‘Œ c}› �}d| j                  D �cg c]  }|j                  ‘Œ c}› �}d| j                  «       › d| j                  j                  › d|› d|› d	�	}| j                  «       D �cg c]  }|j                  j                  «       ‘Œ }}d
j                  |D �	cg c];  }	t        |	t        j                  «      rd|	j                  › d|	j                   › d	�nd‘Œ= c}	«      }
	 | j                  j#                  «       }| j                  j&                  j(                  › |› |
› d|› d| j+                  «       d›d�S g }|D ]  }|j-                  t/        |«      «       Œ | j&                  j(                  › ddj                  |«      › �S c c}w c c}w c c}w c c}	w # t$        $ r d}Y Œªw xY w)Nr   r[   zouts:zins:ú z (z)
 ú(ú)ú,z (size=z	, stride=z.0fz ns)ú: z, )Ú	get_nodesr«   r„   rz   r   ÚExternKernelOutÚ_CollectiveKernelr¾   rŒ   ra  r5  rs   Úget_output_specr˜   ÚLayoutÚsizeÚstrideÚmaybe_get_nameÚAttributeErrorÚ	__class__rk   r%   rÊ   r>  )r8   r5   Údetailr¼   Úouts_strr”   Úins_strÚchildÚlayoutsÚlayoutÚout_tensor_inforµ  Ú	summariesÚchild_snodes                 r@   r>  r>  f  s  € Ø�_‰_Ó€FÜ
ˆ6ƒ{�aÓØˆÜ�e—j‘j¤2×#5Ñ#5´r×7KÑ7KÐ"LÔMØ°e×6GÑ6GÓ6IÖJ° §
¡
¥ÒJÐKÐLˆHØ¨e×.FÑ.FÖG¨˜aŸf›fÒGÐHÐIˆGØ˜Ÿ™Ó)Ð*¨"¨U¯Z©Z×-JÑ-JÐ,KÈ4ÐPXÈzÐYZÐ[bÐZcÐcdÐeˆFØ=B¿_¹_Ó=NÖO°E�5—:‘:×-Ñ-Õ/ÐOˆÐOØŸ(™(ð
 &ö	ð ô ˜f¤b§i¡iÔ0ð ˜&Ÿ+™+˜ i°·±¨¸aÑ@àñòó
ˆð	ØŸ
™
×1Ñ1Ó3ˆIð —*‘*×&Ñ&×/Ñ/Ð0°°¸Ð8IÈÈIÈ;ÐVXÐY^×YtÑYtÓYvÐwzÐX{Ð{ð  Að  	Að €IØò 4ˆØ×Ñœ kÓ2Õ3ð4à�o‰o×&Ñ&Ð' r¨$¯)©)°IÓ*>Ð)?Ð@Ð@ùò/  KùÚGùâOùòøô ò 	àŠIð	ús+   Á)HÂHÃ/!HÄ!A HÅ)H  È H.È-H.c                ó&  — d}d }d„ }t        | «      D ]Þ  \  }}|€^t        |«      r|t        |«      z  }|j                  }n$t	        |j                  «      rn|t        |«      z  } ||t        |«      › «       Œft        |«      r.|t        |«      z  }|j                  } ||t        |«      › «       ŒŸt	        |j                  «      r ||t        |«      › «       d }ŒÊ ||dt        |«      › �«       Œà t        j                  d|dz  dz  › �«       y )NrÙ   c                ó:   — t         j                  | d›d|› �«       y )Nz>6r
  )rC  Údebug)Ústeprz  s     r@   Ústep_logz#visualize_overlap.<locals>.step_logŒ  s   € Ü×Ñ˜T "˜I R¨ uÐ-Õ.rJ   z| zEst. runtime (ms): iè  )r2   r   r_  rz   r   r>  rC  r   )ÚorderÚtotal_est_runtimeÚcur_comm_noder"  r!  r8   s         r@   Úvisualize_overlapr&  …  s  € ð  #ÐØ€Mò/ô ! Ó'ò ;‰ˆˆeØÐ Ü" 5Ô)Ø!Ô%8¸Ó%?Ñ?Ð!Ø %§
¡
‘Ü˜Ÿ™Ô$ð à!Ô%8¸Ó%?Ñ?Ð!Ù�Tœl¨5Ó1Ð2Õ4ä" 5Ô)Ø!Ô%8¸Ó%?Ñ?Ð!Ø %§
¡
�Ù˜¤,¨uÓ"5Ð!6Õ8Ü˜Ÿ™Ô$Ù˜¤,¨uÓ"5Ð!6Ô8Ø $‘á˜ ¤L°Ó$7Ð#8Ð9Õ:ð-;ô. ×ÑØ
Ð/°$Ñ6¸Ñ=Ð>Ð?õrJ   c                óÂ   — | }t         j                  D ]I  }t        |t        «      r|t	        «       v rt	        «       |   }t        |«      sJ d|› d�«       ‚ ||«      }ŒK |S )Nz3Invalid reorder_compute_and_comm_for_overlap pass: z is not callable)r   Ú'reorder_for_compute_comm_overlap_passesr„   rV   Úglobalsr  )r5   r#  Úps      r@   Ú$reorder_compute_and_comm_for_overlapr+  «  sm   € ð €Eä×;Ñ;ò ˆÜ�aœÔ !¤w£y¡.Ü“	˜!‘ˆAÜ˜Œ{ð 	
ØAÀ!ÀÐDTÐUó	
ˆ{ñ �%“‰ðð €LrJ   c           
     óž  ‡‡‡‡‡‡— t        | j                  «      Št        t         «      Št        t         «      Št        ‰«      D ]Ó  \  }}|j                  dk(  sŒ|j
                  t        j                  j                  j                  j                  u sŒQ|j                  d   j                  dk(  sJ d|› d|j                  d   › d�«       ‚|j                  d   }|j                  d   }|dkD  r‰|   j                  |«       ŒÀ‰|   j                  |«       ŒÕ ˆˆˆfd„}t        t         «      }t        ‰«      D ]›  \  }}|j                  dk(  sŒ|j
                  t        j                  j                  j                  j                  u sŒQ|}|j                  d   Š‰j                  dk(  sJ d	‰› d
| › d�«       ‚ |‰«      sŒˆ|‰   j                  |«       Œ� d„ }d„ Š‰D ]�  }|j                  dk(  sŒt        |j
                  t        j                   j"                  «      sŒB|j
                  j$                  j&                  sŒc ||«      rŒl ‰||j)                  «       «      sŒ„J d|› d�«       ‚ |j+                  «       D �]!  \  Š}	t        |	«      D �]  \  }
}‰|   }|j                  d   ‰u sJ ‚|j                  \  }Š|dz   }|
t-        |	«      dz
  k  r|	|
dz      nt-        ‰«      dz
  }‰|| }t/        ˆˆfd„|D «       «      rJ d‰› d|› d| › d�«       ‚|D ]ƒ  }|j                  dk(  sŒ‰|j                  v sŒ"|j
                  t        j                  j                  j                  j                  k7  sŒ^t1        ˆˆfd„|j                  D «       «      }||_        Œ… �Œ �Œ$ |j3                  «       D ]  }	|	D ]  }‰|   }| j5                  |«       Œ Œ! ‰D ]p  }|j                  dk(  sŒ|j
                  t        j                  j                  j                  j                  u sŒN|j                  d   |v sŒ`| j5                  |«       Œr y)aŠ  
    This FX graph pass replaces uses of FSDP2 unsharded params with their corresponding
    graph intermediates that were fsdp.copy_ into the unsharded params in the original graph.

    NOTE: Can only apply this pass to any of the FSDP2 unsharded params that have this pattern
    (or repetition of): `resize_(full) -> copy_ -> resize_(0)`. Because of this, for partial-graph case
    where `resize_(full) -> copy_` is in one graph and `resize_(0)` is in another graph, we can't
    remove these resize and copy ops and thus we will have worse performance there.

    In other words, "do we try to remove all the resize_(full) -> copy_ -> resize_(0) nodes for this unsharded param"
    is actually a per-unsharded-param decision, since for each unsharded param, we look at its resize sequence pattern
    (in `check_resize_pattern()`) to determine if its set of resize and copy nodes can be removed.
    Úcall_functionr   Úplaceholderz1Resize can only operate on graph inputs, but got z# which is resizing non-graph-input r0  r   c                ól  •— ‰j                  | g «      }‰j                  | g «      }t        |«      t        |«      k7  r2t        j                  d| › dt        |«      › dt        |«      › d�«       yt	        ||«      D ]7  \  }}||k\  sŒt        j                  d| › d‰|   › d|› d	‰|   › d|› d
�«        y y)NzH
Unequal number of resize-to-full and resize-to-0 nodes for graph input z:
z vs. zK.
Skipping `remove_fsdp2_unsharded_param_graph_input_usage` FX graph pass.
Fz
For graph input z: resize-to-full node z
 at index z 
happens after resize-to-0 node zd.
Skipping `remove_fsdp2_unsharded_param_graph_input_usage` FX graph pass for that unsharded param.
T)rú   r«   ÚlogÚwarningrž   )Úgraph_inputÚresized_to_full_idxesÚresized_to_0_idxesÚresize_to_full_idxÚresize_to_0_idxÚ&graph_input_to_resized_to_0_node_idxesÚ)graph_input_to_resized_to_full_node_idxesÚ	node_lists        €€€r@   Úcheck_resize_patternzLremove_fsdp2_unsharded_param_graph_input_usage.<locals>.check_resize_patternÝ  s  ø€ ð !J× MÑ MØ˜ó!
Ðð D×GÑGÈÐUWÓXÐäÐ$Ó%¬Ð-?Ó)@Ò@Ü�K‰KðHØHSÀ}ð UÜÐÓÐ ˜E¤#Ð&8Ó"9Ð!:ð ;ðôð ô 47Ø!Ð#5ó4
ò 	Ñ/Ð ð " _Ó4Ü—‘ðØ�Ð3°IÐ>PÑ4QÐ3RÐR\Ð]oÐ\pð q Ø )¨/Ñ :Ð;¸:ÀoÐEVð Wðôñ ð	ð rJ   z\
Assumed all FSDP2 `unsharded_param`s to be graph input, but it's not true!
Offending node: z	. Graph: c                óî   — | j                   t        j                  j                  j                  j
                  u xs: | j                   t        j                  j                  j                  j
                  u S re   )Útargetr.   ru   ÚfsdpÚcopy_rx   ÚinductorÚresize_storage_bytes_)rz   s    r@   Úis_allowed_mutationzKremove_fsdp2_unsharded_param_graph_input_usage.<locals>.is_allowed_mutation	  sO   € à�K‰Kœ5Ÿ9™9Ÿ>™>×/Ñ/×7Ñ7Ð7ò OØ�{‰{œeŸi™i×0Ñ0×FÑF×NÑNÐNð	
rJ   c           	     ón  — t        | j                  t        j                  j                  «      r^t        | j                  j                  j                  «      D ��cg c])  \  }}|j                  �|j                  j                  r|‘Œ+ c}}ng }t        |D �cg c]5  }t        | j                  |   j                  d   j                  «       «      ‘Œ7 c}«      }t        |D �cg c](  }t        |j                  d   j                  «       «      ‘Œ* c}«      }t        ||z  «      dkD  S c c}}w c c}w c c}w )NÚvalr   )r„   r<  r.   Ú_opsÚ
OpOverloadr2   Ú_schemaÚ	argumentsÚ
alias_infoÚis_writer
   r	   ÚargsÚmetaÚuntyped_storager«   )rz   Úunsharded_paramsr®   r‚   Úmutated_arg_idxesÚmutated_node_arg_storagesÚunsharded_paramÚstorages_of_unsharded_paramss           r@   Ú-is_node_mutating_unsharded_param_or_its_aliaszeremove_fsdp2_unsharded_param_graph_input_usage.<locals>.is_node_mutating_unsharded_param_or_its_alias	  s  € ô ˜$Ÿ+™+¤u§z¡z×'<Ñ'<Ô=ô & d§k¡k×&9Ñ&9×&CÑ&CÓD÷á�A�qØ—<‘<Ð+°·±×0EÒ0Eò ôð ð 	ô %/ð +öàô ˜tŸy™y¨™|×0Ñ0°Ñ7×GÑGÓIÕJòó%
Ð!ô (2ð (8öà#ô ˜×3Ñ3°EÑ:×JÑJÓLÕMòó(
Ð$ô Ð,Ð/KÑKÓLÈqÑPÐPùó)ùòùòs   Á.D'Â:D-Ã"-D2zdUser mutation on FSDP2 unsharded param is not allowed when Traceable FSDP2 is used. Violating node: c              3  ó2   •K  — | ]  } ‰|‰g«      –— Œ y ­wre   rq   )r�   rz   rR  rP  s     €€r@   rƒ   zAremove_fsdp2_unsharded_param_graph_input_usage.<locals>.<genexpr>Y	  s#   øè ø€ ò àñ >¸dÀ_ÐDU×Vñùs   ƒz(Assumed no ops mutating unsharded param z in subgraph z, but it's not true!
Graph: c              3  ó.   •K  — | ]  }|‰u r‰n|–— Œ y ­wre   rq   )r�   ÚargÚreplacementrP  s     €€r@   rƒ   zAremove_fsdp2_unsharded_param_graph_input_usage.<locals>.<genexpr>f	  s%   øè ø€ ò %àð (+¨oÑ'=™À3ÓFñ%ùs   ƒN)r,   r¿  r   r2   Úopr<  r.   ru   r?  r@  rx   rJ  rÊ   r=  r>  r„   rD  rE  rF  Ú
is_mutabler3   r=  r«   r…   Útupler-   Ú
erase_node)r]  r?   rz   r2  Únew_sizer:  Ú'unsharded_param_to_fsdp_copy_node_idxesÚfsdp_copy_noderA  Úfsdp_copy_node_idxesr®   Úfsdp_copy_node_idxr<   Úsubgraph_start_idxÚsubgraph_end_idxÚsubgraph_nodesÚnew_argsr7  r8  rR  r9  rV  rP  s                    @@@@@@r@   Ú.remove_fsdp2_unsharded_param_graph_input_usagerd  »  s{  ý€ ô �U—[‘[Ó!€Iô 1<¼DÓ0AÐ-Ü-8¼Ó->Ð*Ü˜yÓ)ò P‰	ˆˆTà�G‰G�Ó&Ø—‘œuŸy™y×1Ñ1×GÑG×OÑOÒOà—9‘9˜Q‘<—?‘? mÒ3ð ð :2Ø26°Ð7ZÐ[_×[dÑ[dÐefÑ[gÐZhð ið6ó Ð3ð Ÿ)™) A™,ˆKØ—y‘y ‘|ˆHØ˜!Š|Ø9¸+ÑF×MÑMÈcÕRà6°{ÑC×JÑJÈ3ÕOðPö"ôJ /:¼$Ó.?Ð+Ü˜yÓ)ò 	U‰	ˆˆTØ�7‰7�oÓ%¨$¯+©+¼¿¹¿¹×9MÑ9M×9UÑ9UÒ*UØ!ˆNØ"Ÿi™i¨™lˆOØ"×%Ñ%¨Ò6ð ð =à Ð! ¨5¨'ð 2ð9ó Ð6ñ $ OÕ4Ø7¸ÑH×OÑOÐPSÕTð	Uò
òQð4 ò ˆà�G‰G�Ó&Ü˜4Ÿ;™;¬¯
©
×(=Ñ(=Õ>Ø—‘×#Ñ#×.Ó.Ù'¨Õ-áDØÐ=×BÑBÓDõð ðeØeiÐdjð kðóð ðð: 
1×	6Ñ	6Ó	8ó")ñ 	ØØä%.Ð/CÓ%Dó 	)Ñ!ˆAÐ!Ø&Ð'9Ñ:ˆNØ!×&Ñ& qÑ)¨_Ñ<Ð<Ð<Ø+×0Ñ0‰NˆAˆ{à!3°aÑ!7Ðð ”sÐ/Ó0°1Ñ4Ò4ð % Q¨¡UÒ+ä˜“^ aÑ'ð ð
 'Ð'9Ð:JÐKˆNÜô à*ôô ð ð)Ø)8Ð(9¸À~ÐFVð WØ€wð ðóð ð 'ò 
)�à—G‘G˜Ó.Ø'¨4¯9©9Ò4ØŸ™¤u§y¡y×'9Ñ'9×'OÑ'O×'WÑ'WÓWä$ô %à#'§9¡9ô%ó  �Hð !)�D•Iò
)ò)	)ð	")ðJ !H× NÑ NÓ Pò -ÐØ"6ò 	-ÐØ&Ð'9Ñ:ˆNØ×Ñ˜^Õ,ñ	-ð-ð ò #ˆà�G‰G�Ó&Ø—‘œuŸy™y×1Ñ1×GÑG×OÑOÒOØ—	‘	˜!‘Ð GÒGà×Ñ˜TÕ"ñ#rJ   c                óè  ‡	— 	 dd l Š	‰	j                  j                  «       sJ ‚‰	j                  j                  j
                  r ‰	j                  j                  j                  sJ ‚	 ddl
m}m}m}m}m} 	 ˆ	fd„} |«       } | |‰	j                  j                  j
                  j                    |t"        j$                   |‰	j                  j&                  j(                  j                    |d«       |d«       |d«       |d«       |d	«      «       |d
«      «       |d«       |d«      «      |d„ ¬«      dˆ	fd„«       } || «       |j+                  | «       y # t        t        t        f$ r Y y w xY w)Nr   r   )ÚCallFunctionÚ
KeywordArgÚMatchÚPatternMatcherPassÚregister_graph_patternc                óH  •— t        | j                  «      }|D ]‡  }|j                  t        j                  u sŒ |j
                  d   j                  ‰j                  j                  j                  j                  u sŒd|j
                  d   dk(  sŒw| j                  |«       Œ‰ y )Nr   r   )r,   r¿  r<  ÚoperatorÚgetitemrJ  ru   r=  Úall_gather_copy_inrx   rZ  )Úgr9  r�   r.   s      €r@   Úremove_unused_getitemz8reinplace_fsdp_all_gather.<locals>.remove_unused_getitem¡	  su   ø€ ä˜Ÿ™“Mˆ	Øò 	 ˆAà—‘œH×,Ñ,Ò,Ø—F‘F˜1‘I×$Ñ$¨¯	©	¯©×(IÑ(I×(QÑ(QÒQØ—F‘F˜1‘I “Nà—‘˜Q•ñ	 rJ   Úall_gather_inputsÚall_gather_outputÚinp_split_sizesÚall_gather_input_numelÚrankÚitem_idxÚ
group_sizeÚ
group_namec                ó&   — | j                   d   dk(  S )Nrv  r   )Úkwargs)Úmatchs    r@   r7  z+reinplace_fsdp_all_gather.<locals>.<lambda>Â	  s   €  %§,¡,¨zÑ":¸aÑ"?€ rJ   )Ú	pass_dictÚextra_checkc                ól   •— ˆfd„}| j                  ||d   |d   |d   |d   |d   |d   |d   g«       y )	Nc                 óú   •— | d d }| d   }| d   } ‰j                   j                  j                  j                  |Ž }|d   }|d   }‰j                   j                  j
                  j                  ||||¬«      }|S )Néþÿÿÿrí  r   r   )Úout)ru   r=  rn  rx   Ú_c10d_functionalÚall_gather_into_tensor_out)	rJ  Úcopy_in_argsrw  rx  rn  rm  Ú	getitem_1Úall_gather_into_tensorr.   s	           €r@   ÚreplzEreinplace_fsdp_all_gather.<locals>.reinplace_all_gather.<locals>.replÅ	  s–   ø€ ð    ˜9ˆLØ˜b™ˆJØ˜b™ˆJØ!J §¡§¡×!BÑ!B×!JÑ!JØð"Ðð )¨Ñ+ˆGØ*¨1Ñ-ˆIà—	‘	×*Ñ*×EÑE×MÑMØ˜Z¨¸ð Nó ð #ð
 *Ð)rJ   rq  rr  rs  rt  ru  rw  rx  )Úreplace_by_example)r{  rJ  rz  r‡  r.   s       €r@   Úreinplace_all_gatherz7reinplace_fsdp_all_gather.<locals>.reinplace_all_gather®	  s[   ø€ ô.	*ð$ 	× Ñ ààÐ*Ñ+ØÐ*Ñ+ØÐ(Ñ)ØÐ/Ñ0Ø�v‘Ø�|Ñ$Ø�|Ñ$ðõ	
rJ   )r{  rh  )Ú5torch.distributed.fsdp._fully_shard._fsdp_collectivesr'   r½  ru   r‚  r†  rƒ  ÚImportErrorr  ÚAssertionErrorÚpattern_matcherrf  rg  rh  ri  rj  rx   rl  rm  r=  rn  Úapply)
r]  rf  rg  rh  ri  rj  rp  Ú
graph_passr‰  r.   s
            @r@   Úreinplace_fsdp_all_gatherr�  |	  sd  ø€ ð
ÛDà× Ñ ×-Ñ-Ô/Ð/Ð/ð �I‰I×&Ñ&×=Ò=Ø—	‘	×*Ñ*×EÒEð	
ðFØE÷
õ ðô 	 ñ $Ó%€JáÙØ�I‰I×&Ñ&×=Ñ=×EÑEÙÜ× Ñ ÙØ—I‘I—N‘N×5Ñ5×=Ñ=ÙÐ2Ó3ÙÐ2Ó3ÙÐ0Ó1ÙÐ7Ó8Ù˜vÓ&óñ ˜:Ó&óñ �|Ó$Ù�|Ó$ó	
ð$ Ù?ô)ô,
ó-ð,
ñB ˜%Ô Ø×Ñ�UÕøôA œ¬Ð8ò Ùðús   ƒA"E ÅE1Å0E1c                óâ   — t        | t        j                  j                  j                  t        j                  j                  j
                  f«      rJ ‚t        | j                  «       dd  «      S )Né   )r„   r.   Ú	_inductorÚ	schedulerÚFusedSchedulerNoder~   rX   rŒ   rÃ   s    r@   Ú
get_op_idxr–  é	  s]   € ÜØä�O‰O×%Ñ%×8Ñ8Ü�O‰O×%Ñ%×:Ñ:ð	
ôð ð ô ˆu�~‰~Ó  Ð#Ó$Ð$rJ   c           	     ó~	  ‡‡‡ ‡!— ddl mŠ  g }t        t           «       }d}d}i }i }i Š!ˆ ˆ!fd„}	| D �]  }
t	        |
j
                  t        j                  j                  j                  j                  ¬«      �rßt        ˆfd„|
j                  D «       «      �rÀd}|
}t        «       }t        |||‰«       t        t        j                  j                  j                  j                  t        j                  j                  j                  j                  t        j                  j                  j                   j                  g«      Št#        |||‰ˆˆ fd„¬	«       t%        |d
„ ¬«      }t'        |«      }d}t)        t'        |«      «      D ]W  }||   }t+        |j
                  t        j                  j                  j                   j                  «      r|dz  }|dkD  sŒU|} n |d | }d }t)        t'        |«      dz
  «      D ]3  }t-        ||dz      j
                  t.        j0                  «      sŒ.|dz   } n |€J ‚ |	|d | «      } |	||d  «      }|||<   �Œ't+        |
j
                  t        j                  j                  j2                  j                  «      s�Œkd}|
}t        «       }t#        |||‰«       t%        |d„ ¬«      }d }t)        t'        |«      dz
  «      D ]3  }t-        ||dz      j
                  t.        j0                  «      sŒ.|dz   } n |€J ‚ |	|d | «      } |	||d  «      }|||<   �Œ t'        ‰!«      dkD  sJ ‚|rt'        |«      dkD  sJ ‚|rt'        |«      dkD  sJ ‚| D ]N  }
|
j5                  «       ‰!v r‰!|
j5                  «          }
|
|v rŒ-|j7                  |
«       |j9                  |
«       ŒP d }|j;                  «       D ]k  \  }}|�bt=        t?        |jA                  «       «      «      }|jC                  «       D ]-  }|jE                  tG        |j5                  «       |d¬«      «       Œ/ |}Œm d }|j;                  «       D ]k  \  }}|�bt=        t?        |jA                  «       «      «      }|jC                  «       D ]-  }|jE                  tG        |j5                  «       |d¬«      «       Œ/ |}Œm |S )Nr   )r”  Fc                ó˜   •— ‰j                   j                  | «      }| D ]  }|‰|j                  «       <   Œ |‰|j                  «       <   |S re   )r~   ÚcreaterŒ   )Úsnodes_to_groupÚ
group_noder8   r”  Úsnode_name_to_final_snodes      €€r@   Ú_create_group_nodez:enforce_comm_ordering_for_fsdp.<locals>._create_group_node
  sV   ø€ Ø×3Ñ3×:Ñ:¸?ÓKˆ
Ø$ò 	EˆEØ:DÐ% e§n¡nÓ&6Ò7ð	Eà;EÐ! *×"5Ñ"5Ó"7Ñ8ØÐrJ   )rW  c              3  ó¨   •K  — | ]I  }t        ‰|   j                  t        j                  j                  j
                  j                  «      –— ŒK y ­wre   )r   rz   r.   ru   r=  rn  rx   )r�   r‚   r�  s     €r@   rƒ   z1enforce_comm_ordering_for_fsdp.<locals>.<genexpr>
  sD   øè ø€ ò 
ð ô Ø" 1Ñ%×*Ñ*¬E¯I©I¯N©N×,MÑ,M×,UÑ,U÷ñ
ùs   ƒAATc                ó–   •— t        | ‰j                  «      xs0 t        | ‰j                  «      xr | j                  j                  ‰v  S re   )r„   ÚNopKernelSchedulerNodeÚExternKernelSchedulerNoderz   Úop_overload)r‚   Úallowed_opsr”  s    €€r@   r7  z0enforce_comm_ordering_for_fsdp.<locals>.<lambda>.
  sF   ø€ Ü˜q )×"BÑ"BÓCò ä" 1 i×&IÑ&IÓJò >ØŸF™F×.Ñ.°+Ð=ð	'€ rJ   )Úcriteria_cbc                ó   — t        | «      S re   ©r–  r¤  s    r@   r7  z0enforce_comm_ordering_for_fsdp.<locals>.<lambda>9
  ó
   € ´J¸q³M€ rJ   r¥  r   c                ó   — t        | «      S re   r¦  r¤  s    r@   r7  z0enforce_comm_ordering_for_fsdp.<locals>.<lambda>j
  r§  rJ   r»  )$r[   r”  r
   r   r   rz   r.   ru   r‚  rƒ  rx   r…   r±  r   Úwait_tensorr=  Úsplit_with_sizes_copyr   Úsortedr«   r*   r   r„   r   Ú_WaitKernelÚ	chunk_catrŒ   rÊ   r´   r=  rˆ  r‰  r�   r¾   r¾  r   )"r5   rÀ  r�  Ú	new_orderr   Ú	ag_existsÚ	rs_existsÚ$ag_grouped_node_to_wait_grouped_nodeÚ$rs_grouped_node_to_wait_grouped_noder�  r8   Úag_snodeÚag_related_snode_setÚag_related_snodesÚend_idx_of_current_ag_blockÚcopy_out_countr®   Ú	cur_snodeÚwait_node_idxÚag_group_nodeÚag_wait_group_nodeÚrs_snodeÚrs_related_snode_setÚrs_related_snodesÚrs_group_nodeÚrs_wait_group_nodeÚprev_ag_waitÚwait_group_noder¼  r¼   Úprev_rs_waitr£  r”  rœ  s"     `                            @@@r@   Úenforce_comm_ordering_for_fsdprÄ  ô	  sõ  û€ õ
 à)+€IÜœ3‘Ó!€IØ€IØ€IØ+-Ð(Ø+-Ð(Ø "Ðõð ó nUˆäØ�J‰Jœ5Ÿ9™9×5Ñ5×PÑP×XÑXö
äó 
ð —_‘_ô	
õ 
ð ˆIØˆHÜLVËLÐ ô (ØØ$ØØ"ô	ô %ä—I‘I×.Ñ.×IÑI×QÑQÜ—I‘I×.Ñ.×:Ñ:×BÑBÜ—I‘I—N‘N×8Ñ8×@Ñ@ðóˆKô )ØØ$ØØ"ôõô !'Ø$Ñ*Aô!Ðô +.Ð.?Ó*@Ð'ØˆNÜœ3Ð0Ó1Ó2ò �Ø-¨aÑ0�	Ü!Ø—N‘N¤E§I¡I§N¡N×$HÑ$H×$PÑ$Pôð # aÑ'�NØ! AÓ%Ø23Ð/Ùðð !2Ð2NÐ3NÐ OÐð !ˆMÜœ3Ð0Ó1°AÑ5Ó6ò �ÜÐ/°°A±Ñ6×;Ñ;¼R¿^¹^ÕLØ$%¨¡E�MÙðð !Ð,Ð,Ð,Ù.Ð/@ÀÀ-Ð/PÓQˆMñ "4Ð4EÀmÀnÐ4UÓ!VÐàBTÐ0°Ó?ô ˜EŸJ™J¬¯	©	¯©×(@Ñ(@×(HÑ(HÖIØˆIØˆHô MWËLÐ Ü(ØØ$ØØ"ô	ô !'Ø$Ñ*Aô!Ðð
 !ˆMÜœ3Ð0Ó1°AÑ5Ó6ò �ÜÐ/°°A±Ñ6×;Ñ;¼R¿^¹^ÕLØ$%¨¡E�MÙðð !Ð,Ð,Ð,Ù.Ð/@ÀÀ-Ð/PÓQˆMñ "4Ð4EÀmÀnÐ4UÓ!VÐàBTÐ0°Ó?ð]nUô` Ð(Ó)¨AÒ-Ð-Ð-ÙÜÐ7Ó8¸1Ò<Ð<Ð<ÙÜÐ7Ó8¸1Ò<Ð<Ð<ð ò ˆØ�>‰>ÓÐ8Ñ8Ø-¨e¯n©nÓ.>Ñ?ˆEØ�IÑØØ×Ñ˜ÔØ�‰�eÕðð €LØ*N×*TÑ*TÓ*Vò 'Ñ&ˆ�ØÐ#Ü¤ ]×%CÑ%CÓ%EÓ FÓGˆLØ!×-Ñ-Ó/ò �Ø×*Ñ*Ü˜AŸJ™J›L°|ÈTÔRõðð '‰ð'ð €LØ*N×*TÑ*TÓ*Vò 'Ñ&ˆ�ØÐ#Ü¤ ]×%CÑ%CÓ%EÓ FÓGˆLØ!×-Ñ-Ó/ò �Ø×*Ñ*Ü˜AŸJ™J›L°|ÈTÔRõðð '‰ð'ð ÐrJ   )r5   úlist[BaseSchedulerNode])r5   rÅ  rã   rÅ  )rz   zIRNode | Operation | Nonerã   rÐ   )r8   r   rã   rÐ   )r8   r   )F)rã   rV   )r™   rÅ  rã   rV   )r5   rÅ  rã   z~tuple[dict[BaseSchedulerNode, BaseSchedulerNode | None], dict[BaseSchedulerNode, BaseSchedulerNode | None], BaseSchedulerNode])r¦   r�   rã   ú#dict[BaseSchedulerNode, OrderedSet])r5   rÅ  rã   z(dict[BaseSchedulerNode, OrderedSet[str]])rË   úBaseSchedulerNode | NonerÌ   rÇ  rÍ   ú1dict[BaseSchedulerNode, BaseSchedulerNode | None]rã   rÅ  )
rÑ   r   rÒ   r   rÓ   ú'dict[BaseSchedulerNode, frozenset[str]]rÔ   rÉ  rã   rÐ   )rÑ   r   rÍ   rÈ  rÝ   údict[BaseSchedulerNode, float]rÓ   rÉ  rÔ   rÉ  rã   útuple[float, float, str])rÒ   r   rË   r   rì   rÈ  rÝ   rÊ  rÓ   rÉ  rÔ   rÉ  rã   rË  )rñ   r   rò   r   ró   r   rì   rÈ  rÍ   rÈ  rË   r   rã   r   )rñ   r   r™   rÅ  ró   r   rü   rX   rý   rX   rþ   r   rÿ   r�   r   r�   rã   z(tuple[int, dict[BaseSchedulerNode, int]])rñ   r   r™   rÅ  ró   r   rý   rX   rþ   r   rÿ   r�   r  údict[BaseSchedulerNode, int]r   r�   r¦   r�   r¥   r�   rã   rU   )
rñ   r   r™   rÅ  r¦   r�   r¨   rÆ  rã   z8dict[BaseSchedulerNode, list[FreeableInputBuffer | Any]])rñ   r   rã   ztuple[bool, str | None])rE  z$dict[BaseSchedulerNode, ReorderInfo]rË   r   rÍ   rÈ  rF  rX   r£   rX   r¢   r�   r¡   úOrderedSet[str]rã   rÅ  )r5   rÅ  rã   zDtuple[list[BaseSchedulerNode], dict[BaseSchedulerNode, ReorderInfo]])
r5   rÅ  rD   rÐ   rE   rÐ   rF   rÐ   rã   rÅ  )r¿  rÅ  rã   rÅ  )rñ   r   r™   rÅ  rý   rX   rþ   r   rÌ  r�   r  rÌ  rÍ  rÌ  r   r�   r¥   r�   rã   rU   )rñ   r   r™   rÅ  rò   r   rü   rX   rý   rX   rþ   r   rÌ  r�   r   r�   r¥   r�   rã   zFtuple[int, dict[BaseSchedulerNode, int], dict[BaseSchedulerNode, int]])rE  z%dict[BaseSchedulerNode, SinkWaitInfo]rË   r   rÍ   rÈ  rF  rX   r£   rX   r¢   r�   r¡   rÍ  rã   rÅ  )r5   rÅ  rã   zEtuple[list[BaseSchedulerNode], dict[BaseSchedulerNode, SinkWaitInfo]])r8   r   rã   r^   )r]  útorch.fx.Graph)r]  rÎ  rã   rU   )r5   ú1list[torch._inductor.scheduler.BaseSchedulerNode]rÀ  z4dict[str, torch._inductor.scheduler.SchedulerBuffer]r�  zdict[str, BaseSchedulerNode]rã   rÏ  )fÚ
__future__r   r›  r?  rÔ  Úloggingrl  r¯  Úcollectionsr   Údataclassesr   Útypingr   r   r.   Útorch._loggingr   Ú torch.multiprocessing.reductionsr	   Útorch.utils._ordered_setr
   r[   r   r   r   Údependenciesr   r   r   Úmemoryr   r   r   r   Úutilsr   r   r   r   r   r   r   Úvirtualizedr   Ú	getLoggerrk   r0  Ú_loggingÚgetArtifactLoggerrC  r$   r   rA   rE   rD   rM   rR   rT   r{   r€   rŠ   r‘   r•   r›   r©   r°   rŸ   r¿   rÄ   rÆ   rÈ   rÎ   r×   ré   rï   rö   r  r  r  r"  rM  rO   rH   rÂ  rÄ  rÊ  rÑ  rÜ  rà  ræ  ré  r   rî  r_  r>  r&  r+  rd  r�  r–  rÄ  rq   rJ   r@   ú<module>rß     sø  ðõ #ã Û Û Û Û Û 
Ý #Ý !ß %ã Ý +Ý ;Ý /ç &Ñ &Ý !ñ ß%÷ó ÷÷ ñ õ ð €g×Ñ˜Ó!€Ø�n‰n×.Ñ.¨x¸ÓC€áÝ;ð#FØ#ó#FóLóðØ#ðàóð&#Ø#ð#àó#ðL ÷9ð 9ó ð9ó(ó"(óôò0ó3òð2Ø#ððóð"(Øð(à(ó(ð0Ø#ðà-óò"Gò
ò;ðØ
"ðà
"ðð Aðð ó	ð6.Ø'ð.à!ð.ð >ð.ð ;ð	.ð
 
ó.ð9.Ø'ð9.à@ð9.ð -ð9.ð >ð	9.ð
 ;ð9.ð ó9.ðx9.Ø!ð9.à
ð9.ð Að9.ð -ð	9.ð
 >ð9.ð ;ð9.ð ó9.ðx.Ø ð.à!ð.ð "ð.ð Að	.ð
 Að.ð ð.ð ó.ðb@.Ø ð@.à	 ð@.ð "ð@.ð ð	@.ð
 ð@.ð %ð@.ð 6:ð@.ð ð@.ð .ó@.ðFJØ ðJà	 ðJð "ðJð ð	Jð
 %ðJð 6:ðJð 4ðJð ðJð  ðJð ðJð 
óJðZ$;Ø ð$;à	 ð$;ð  ð$;ð >ð	$;ð
 >ó$;ðNØ ðàóð<bØ/ðbà
ðbð Aðbð ð	bð
 ðbð !%ðbð #ðbð óbðJUØ#ðUàIóUðp
YØ#ðYàðYð ðYð ð	Yð
 óYðxØ"ðàóð0 ÷9ð 9ó ð9ð"(Ø ð(àó(ðV2
Ø ð2
à	 ð2
ð ð2
ð %ð	2
ð
 >Bð2
ð 4ð2
ð 9ð2
ð ð2
ð ð2
ð 
ó2
ðjCGØ ðCGà	 ðCGð "ðCGð ð	CGð
 ðCGð %ðCGð >BðCGð ðCGð ðCGð LóCGðL.Ø ð.à!ð.ð "ð.ð Að	.ð
 Að.ð ð.ð ó.ðbWØ0ðWà
ðWð AðWð ð	Wð
 ðWð !%ðWð #ðWð óWðt4CØ ð4Cà	 ð4Cð  ð4Cð >ð	4Cð
 >ó4CðnLØ#ðLàJóLó^
5ó4	òAò>#ðLØ#ðàóó ~#óBjòZ%ðnØ=ðnàEðnð 5ðnð 7ô	nrJ   