a
    dB                     @   s   d dl Z d dlZd dlmZmZ d dlmZmZm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mZ e eZdd	 ZeG d
d dZee dddZG dd dZdS )    N)	dataclassfield)AnyListOptional)fx)GraphCompileReason)deepcopy_to_fake_tensorfake_mode_from_tensors)Nodec                 C   sp   t | rd| j dS t| tr>dddd | D  dS t| trdddd	d | D  dS t| S d S )
NzT[]ztuple(, c                 S   s   g | ]}t |qS  args_str.0xr   r   k/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torch/_dynamo/backends/distributed.py
<listcomp>       zargs_str.<locals>.<listcomp>)zlist(c                 S   s   g | ]}t |qS r   r   r   r   r   r   r      r   )torchZ	is_tensorshape
isinstancetuplejoinliststr)argsr   r   r   r      s    


r   c                   @   sZ   e Zd ZU dZeed< eedZe	e
 ed< eedZe	ej ed< eedZe	ed< dS )Bucketr   size)default_factoryparamsnodes	param_idsN)__name__
__module____qualname__r!   int__annotations__r   r   r#   r   r   r$   r   r   r%   r   r   r   r   r       s   
r    )bucketsc                 C   s   d}g }t t| D ]R\}}t|jdkr|||j|jd f |jdd  D ]}|d d |f qPqz(ddlm} td|||dd  W n t	y   td Y n0 d S )	N)IndexzSize (b)zParam Namesr      )tabulatez!
DDPOptimizer bucket assignments
Zsimple_grid)headersZtablefmtzGPlease `pip install tabulate` in order to pretty-print ddp bucket sizes)
	enumeratereversedlenr#   appendr!   r.   loginfoImportError)r+   r/   rowsidxZbucketparamr.   r   r   r   pretty_print_buckets%   s$    r:   c                   @   sF   e Zd ZdZdeee dddZdd Zej	e
ej dd	d
ZdS )DDPOptimizera  Note [DDPOptimizer]
    DDPOptimizer applies when dynamo compiles models wrapped in DistributedDataParallel (DDP),
    breaking the dynamo graph into chunks to compile separately, with the breaks aligning to
    the boundaries of gradient-allreduce buckets chosen by DDP.

    Background/Motivation
     - DDP uses allreduce collectives to synchronize partial gradients computed on different workers
     - DDP groups gradient allreduces into 'buckets' to optimize communication efficiency of all-reduce
     - Parameters grouped into buckets are assumed to be adjacent in time, so they become ready
       at around the same time during backward and thus can share the same allreduce efficently
     - Allreduces must overlap with backward compute for optimal training performance
     - DDP schedules allreduces using 'hooks' fired from the c++ autograd engine in pytorch, which
       operates when individual grads become 'ready'
     - Dynamo+AOTAutograd produces a single fused graph that runs 'atomically' from the perspective of the
       autograd engine, such that all gradients become 'ready' at the same time.  Hooks fire after the whole
       fused backward function executes, preventing any overlap of compute and communication

    Algorithm
     - DDPOptimizer starts off with an FX graph traced by dynamo which represents forward.  It can traverse
       this graph in reverse order to determine the true order that gradients will become ready during backward.
     - Parameter sizes are counted in reverse order, up to a bucket size limit, at which point a new bucket is started
       and a graph break introduced
     - Each of the subgraphs is compiled by the compiler provided to dynamo by the user, and then fused back together
       into an outer module that is returned to the user

    Notes
     - It would be better to enforce (by adding an API to DDP) that the bucket splits chosen here are used by DDP,
       and that DDP does not need to detect or optimize bucket order by observing execution at runtime, as it does
       in eager.
     - If Dynamo can't capture a whole graph for the portion of the model wrapped by DDP, this algorithm will currently
       produce splits that do not necessarily align with the buckets used by DDP.  This should result in performance
       degradation approaching the baseline case where graph-splits are not used, but not worse.
     - If the backend compiler fails to compile a single subgraph, it will execute eagerly despite the rest of the
       subgraphs being compiled
     - DDP has a 'parameters_and_buffers_to_ignore' field, which DDPOptimizer attempts to honor by reading markers
       left by DDP on individual parameters.  In cases where other transformations, such as reparameterization, are
       also used, the ignore markers could be lost.  If DDPOptimizer fails to ignore a parameter ignored by DDP,
       it is not catastrophic but could impact performance by choosing sub-optimal bucket splits.
     - DDPOptimizer always ignores all buffers, regardless of their ignore flag, since buffers do not require gradients,
       and therefore aren't allreduced by DDP.  (They are broadcast during forward, but this is not covered by
       DDPOptimizer)

    Debugging
     - Generally, it is easiest to debug DDPOptimizer in a single process program, using pdb.
     - In many cases, the log messages are helpful (they show bucket size assignments)-
       just configure torch._dynamo.config.log_level to info or debug.
     - See `benchmarks/dynamo/distributed.py` for a simple harness that will run a toy model or a torchbench model
       in a single process (or with torchrun, in multiple processes)

    Args:
        bucket_bytes_cap (int): Controls the size of buckets, in bytes, used to determine graphbreaks.  Should be
            set to match the equivalent parameter on the original DDP module.

        backend_compile_fn (callable): A dynamo compiler function, to be invoked to compile each subgraph.

        first_bucket_cap (int): Controls the size of the first bucket.  Should match DDP's first bucket cap.  DDP
            special-cases the first bucket size since it is sometimes optimal to start a small allreduce early.

    N)bucket_bytes_capfirst_bucket_capc                 C   sP   |d ur|| _ ntj r&tjj| _ n|| _ || _| j | jksFJ d|| _d S )NzQFirst bucket should be smaller/equal to other buckets to get comms warmed up ASAP)r=   r   ZdistributedZis_availableZ_DEFAULT_FIRST_BUCKET_BYTESr<   backend_compile_fn)selfr<   r>   r=   r   r   r   __init__w   s    

