
    /j0                         d dl Z d dlmZ d dlZd dlmc mZ d Zd Z	d Z
d Zd Ze j        d             Zd	 Zd
 Zd Zd Zd ZdS )    N)
namedtuplec                 4     t                      fd}|S )Nc                                          d          r"                    d          j        } || i |S                      d          s                     d          rY                     d          rdnd}|dk    rdnd}                    |          j        }t	          d| d d| d| d	           | i |S )	Nautogradsave_for_backwardbackwardzWe found a 'z' registration for  at z but were unable to find a 'z' registration. To use the CustomOp API to register a backward formula, please provide us both a backward function and a 'save for backward' function via `impl_backward` and `impl_save_for_backward` respectively.)	_has_impl	_get_implfunclocationRuntimeError)argskwargskernelmissingfoundlocautograd_fallback	custom_ops         ^/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/torch/_custom_op/autograd.pyinnerz*autograd_kernel_indirection.<locals>.inner   s&   z** 	+((449F64*6***
 233 	y7J7J:7V7V 	'0':'::'F'FV##J  ,3j+@+@''jE%%e,,5C:u : : : :: :4;: : :   ! $1&111    )autograd_not_implemented)r   r   r   s   ` @r   autograd_kernel_indirectionr      s7    0;;2 2 2 2 2 20 Lr   c                       fd}|S )Nc                      t          j                    r't          j        d | |f          rt	          d          t           j                                        5   | i |cd d d            S # 1 swxY w Y   d S )Nc                 D    t          | t          j                  o| j        S N)
isinstancetorchTensorrequires_gradxs    r   <lambda>z:autograd_not_implemented.<locals>.kernel.<locals>.<lambda>6   s    jEL11Eao r   z.Autograd has not been implemented for operator)r!   is_grad_enabledpytreetree_anyr   _C_AutoDispatchBelowAutograd)r   r   r   s     r   r   z(autograd_not_implemented.<locals>.kernel4   s     "" 	QvEEf~(
 (
 	Q OPPPX0022 	. 	.9d-f--	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	.s   A//A36A3 )r   r   s   ` r   r   r   3   s#    . . . . . Mr   c                 ^   |'t          |t                    s|f}n|}t          |          t          |          k    r/t          dt          |           dt          |                     g }t	          t          ||                    D ]\  }\  }}t          |t          j                  r|s|                    |           :t          |t                    r|s|
                    |           g|r&t          d| d| dt          |           d          |r | j        |  d S d S d S )Nz output_differentiability length z != output length zWith output_differentiability=z	. At idx z , we received an object of type za that is not a Tensor, so it cannot have be marked as differentiable in output_differentiability.)r    tuplelenAssertionError	enumeratezipr!   r"   appendlistextendr   typemark_non_differentiable)ctxoutputoutput_differentiabilitytuple_outputnon_differentiable_tensorsidxdifferentiableouts           r   r7   r7   ?   s     +&%(( 	""9LL!L'((C,=,=== 837O3P3P 8 8$'$5$58 8   &("*3(,77+
 +
 	 	&C&.# #u|,, % ;.55c:::#t$$ % ;.55c::: "15M 1 1!1 1CG991 1 1   & 	E'C')CDDDD= ,+:	E 	Er   c                 &      fd}|S )Nc                     t          j        |           \  }d 
fd}	fd}t          	j        dz   ||          } |j        | }t          d          t          j        t          |                    S )Nc                    |                      d           t          j        t          |                    }t          j                                        5   | }d d d            n# 1 swxY w Y   t          t          j        t          |                    }t          |          } ||          }t          | ||f           t          | |
           t          j        |          \  }	t          |          S )NT)set_materialize_gradsr(   tree_unflattenr4   r!   r*   r+   namedtuple_argstree_mapr6   save_pytree_for_backwardr7   tree_flattenr.   )r8   	flat_argsr   r9   	args_infosave_for_backward_fn_inputsto_saveflat_outputop_overloadout_specr:   save_for_backward_fnschemaspecs           r   forwardz9construct_autograd_kernel.<locals>.apply.<locals>.forwardr   s1   %%d+++(i$??D4466 , ,$d+, , , , , , , , , , , , , , , (d0K0KLLI*9&$*G*G'**+FOOG$S7I*>???#C1IJJJ %+$7$?$?!K%%%s   A))A-0A-c                 0   	t          d          t          j        t          |          	          }t	          |           \  }}t                      }t          |t                    s|f} ||g|R  }t          ||           t          ||          S )Nout_spec is unexpectedly None)
r0   r(   rD   r4   unpack_savedobjectr    r.   validate_grad_inputs_dictgrad_inputs_dict_to_flat_tuple)
r8   flat_grad_outputgradssavedrJ   	inner_ctxgrad_inputs_dictbackward_fnr   rO   s
          r   r   z:construct_autograd_kernel.<locals>.apply.<locals>.backward   s    $%DEEE)$/?*@*@(KKE+C00E9 IeU++ !*{9eDeDDD &&6	9MMM12BINNNr   	_customoprU   )r(   rH   gen_autograd_function_opnameapplyr0   rD   r4   )r   rI   rS   r   generated_clsrM   rO   rR   r_   r   rN   r:   rP   rQ   s         @@r   rc   z(construct_autograd_kernel.<locals>.applyn   s     -d33	4	& 	& 	& 	& 	& 	& 	& 	& 	& 	&&	O 	O 	O 	O 	O 	O 	O" .+Wh
 
 *m)95 !@AAA$T+%6%6AAAr   r,   )rQ   r:   r   rN   rP   r_   rc   s   `````` r   construct_autograd_kernelre   f   sL    /B /B /B /B /B /B /B /B /B /Bb Lr   c                     t          | t          j        j        ft	          |          t	          |          d          }|S )N)rS   r   )r6   r!   r   Functionstaticmethod)namerS   r   rd   s       r   ra   ra      sG    		 "#G,,$X..	
 	
 M r   c                     d | j         j        D             }t          | j                  dz   }t	          ||          }|S )Nc                     g | ]	}|j         
