a
    h                     @  s  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 d	dlmZ d	dl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)e*Z+ej,-e*dZ.erd dl/m0Z0 dddddZ1dddddZ2dddddZ3dddddZ4eG dd dZ5dddddZ6dd d d dd!d"d#Z7ddd$d%d&Z8d'd(d)d*d+Z9d,d- Z:d.d/ Z;dddd0d1Z<d2d3d4d5Z=d2d6d7d8d9Z>d:d; Z?d<d=d>d<d?d@dAZ@dS )B    )annotationsN)defaultdict)	dataclass)AnyTYPE_CHECKING)trace_structured)StorageWeakRef)
OrderedSet   )configir)WeakDep)estimate_peak_memoryFreeableInputBufferget_freeable_input_buf)contains_collectivecontains_waitfind_recursive_deps_of_nodefind_recursive_users_of_nodeis_collectiveis_fallback_opis_wait)Voverlap)BaseSchedulerNodezlist[BaseSchedulerNode])snodesreturnc                 C  s   t | ddddS )z7
    Greedily schedules waits as late as possible.
    FTraise_comms
sink_waitsreorder_for_overlap_schedule_for_commr    r$   C/var/www/auris/lib/python3.9/site-packages/torch/_inductor/comms.pyr   *   s    r   c                 C  s   t | ddddS )z8
    Greedily schedules comms as early as possible.
    TFr   r!   r#   r$   r$   r%   r   3   s    r   c                 C  s   t | d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.
    Tr   r!   r#   r$   r$   r%   reorder_compute_for_overlap<   s    r&   c                   s   t | \}fddD  t fdd D }tfddD }d| d| dg d	}d
d  D }tjdrddlm} |||d7 n,d7 t|d 7 dt	t|7 t
 tddd fddd |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)

    c                   s   i | ]}| | j qS r$   improvement.0snode
node_statsr$   r%   
<dictcomp>q       z@reorder_communication_preserving_peak_memory.<locals>.<dictcomp>c                   s   g | ]} | qS r$   r$   r)   r'   r$   r%   
<listcomp>r   r/   z@reorder_communication_preserving_peak_memory.<locals>.<listcomp>c                   s   g | ]} | j qS r$   )movesr)   r,   r$   r%   r0   s   r/   zAreorder_communication_preserving_peak_memory improved overlap by z
 ns after z reorders.
)zCollective nodezinitial exposedzfinal exposedr(   zlimiting factorr1   c                 S  s.   g | ]&\}}t ||j|j|j|j|jgqS r$   )node_summaryinitial_exposedfinal_exposedr(   limiting_factorr1   )r*   r+   Znode_reorder_infor$   r$   r%   r0      s   	tabulater   )r6   )headersz>Please `pip install tabulate` to nicely render overlap stats.

Zartifactc                   S  s
   dddS )N,reorder_communication_preserving_peak_memorystring)nameencodingr$   r$   r$   r$   r%   <lambda>   s    z>reorder_communication_preserving_peak_memory.<locals>.<lambda>c                     s    S Nr$   r$   )reorder_log_strr$   r%   r=      r/   )Zmetadata_fnZ
payload_fn)6_reorder_communication_preserving_peak_memory_internalsumitems	importlibutil	find_specr6   strjoinmapoverlap_loginfor   )r   Zreordered_snodesZtotal_improvementtotal_movesr7   rowsr6   r$   )r(   r-   r?   r%   r9   O   s>     	


	r9   c                   @  sN   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< e	dd Z
dS )ReorderInfozE
    Debug info describing how an individual snode was reordered
    floatr3   r4   NonerF   r5   r   intr1   c                 C  s   | j | j S r>   )r3   r4   )selfr$   r$   r%   r(      s    zReorderInfo.improvementN)__name__