zDDPOptimizer.__init__c                 C   s   t |do|jS )N_ddp_ignored)hasattrrA   )r?   Z	parameterr   r   r   _ignore_parameter   s    zDDPOptimizer._ignore_parameter)gmexample_inputsc                    s&  t |  du rtjj  t g}t|jjD ]V}|j	dv rBq0|d j
| jksnt|dkr||d j
| jkr||dt  |j	dkr||j}| D ]l\}}||}|jr| |s|d  j
|  7  _
|d j|j d|  |d jt| qnl|j	dkrxt||j}	|	jrx| |	sx|d  j
|	  7  _
|d j|j |d jt|	 |d j| q0t|dkr|d j
dkr|d j|d j t|d jdksJ d|d= || _td	| j d
 t | t|dkr| !||S i t"|D ] \}
}|jD ]}|
|< q6q(t#j$j%%|dfdd}d|j dd|j d }|& D ]6\}}d|vrt|r|d| d|j d7 }q|d7 }t'| G  fdddtj#j(j)}||| j!}|j*|  |+  t'dt,|j d  |S )a1  
        Implements graph splitting, first determining a set of of buckets by counting
        parameter sizes in reverse graph order, then invoking the user/backend compiler
        to compile each subgraph. Finally, stiches compiled graphs into one graphmodule
        and returns its callable.
        N)outputplaceholderr   r-   call_module_Zget_attrz#Params should be empty if size is 0zDDPOptimizer used bucket cap z$ and produced the following buckets:c                    s    |  S Nr   )node)partition_mapr   r   <lambda>   r   z)DDPOptimizer.compile_fn.<locals>.<lambda>z
---orig graph---

z
---split graph---
.
---
 graph---