S r,   )ri   .0args     r   
<listcomp>z'namedtuple_args_cls.<locals>.<listcomp>   s    ===Csx===r   _args)	argumentsflat_allstrri   r   )rQ   attribsri   	tuple_clss       r   namedtuple_args_clsrv      sD    ==6#3#<===Gv{g%D4))Ir   c                     t          |t                    st          dt          |                     t	          |           } || S )Nzexpected tuple, got )r    r.   r0   r6   rv   )rQ   r   ru   s      r   rE   rE      sL    dE"" B@DJJ@@AAA#F++I9dr   c                    fd}t          | t                    s |dt          |                       d j        j        j        D             }|                                 }||k    r |d| d| d           |                                 D ]\  }}t          ||          }t          |t                    r t          |t          t          f          s |d| dt          |           d	           t          |          t          |          k    r. |d| d
t          |           dt          |                      t          t          ||                    D ]w\  }	\  }
}|
t          |
t          j                  s! |d| dt          |
           d|	            t!          |t          j                  s |d| d|	 d|	 d|            xL|Pt          |t          j                  s |dt          |           d| d           t!          |t          j                  s |d| d| d| d           d S )Nc                 h                         d          }t          d d|j         d|            )Nr   z%In the backward function defined for r	   z using the CustomOp API, )r   r   r   )whatr   