__module____qualname____doc__r3   __annotations__r4   r5   r1   propertyr(   r$   r$   r$   r%   rM      s   
rM   zDtuple[list[BaseSchedulerNode], dict[BaseSchedulerNode, ReorderInfo]]c                   sH  t | d }d}t | }tjdur(tj}ttjj }ttj }t	| |}t
| ||\}}dd | D i }	fdd}
t| D ]\}}t|rt  }|	|< |
|| |d d  |_|_||krd	|_qt|d d
d
D ]V}| | }|td|| k rd|_ qt|r$d|_ qtdd |jD  t fdd| D rht|shd|_ q|||  ||d  ||  k rd|_ q|j| krd|_ q| jd7  _|d7 }| | }| |d  | |< || |d < ||d  ||  }|| ||d   }|| | | ||< |
|| |d d |_qq| |	fS )z
    Internal testing helper that also returns debug info.
    Returns:
        - reordered snodes list
        - dict {snode: ReorderInfo}
    d   r   Nc                 S  s   i | ]}|t |qS r$   estimate_op_runtimer)   r$   r$   r%   r.      r/   zJ_reorder_communication_preserving_peak_memory_internal.<locals>.<dictcomp>c                   sF   t | }d}|D ]&}t|rqt|r* q8| | 7 }qtd|| S )N        r   )r[   r   r   max)Zcollective_snodeZremaining_snodesZ	comm_timeZcompute_timer+   )runtimesr$   r%   exposed_communication_time   s    zZ_reorder_communication_preserving_peak_memory_internal.<locals>.exposed_communication_timer
   z
move limitrN   zprefetch limitzcollective orderingc                 S  s   g | ]
}|j qS r$   r;   )r*   sr$   r$   r%   r0      r/   zJ_reorder_communication_preserving_peak_memory_internal.<locals>.<listcomp>c                 3  s   | ]}|   v V  qd S r>   )get_name)r*   o)	dep_namesr$   r%   	<genexpr>   s   zI_reorder_communication_preserving_peak_memory_internal.<locals>.<genexpr>zdata dependencyzpeak memoryzsufficient overlapping)lenr   Zreorder_prefetch_limitr	   r   graphgraph_inputskeysget_output_namesr   r   	enumerater   rM   r3   r4   r5   ranger]   unmet_dependenciesanyget_outputsr   r1   )r   Z
MOVE_LIMITrK   ZPER_COLLECTIVE_PREFETCH_LIMITrh   graph_outputsZname_to_freeable_input_bufpeak_memoryZcurr_memorystatsr_   ir+   Zreorder_infojZ
prev_snodetmpZj_plus_one_allocZj_allocr$   )rd   r^   r%   r@      st    




"
r@   bool)r   r   r   r    r   c                   s(  i }i i i i   	t | D ]b\}}| D ]}|||< q0| D ]}||< qF|| < | }	tj|	< d|	< |	|	< q d}
| D ]h}|rt|r|
| < |jD ]"}|  }t| |
|< q|
d7 }
q|rt	|rd| < qG 	fddd dd | D g t
tdd | D 
 D ]B\}}t|dkrdt | |D ]}| | qhq>g  fdd	fd
d
fdd}trtj}|rt|r|| n| q D ]&\}}t|dksJ d qS )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                      s,   e Zd Zdd fddZdd ZdS )z$_schedule_for_comm.<locals>.RunnablerP   )r   c                   s>   || _ tt| } |  }| | | f| _d S r>   )r+   nextiterget_operation_namesrb   score)rR   r+   r;   Z
fused_namename_to_fused_nodescores_0scores_1scores_2r$   r%   __init__Q  s    z-_schedule_for_comm.<locals>.Runnable.__init__c                 S  s   | j |j k S r>   rz   )rR   otherr$   r$   r%   __lt__[  s    z+_schedule_for_comm.<locals>.Runnable.__lt__N)rS   rT   rU   r   r   r$   r{   r$   r%   RunnableP  s   
r   c                 S  s"   i | ]}|t d d |jD qS )c                 s  s   | ]}|j V  qd S r>   r`   )r*   depr$   r$   r%   re   _  r/   z0_schedule_for_comm.<locals>.<dictcomp>.<genexpr>)r	   rm   r)   r$   r$   r%   r.   ^  s   z&_schedule_for_comm.<locals>.<dictcomp>c                 S  s   i | ]}|t |qS r$   rZ   r)   r$   r$   r%   r.   e  r/   c                   sX    |  |  D ]@}| D ]2} |  | t|  dkrt |  qqdS )zU
        Schedules `snode` and put all unblocked nodes onto the ready queue.
        r   N)appendget_buffer_namesremoverf   heapqheappush)r+   buf_name)r   buffer_usersready	scheduled
