U
    yh                     @   sH   d dl mZmZ d dlZddlmZ d
eee  dddZdd	 ZdS )    )ListOptionalN   )map_debug_info)outputs_with_grads_idxsc              
      s   |dk	r,fdd|D fdd|D zhg g  fdd   t jjd g }|D ](}t|t jr||j qh|d qhW nP tk
r } z2dt d	t d
t| d}t	||W 5 d}~X Y nX |S )a  
    This is a helper function to:
    1. compute the gradients for the stage inputs, and
    2. accumulate gradients for the stage module's parameters.

    Given the input value(s) and the corresponding gradient for the output
    value(s), compute and accumulate gradients for all parameter values (leaves
    in the autograd trace) as well as return a list of the gradients for the
    input values
    Nc                    s   g | ]} | qS  r   .0i)stage_outputr   X/var/www/html/venv/lib/python3.8/site-packages/torch/distributed/pipelining/_backward.py
<listcomp>   s     z"stage_backward.<locals>.<listcomp>c                    s   g | ]} | qS r   r   r   )output_gradsr   r   r      s     c                    s@  t | tjr\| js | jd kr d S t |tjtd fsFtdt| |  | nt | tt	fr|d krvd S t |tt	fstdt|  dt| t
| t
|kstt| |D ]\}} || qnht | tr<|d krd S t |tstt|  t| kst|  D ]} | | ||  q n d S )Nz)Expected Tensor or None gradient but got z!grad_value expected to have type z	 but got )
isinstancetorchTensorZrequires_gradZgrad_fntypeAssertionErrorappendtuplelistlenzipdictsetkeys)Z
output_valZgrad_valovgvk)extract_tensors_with_gradsoutput_grad_tensorsstage_output_tensorsr   r   r   %   s>     
 z2stage_backward.<locals>.extract_tensors_with_grads)Zgrad_tensorsz=
        Failed to run stage backward:
        Stage output: z
        Output gradient: z
        Input: z	
        )
r   ZautogradZbackwardr   r   r   Zgrad	Exceptionr   RuntimeError)r   r   Zinput_valuesr   Zgrad_inputsvaleZexc_msgr   )r   r    r   r   r!   r   stage_backward
   s8    
 r&   c                 C   s(   | dkr|S |dkr| S t | |S dS )z]
    Coalesce two values, even if one of them is null, returning the non-null
    value.
    N)r   add)lhsrhsr   r   r   _null_coalesce_accumulatel   s
    r*   )N)	typingr   r   r   _debugr   intr&   r*   r   r   r   r   <module>   s    
b