forward_ops     r   errorz(validate_grad_inputs_dict.<locals>.error   s]    ''
33BJ B B B B;?B B
 
 	
r   zBexpected the output of the backward function to be a dict but got c                 N    h | ]"}|j                                         |j        #S r,   )r6   is_tensor_likeri   rl   s     r   	<setcomp>z,validate_grad_inputs_dict.<locals>.<setcomp>   s>       8""$$  r   z3expected the returned grad_input dict to have keys z	 but got z. The backward function must return a gradient (can be None) for each arg to the CustomOp that may be a Tensor or Sequence[Tensor]. Args declared to be non-Tensor-like types should not appear in the grad_input dictzfor input 'zR' expected the grad_input dict to hold a list of gradients but got object of type .z1' expected the grad_input dict to hold a list of z gradients but got z\' expected the grad_input dict to hold a list of None or Tensor gradients but got object of z
 at index z(', got a Tensor as the gradient for the z(-th value but expected None because the z(-th value was not a Tensor (it was type zgot object of type z as the gradient for input 'z:', but expected the gradient to be either None or a Tensorz(got a Tensor as the gradient for input 'z3' but expected None as the gradient because input 'z ' was not a Tensor (it was type z).)r    dictr6   _schemarq   rr   keysitemsgetattrr4   r.   r/   r1   r2   r!   r"   
issubclass)r^   r{   rJ   r|   expected_keysactual_keysri   gradarg_infor=   ginfos    `          r   rX   rX      s   
 
 
 
 
 &-- 
,()), ,	
 	
 	

 %/8  M
 #''))K##&& &'2& & &	
 	
 	
 ',,.. / /
d9d++h%% 	dUDM22 %$ % %Dzz% % %  
 4yyCMM))#$ # #&)(mm# #4yy# #  
 #,Ch,?,?"@"@  Ya9!!U\22 E>d > >%)!WW> >8;> >  
 "$55 E+d + +#&+ +"+ + !)+ +   <$-- 	EKd4jj K KK K K  
 (EL11 	E>4 > >@D> >19> > >  W/ /r   c                 2   g }|                                                                 D ]N\  }}|| vr*|                    t          j        d |                     3|                    | |                    Ot          t          j        |                    S )Nc                     d S r   r,   r$   s    r   r&   z0grad_inputs_dict_to_flat_tuple.<locals>.<lambda>  s    D r   )_asdictr   r3   r(   rF   r.   tree_leaves)r^   rJ   resultri   r   s        r   rY   rY     s    F#++--3355 . .h'''MM&/..(CCDDD&t,----#F++,,,r   c                 @   t          j        |          \  }}t          |          }d t          |          D             }d t          |          D             }d |D             }d |D             }|| _        || _         | j        |  || _        || _        || _	        d S )Nc                 L    g | ]!\  }}t          |t          j                  |"S r,   r    r!   r"   rm   r=   things      r   ro   z,save_pytree_for_backward.<locals>.<listcomp>  s=       Uz%7V7V  r   c                 L    g | ]!\  }}t          |t          j                  |"S r,   r   r   s      r   ro   z,save_pytree_for_backward.<locals>.<listcomp>"  s>       C%..  r   c                 F    g | ]}t          |t          j                  |S r,   r   rm   r   s     r   ro   z,save_pytree_for_backward.<locals>.<listcomp>'  s)    PPP
5%,0O0OPuPPPr   c                 F    g | ]}t          |t          j                  |S r,   r   r   s     r   ro   z,save_pytree_for_backward.<locals>.<listcomp>(  s)    XXXU
5%,8W8WX5XXXr   )
r(   rH   r/   r1   rR   num_eltsr   tensor_idxssaved_non_tensorsnon_tensor_idxs)	r8   stuff
flat_stuffrR   r   r   r   tensorsnon_tensorss	            r   rG   rG     s    *511J:H '
33  K #J//  O
 QP*PPPGXXjXXXKCHCLC7##!CO'C)Cr   c                     d g| j         z  }t          | j        | j                  D ]
\  }}|||<   t          | j        | j                  D ]
\  }}|||<   t          j        || j                  }|S r   )	r   r2   saved_tensorsr   r   r   r(   rD   rR   )r8   r   tensorr=   
non_tensorr   s         r   rV   rV   3  s    #,&J3,co>> ! ! 
3s4c6IJJ % %
C$
3!*ch77ELr   )	functoolscollectionsr   r!   torch.utils._pytreeutils_pytreer(   r   r   r7   re   ra   	lru_cacherv   rE   rX   rY   rG   rV   r,   r   r   <module>r      s       " " " " " "  $ $ $ $ $ $ $ $ $  @	 	 	$E $E $EN9 9 9x	 	 	     M M M`- - -* * *.    r   