unmet_depsr$   r%   scheduleo  s    
z$_schedule_for_comm.<locals>.schedulec                    s.   dd  D } t | dkrdS t| dd dS )zh
        Return the next node in the ready queue that's neither a collective or
        a wait.
        c                 S  s$   g | ]}t |jst|js|qS r$   )r   r+   r   r*   xr$   r$   r%   r0     s   zI_schedule_for_comm.<locals>.get_overlapping_candidate.<locals>.<listcomp>r   Nc                 S  s   | j S r>   r   r   r$   r$   r%   r=     r/   zG_schedule_for_comm.<locals>.get_overlapping_candidate.<locals>.<lambda>key)rf   min)
candidates)r   r$   r%   get_overlapping_candidatez  s    z5_schedule_for_comm.<locals>.get_overlapping_candidatec                   sd   t | sJ |  |  }|dkrV   }durV| |j ||j 8 }qt dS )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   r+   r   heapify)r+   Zcollective_cost	candidate)r   r   r   snode_to_costr$   r%   schedule_collective_for_overlap  s    

z;_schedule_for_comm.<locals>.schedule_collective_for_overlapz;Detected unscheduled nodes. Nodes with unmet dependencies: )rk   r   ry   rb   sysmaxsizer   	ancestorsr   r   r   r	   rB   rf   r   r   addheappopr+   )r   r   r   r    Zbuf_name_to_snodeidxr+   r   Zop_name	node_nameZcomm_idxZancestorZanc_fused_namedepsr   r   r$   )r   r   r   r|   r   r   r   r}   r~   r   r   r   r%   r"     sb    &







r"   )nodesr   c                 C  st   t j s| S dd | D }tdt|D ]D}tt||  }||d   D ]}|| t	||d qRq*| S )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
    c                 S  s   g | ]}t |r|qS r$   )r   )r*   nr$   r$   r%   r0     r/   z3decide_global_ordering_of_comms.<locals>.<listcomp>r
   mutating_buf)
torchdistributedis_availablerl   rf   rw   rx   r   add_fake_depr   )r   name_to_bufr|   Z
comm_nodesrs   r   bufr$   r$   r%   decide_global_ordering_of_comms  s    
r   r   rO   )r+   r   c                 C  s0   t jdkr|  }ntt js"J t | }|S )z:
    Returns estimated op runtime in nanoseconds (ns)
    default)r   r[   get_estimated_runtimecallable)r+   Zruntimer$   r$   r%   r[     s
    


r[   c                 C  s   |   }t|dkrd}t| jtjtjfr<d| jj d}dd |   D }ddd |D }z| j	 }W n t
y   d}Y n0 | jjj | | d| d|  d	d
S g }|D ]}|t| q| jj dd| S )Nr
    z ()c                 S  s   g | ]}|j  qS r$   )nodeZget_output_spec)r*   childr$   r$   r%   r0     r/   z node_summary.<locals>.<listcomp>,c                 S  s2   g | ]*}t |tjr*d |j d|j dndqS )z (size=z	, stride=r   r   )
isinstancer   ZLayoutsizeZstride)r*   Zlayoutr$   r$   r%   r0     s   
z.0fz ns): z, )Z	get_nodesrf   r   r   r   ZExternKernelOutZ_CollectiveKernelZpython_kernel_namerG   Zmaybe_get_nameAttributeError	__class__rS   r   r   r2   )r+   r   ZdetailZlayoutsZout_tensor_infor   Z	summariesZchild_snoder$   r$   r%   r2     s(    
*r2   c                 C  s   d}d }dd }t | D ]\}}|d u rnt|rD|t|7 }|j}nt|jrPn|t|7 }||t|  qt|r|t|7 }|j}||t|  qt|jr||t|  d }q||dt|  qtd|d d   d S )Nr\   c                 S  s   t | dd|  d S )Nz>6r   )rI   debug)stepmsgr$   r$   r%   step_log  s    z#visualize_overlap.<locals>.step_logz| zEst. runtime (ms): i  )rk   r   r[   r   r   r2   rI   r   )orderZtotal_est_runtimeZcur_comm_noder   r   r+   r$   r$   r%   visualize_overlap  s.    