z
---------------
c                       s8   e Zd Z fddZdd ZeedfddZ  ZS )z/DDPOptimizer.compile_fn.<locals>.SubmodCompilerc                    s   t  | || _d S rJ   )superr@   compiler)r?   modulerS   	__class__r   r   r@      s    z8DDPOptimizer.compile_fn.<locals>.SubmodCompiler.__init__c                 S   s   t |dksJ dG dd dtjj}d}|jjD ],}|jdkr4t|jd t	s4d}|jf|_q4|
  tdttdtg|_|| |||}|S )	z
                Compile the submodule,
                using a wrapper to make sure its output is always a tuple,
                which is required by AotAutograd based compilers
                r   z%We assume only args for these modulesc                       s$   e Zd Z fddZdd Z  ZS )zUDDPOptimizer.compile_fn.<locals>.SubmodCompiler.compile_submod.<locals>.WrapperModulec                    s   t    || _|| _d S rJ   )rR   r@   submodunwrap_singleton_tuple)r?   rW   rX   rU   r   r   r@      s    
z^DDPOptimizer.compile_fn.<locals>.SubmodCompiler.compile_submod.<locals>.WrapperModule.__init__c                 W   s*   | j | }| jr&t|ttfr&|d S |S )Nr   )rW   rX   r   r   r   )r?   r   r   r   r   r   forward   s    
z]DDPOptimizer.compile_fn.<locals>.SubmodCompiler.compile_submod.<locals>.WrapperModule.forward)r&   r'   r(   r@   rY   __classcell__r   r   rU   r   WrapperModule   s   r[   FrF   Tz{DDPOptimizer intentional graph-break (See Note [DDPOptimizer]). Set `torch._dynamo.config.optimize_ddp = False` to disable.)r2   r   nnModulegraphr$   opr   r   r   	recompiler   	tracebackFrameSummary__file__r;   Zcompile_subgraph_reasonrS   )r?   Z	input_modr   kwargsr[   rX   Zsnwrapperr   r   r   compile_submod   s&    

z>DDPOptimizer.compile_fn.<locals>.SubmodCompiler.compile_submod)nreturnc           	   
      s  |  | | |\}}g } s(J |D ]:}t|tjr\t|tjjs\| | q,|| q,t	
d|j d|j dt|  t|tsJ t|tsJ |jdkrn| |j} rt| }n|}t	
d|j dt|j  | |||}| j|j d|j |_| j|j|  , ||i |W  d    W  d    S 1 sb0    Y  n$t| |j|j||W  d    S W d    n1 s0    Y  d S )Nz	run_node r   z
 got args rH   rP   rQ   Z	compiled_)Z_set_current_nodeZfetch_args_kwargs_from_envr   r   Tensor_subclassesZ
FakeTensorr3   Zfrom_tensorr4   debugr_   targetr   r   dictZ
fetch_attrr	   r   r^   rf   rT   Zdelete_submoduleZadd_submodulegetattr)	r?   rg   r   rd   new_argsargZreal_modZcurr_submodZcompiled_submod_real	fake_moder   r   run_node*  s<    $>z8DDPOptimizer.compile_fn.<locals>.SubmodCompiler.run_node)	r&   r'   r(   r@   rf   r   r   rs   rZ   r   rq   rU   r   SubmodCompiler   s   Brt   z
---final graph---
)-r
   r   rj   Zfake_tensorZFakeTensorModer    r1   r^   r$   r_   r!   r<   r2   r=   insertZget_submodulerl   Znamed_parametersZget_parameterZrequires_gradrC   Zuntyped_storagenbytesr#   r3   r%   idrn   extendr+   r4   r5   r:   r>   r0   r   ZpassesZsplit_moduleZnamed_modulesrk   interpreterZInterpreterrunr`   r   )r?   rD   rE   r+   rK   rl   namepr9   Zmaybe_paramr8   bZsplit_gmZ	debug_strrT   rt   Zsubmod_compilerr   )rr   rL   r   
compile_fn   s    




y
zDDPOptimizer.compile_fn)N)r&   r'   r(   __doc__r)   r   r@   rC   r   ZGraphModuler   r   ri   r~   r   r   r   r   r;   :   s   @ r;   )loggingra   Zdataclassesr   r   typingr   r   r   r   r   Ztorch._dynamo.output_graphr   Ztorch._dynamo.utilsr	   r
   Ztorch.fx.noder   	getLoggerr&   r4   r   r    r:   r;   r   r   r   r   <module>   s   
	