r   c           
      C  s  | }t tjj }t tj }tjD ]`}t|t	rL|t
 v rLt
 | }t|sdJ d| dt| t| ||\}}tj dkrtd| d|d zt| W n2 ty } ztjd|d W Y d }~n
d }~0 0 t }||}t | }	tj dkrftd	| d
|	 d zt| W n4 tyd } ztjd|d W Y d }~n
d }~0 0 t| t| ||\}}td| q(|S )Nz3Invalid reorder_compute_and_comm_for_overlap pass: z is not callabler   z.==== Visualize overlap before reordering pass z, peak_memory=z ====r   )exc_infoz-==== Visualize overlap after reordering pass z	 (ran in z	 sec)====zfinal peak_memory=)r	   r   rg   rh   ri   rj   r   Z'reorder_for_compute_comm_overlap_passesr   rF   globalsr   r   r   r   r   Zget_rankrI   r   r   	Exceptiontimeprint)
r   r   rh   rp   prq   _et0tr$   r$   r%   $reorder_compute_and_comm_for_overlap  sH    


$$r   ztorch.fx.Graph)rg   c              
     sJ  t | jtt tt  tD ]\}}|jdkr"|jtjjj	j
kr"|jd jdksrJ d| d|jd  d|jd }|jd }|dkr| | q" | | q" fdd	}tt }tD ]j\}}|jdkr|jtjjjj
kr|}|jd jdks"J d
 d|  d|r| | qdd }dd D ]Z}|jdkrNt|jtjjrN|jjjrN||sN|| rNJ d| dqN| D ]\}	t|	D ]\}
}| }|jd u sJ |j\}|d }|
t|	d k r|	|
d  n
td }|| }tfdd|D rfJ d d| d|  d|D ]R}|jdkrj|jv rj|jtjjj	j
krjtfdd|jD }||_qjqĐq| D ]0\}	t|	D ]\}
}| }| | qސqΈD ]@}|jdkr|jtjjj	j
kr|jd |v r| | qdS )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 r8   r
   c                   s    | g }  | g }t|t|ksRtd|  dt| dt| d dS t||D ]H\}}||kr\td|  d|  d| d	|  d| d
  dS q\dS )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)getrf   logwarningzip)graph_inputZresized_to_full_idxesZresized_to_0_idxesZresize_to_full_idxZresize_to_0_idx)&graph_input_to_resized_to_0_node_idxes)graph_input_to_resized_to_full_node_idxes	node_listr$   r%   check_resize_patternY  sD    zLremove_fsdp2_unsharded_param_graph_input_usage.<locals>.check_resize_patternz\
Assumed all FSDP2 `unsharded_param`s to be graph input, but it's not true!
Offending node: z	. Graph: c                 S  s$   | j tjjjjkp"| j tjjjjkS r>   )targetr   opsfsdpcopy_r   inductorresize_storage_bytes_r   r$   r$   r%   is_allowed_mutation  s    zKremove_fsdp2_unsharded_param_graph_input_usage.<locals>.is_allowed_mutationc                   sd   t  jtjjr(dd t jjjD ng }t fdd|D }tdd |D }t	||@ dkS )Nc                 S  s&   g | ]\}}|j d ur|j jr|qS r>   )Z
alias_infoZis_write)r*   rs   r   r$   r$   r%   r0     s   zyremove_fsdp2_unsharded_param_graph_input_usage.<locals>.is_node_mutating_unsharded_param_or_its_alias.<locals>.<listcomp>c                   s$   g | ]}t  j| jd   qS val)r   argsmetauntyped_storage)r*   rs   r   r$   r%   r0     s   c                 S  s   g | ]}t |jd   qS r   )r   r   r   )r*   unsharded_paramr$   r$   r%   r0     s   r   )
r   r   r   _ops
OpOverloadrk   _schema	argumentsr	   rf   )r   Zunsharded_paramsZmutated_arg_idxesZmutated_node_arg_storagesZstorages_of_unsharded_paramsr$   r   r%   -is_node_mutating_unsharded_param_or_its_alias  s"    	
zeremove_fsdp2_unsharded_param_graph_input_usage.<locals>.is_node_mutating_unsharded_param_or_its_aliaszdUser mutation on FSDP2 unsharded param is not allowed when Traceable FSDP2 is used. Violating node: c                 3  s   | ]} |gV  qd S r>   r$   )r*   r   )r   r   r$   r%   re     s   zAremove_fsdp2_unsharded_param_graph_input_usage.<locals>.<genexpr>z(Assumed no ops mutating unsharded param z in subgraph z, but it's not true!
Graph: c                 3  s   | ]}|u r n|V  qd S r>   r$   )r*   arg)replacementr   r$   r%   re     s   N)listr   r   rk   opr   r   r   r   r   r   r   r   r   r   r   r   r   r   Z
is_mutableri   rB   rf   rn   tuple
erase_node)rg   r   r   r   Znew_sizer   Z'unsharded_param_to_fsdp_copy_node_idxesZfsdp_copy_noder   Zfsdp_copy_node_idxesrs   Zfsdp_copy_node_idxr   Zsubgraph_start_idxZsubgraph_end_idxZsubgraph_nodesnew_argsr$   )r   r   r   r   r   r   r%   .remove_fsdp2_unsharded_param_graph_input_usage7  s    



%



r   rP   )rg   r   c           	        s   z2dd l   j sJ  jjjr, jjjs0J W n ttt	fyL   Y d S 0 ddl
m}m}m}m}m}  fdd}| }|| jjjj|tj| jjjj|d|d|d|d	|d
|d|d|d|d
|d|d|d|dd ddd fdd}||  ||  d S )Nr   r
   )CallFunction
KeywordArgMatchPatternMatcherPassregister_graph_patternc                   sT   t | j}|D ]@}|jtjkr|jd j jjjj	u r|jd dkr| 
| qd S )Nr   r
   )r   r   r   operatorgetitemr   r   r   all_gather_copy_inr   r   )gr   r   r   r$   r%   remove_unused_getitem   s    

z8reinplace_fsdp_all_gather.<locals>.remove_unused_getitemall_gather_inputsinp_split_sizesall_gather_input_numel
world_sizerankdtypedevicegroup_name_inner"allocate_memory_from_process_groupitem_idx
group_size
group_namec                 S  s   | j d dkS )Nr  r   )kwargsmatchr$   r$   r%   r=   D  r/   z+reinplace_fsdp_all_gather.<locals>.<lambda>)Z	pass_dictZextra_checkr   r  c                   s^    fdd}|  ||d |d |d |d |d |d |d	 |d
 |d |d |d g d S )Nc                    sX   | d d }| d }| d } j jjj| }|d }|d } j jjj||||d}|S )NrN   r   r
   )out)r   r   r   r   _c10d_functionalall_gather_into_tensor_out)r   Zcopy_in_argsr	  r
  r   r   Z	getitem_1all_gather_into_tensorr   r$   r%   replG  s    

zEreinplace_fsdp_all_gather.<locals>.reinplace_all_gather.<locals>.replr   r   r  r  r  r  r  r  r  r	  r
  )Zreplace_by_example)r  r   r  r  r   r$   r%   reinplace_all_gather-  s     z7reinplace_fsdp_all_gather.<locals>.reinplace_all_gather)Z5torch.distributed.fsdp._fully_shard._fsdp_collectivesr   r   r   r  r  r  ImportErrorr   AssertionErrorZpattern_matcherr   r   r   r   r   r   r   r   r   r   apply)	rg   r   r   r   r   r   r   Z
graph_passr  r$   r   r%   reinplace_fsdp_all_gather  sP    


$r  c                 C  s2   t | tjjjtjjjfrJ t|  dd  S )N   )r   r   Z	_inductor	schedulerZFusedSchedulerNodeGroupedSchedulerNoderQ   rb   )r+   r$   r$   r%   
get_op_idxn  s    r  z1list[torch._inductor.scheduler.BaseSchedulerNode]z4dict[str, torch._inductor.scheduler.SchedulerBuffer]zdict[str, BaseSchedulerNode])r   r   r|   r   c              	     s  ddl m g }tt  }d}d}i }i }i fdd}	| D ]8}
t|
jtjjj	j
drtfdd|
jD rd	}|
}t }t||| ttjjj	j
tjjjj
tjjjj
g t||| fd
dd t|dd d}t|}d}tt|D ]<}|| }t|jtjjjj
r(|d7 }|dkr|} q<q|d | }d }tt|d D ],}t||d  jtjr\|d } qq\|d usJ |	|d | }|	||d  }|||< q@t|
jtjjjj
r@d	}|
}t }t||| t|dd d}d }tt|d D ],}t||d  jtjr|d } qDq|d usRJ |	|d | }|	||d  }|||< q@tdksJ |rt|dksJ |rt|dksJ | D ]B}
|
 v r|
  }
|
|v rq||
 ||
 qd }| D ]N\}}|d urZtt|  }|! D ]}|"t#| |d q<|}qd }| D ]N\}}|d urtt|  }|! D ]}|"t#| |d q|}qn|S )Nr
   )r  Fc                   s2    j | }| D ]}|| < q|| < |S r>   )r  createrb   )Zsnodes_to_groupZ
group_noder+   )r  snode_name_to_final_snoder$   r%   _create_group_node  s
    z:enforce_comm_ordering_for_fsdp.<locals>._create_group_node)r   c                 3  s&   | ]}t  | jtjjjjV  qd S r>   )r   r   r   r   r   r   r   r   )r|   r$   r%   re     s   z1enforce_comm_ordering_for_fsdp.<locals>.<genexpr>Tc                   s&   t | jp"t | jo"| jj v  S r>   )r   ZNopKernelSchedulerNodeZExternKernelSchedulerNoder   Zop_overloadr   )allowed_opsr  r$   r%   r=     s    
z0enforce_comm_ordering_for_fsdp.<locals>.<lambda>)Zcriteria_cbc                 S  s   t | S r>   r  r   r$   r$   r%   r=     r/   r   r   c                 S  s   t | S r>   r!  r   r$   r$   r%   r=     r/   r   )$r   r  r	   r   r   r   r   r   r  r  r   rn   r   r   Zwait_tensorr   Zsplit_with_sizes_copyr   sortedrf   rl   r   r   r   Z_WaitKernelZ	chunk_catrb   r   r   rB   rw   rx   r   ro   r   r   )r   r   r|   Z	new_orderr   Z	ag_existsZ	rs_existsZ$ag_grouped_node_to_wait_grouped_nodeZ$rs_grouped_node_to_wait_grouped_noder  r+   Zag_snodeZag_related_snode_setZag_related_snodesZend_idx_of_current_ag_blockZcopy_out_countrs   Z	cur_snodeZwait_node_idxZag_group_nodeZag_wait_group_nodeZrs_snodeZrs_related_snode_setZrs_related_snodesZrs_group_nodeZrs_wait_group_nodeZprev_ag_waitZwait_group_noder   rc   Zprev_rs_waitr$   )r   r|   r  r  r%   enforce_comm_ordering_for_fsdpy  s    












r#  )A
__future__r   r   rC   loggingr   r   r   collectionsr   Zdataclassesr   typingr   r   r   Ztorch._loggingr   Z torch.multiprocessing.reductionsr   Ztorch.utils._ordered_setr	   r   r   r   Zdependenciesr   Zmemoryr   r   r   utilsr   r   r   r   r   r   r   Zvirtualizedr   	getLoggerrS   r   Z_loggingZgetArtifactLoggerrI   Ztorch._inductor.schedulerr   r   r   r&   r9   rM   r@   r"   r   r[   r2   r   r   r   r  r  r#  r$   r$   r$   r%   <module>   sR   $	
		WY &) Es