/usr/local/lib64/python3.6/site-packages/torch/autograd/__pycache__
NameSizeModeActions
anomaly_mode.cpython-36.pyc51490644editdlrm
forward_ad.cpython-36.pyc42590644editdlrm
function.cpython-36.pyc225870644editdlrm
functional.cpython-36.pyc315430644editdlrm
gradcheck.cpython-36.pyc504520644editdlrm
grad_mode.cpython-36.pyc96020644editdlrm
graph.cpython-36.pyc63160644editdlrm
profiler.cpython-36.pyc257530644editdlrm
profiler_legacy.cpython-36.pyc73220644editdlrm
profiler_util.cpython-36.pyc269410644editdlrm
variable.cpython-36.pyc8150644editdlrm
__init__.cpython-36.pyc110010644editdlrm
Edit: /usr/local/lib64/python3.6/site-packages/torch/autograd/__pycache__/function.cpython-36.pyc (22587B)
3 EgX@s~ddlZddljZddlmZddljjZddlmZddl Z ddl Z ddl m Z ddl mZmZmZGdddeZeZGdd d eZGd d d ejeeZGd d d eZGdddeeejeeZddZddZGdddeZd0ddZddZd1ddZddZ edd d!d"Z!ed#d d$ed%Z"ed&d d'd(d)Z#ed*d d+d"Z$ed,d d-d d$d"Z%Gd.d/d/eZ&dS)2N) _functions)with_metaclass) OrderedDict)AnyListOptionalc@sReZdZejdddZejdddZddZejdd d Ze d d d Z dS) FunctionCtx)tensorscGs ||_dS)aSaves given tensors for a future call to :func:`~Function.backward`. **This should be called at most once, and only from inside the** :func:`forward` **method. This should only be called with input or output tensors** In :func:`backward`, saved tensors can be accessed through the :attr:`saved_tensors` attribute. Before returning them to the user, a check is made to ensure they weren't used in any in-place operation that modified their content. Arguments can also be ``None``. This is a no-op. See :ref:`extending-autograd` for more details on how to use this method. Example:: >>> class Func(Function): >>> @staticmethod >>> def forward(ctx, x: torch.Tensor, y: torch.Tensor, z: int): >>> w = x * y * z >>> out = x * y + y * z + w >>> ctx.save_for_backward(x, y, out) >>> ctx.z = z # z is not a tensor >>> ctx.w = w # w is neither input nor output >>> return out >>> >>> @staticmethod >>> def backward(ctx, grad_out): >>> x, y, out = ctx.saved_tensors >>> z = ctx.z >>> gx = grad_out * (y + y * z) >>> gy = grad_out * (x + z + x * z) >>> gz = None >>> return gx, gy, gz >>> >>> a = torch.tensor(1., requires_grad=True, dtype=torch.double) >>> b = torch.tensor(2., requires_grad=True, dtype=torch.double) >>> c = 4 >>> d = Func.apply(a, b, c) N)to_save)selfr r C/usr/local/lib64/python3.6/site-packages/torch/autograd/function.pysave_for_backwards)zFunctionCtx.save_for_backward)argscGs ||_dS)aMarks given tensors as modified in an in-place operation. **This should be called at most once, only from inside the** :func:`forward` **method, and all arguments should be inputs.** Every tensor that's been modified in-place in a call to :func:`forward` should be given to this function, to ensure correctness of our checks. It doesn't matter whether the function is called before or after modification. Examples:: >>> class Inplace(Function): >>> @staticmethod >>> def forward(ctx, x): >>> x_npy = x.numpy() # x_npy shares storage with x >>> x_npy += 1 >>> ctx.mark_dirty(x) >>> return x >>> >>> @staticmethod >>> @once_differentiable >>> def backward(ctx, grad_output): >>> return grad_output >>> >>> a = torch.tensor(1., requires_grad=True, dtype=torch.double).clone() >>> b = a * a >>> Inplace.apply(a) # This would lead to wrong gradients! >>> # but the engine would not know unless we mark_dirty >>> b.backward() # RuntimeError: one of the variables needed for gradient >>> # computation has been modified by an inplace operation N) dirty_tensors)r rr r r mark_dirty9s!zFunctionCtx.mark_dirtycGstjddS)Nzmark_shared_storage is deprecated. Tensors with shared storages are automatically tracked. Note that calls to `set_()` are not tracked)warningswarn)r pairsr r r mark_shared_storage\szFunctionCtx.mark_shared_storagecGs ||_dS)aMarks outputs as non-differentiable. **This should be called at most once, only from inside the** :func:`forward` **method, and all arguments should be tensor outputs.** This will mark outputs as not requiring gradients, increasing the efficiency of backward computation. You still need to accept a gradient for each output in :meth:`~Function.backward`, but it's always going to be a zero tensor with the same shape as the shape of a corresponding output. This is used e.g. for indices returned from a sort. See example:: >>> class Func(Function): >>> @staticmethod >>> def forward(ctx, x): >>> sorted, idx = x.sort() >>> ctx.mark_non_differentiable(idx) >>> ctx.save_for_backward(x, idx) >>> return sorted, idx >>> >>> @staticmethod >>> @once_differentiable >>> def backward(ctx, g1, g2): # still need to accept g2 >>> x, idx = ctx.saved_tensors >>> grad_input = torch.zeros_like(x) >>> grad_input.index_add_(0, idx, g1) >>> return grad_input N)non_differentiable)r rr r r mark_non_differentiablebsz#FunctionCtx.mark_non_differentiable)valuecCs ||_dS)aSets whether to materialize output grad tensors. Default is ``True``. **This should be called only from inside the** :func:`forward` **method** If ``True``, undefined output grad tensors will be expanded to tensors full of zeros prior to calling the :func:`backward` method. Example:: >>> class SimpleFunc(Function): >>> @staticmethod >>> def forward(ctx, x): >>> return x.clone(), x.clone() >>> >>> @staticmethod >>> @once_differentiable >>> def backward(ctx, g1, g2): >>> return g1 + g2 # No check for None necessary >>> >>> # We modify SimpleFunc to handle non-materialized grad outputs >>> class Func(Function): >>> @staticmethod >>> def forward(ctx, x): >>> ctx.set_materialize_grads(False) >>> ctx.save_for_backward(x) >>> return x.clone(), x.clone() >>> >>> @staticmethod >>> @once_differentiable >>> def backward(ctx, g1, g2): >>> x, = ctx.saved_tensors >>> grad_input = torch.zeros_like(x) >>> if g1 is not None: # We must check for None now >>> grad_input += g1 >>> if g2 is not None: >>> grad_input += g2 >>> return grad_input >>> >>> a = torch.tensor(1., requires_grad=True) >>> b, _ = Func.apply(a) # induces g2 to be undefined N)Zmaterialize_grads)r rr r r set_materialize_gradss*z!FunctionCtx.set_materialize_gradsN) __name__ __module__ __qualname__torchTensorrrrrboolrr r r r r s +# rc@seZdZeddZdS) _HookMixincCs*|dkrt}tj|}|||j<||fS)N)rhooksZRemovableHandleid)Zbackward_hookshookhandler r r _register_hooks   z_HookMixin._register_hookN)rrr staticmethodr%r r r r r sr c@seZdZddZddZdS)BackwardCFunctioncGsL|jj}|jj}|tjk r,|tjk r,td|tjk r:|n|}||f|S)NzsImplementing both 'backward' and 'vjp' for a custom Function is not allowed. You should only implement one of them.) _forward_clsbackwardvjpFunction RuntimeError)r r backward_fnZvjp_fnZuser_fnr r r applys zBackwardCFunction.applycGs|jj|f|S)N)r(jvp)r rr r r apply_jvpszBackwardCFunction.apply_jvpN)rrrr.r0r r r r r's r'cs eZdZdZfddZZS) FunctionMetaaFunction metaclass. This metaclass sets up the following properties: _backward_cls: The Function class corresponding to the differentiated version of this function (which is generated on the fly by this metaclass). cs4t|dtfd|i}||_tt|j|||dS)NZBackwardr()typer'Z _backward_clssuperr1__init__)clsnamebasesattrsr-) __class__r r r4szFunctionMeta.__init__)rrr__doc__r4 __classcell__r r )r9r r1sr1c@sleZdZdZddZddZdZeeeeeddd Z eeeed d d Z e Z eeeed ddZ dS)r+aYBase class to create custom `autograd.Function` To create a custom `autograd.Function`, subclass this class and implement the :meth:`forward` and :meth`backward` static methods. Then, to use your custom op in the forward pass, call the class method ``apply``. Do not call :meth:`forward` directly. To ensure correctness and best performance, make sure you are calling the correct methods on ``ctx`` and validating your backward function using :func:`torch.autograd.gradcheck`. See :ref:`extending-autograd` for more details on how to use this class. Examples:: >>> class Exp(Function): >>> @staticmethod >>> def forward(ctx, i): >>> result = i.exp() >>> ctx.save_for_backward(result) >>> return result >>> >>> @staticmethod >>> def backward(ctx, grad_output): >>> result, = ctx.saved_tensors >>> return grad_output * result >>> >>> # Use it by calling the apply method: >>> output = Exp.apply(input) cOs|j}tj|dtdS)Nz should not be instantiated. Methods on autograd functionsare all static, so you should invoke them on the class itself. Instantiating an autograd function will raise an error in a future version of PyTorch.)r9rrDeprecationWarning)r rkwargsr5r r r r4s zFunction.__init__cOs tddS)NzLegacy autograd function with non-static forward method is deprecated. Please use new-style autograd function with static forward method. (Example: https://pytorch.org/docs/stable/autograd.html#torch.autograd.Function))r,)r rr=r r r __call__szFunction.__call__F)ctxrr=returncOs tddS)aWPerforms the operation. This function is to be overridden by all subclasses. It must accept a context ctx as the first argument, followed by any number of arguments (tensors or other types). The context can be used to store arbitrary data that can be then retrieved during the backward pass. zEYou must implement the forward function for custom autograd.Function.N)NotImplementedError)r?rr=r r r forward s zFunction.forward)r? grad_outputsr@cGs tddS)aDefines a formula for differentiating the operation with backward mode automatic differentiation. This function is to be overridden by all subclasses. It must accept a context :attr:`ctx` as the first argument, followed by as many outputs as the :func:`forward` returned (None will be passed in for non tensor outputs of the forward function), and it should return as many tensors, as there were inputs to :func:`forward`. Each argument is the gradient w.r.t the given output, and each returned value should be the gradient w.r.t. the corresponding input. If an input is not a Tensor or is a Tensor not requiring grads, you can just pass None as a gradient for that input. The context can be used to retrieve tensors saved during the forward pass. It also has an attribute :attr:`ctx.needs_input_grad` as a tuple of booleans representing whether each input needs gradient. E.g., :func:`backward` will have ``ctx.needs_input_grad[0] = True`` if the first input to :func:`forward` needs gradient computated w.r.t. the output. zwYou must implement either the backward or vjp method for your custom autograd.Function to use it with backward mode AD.N)rA)r?rCr r r r)szFunction.backward)r? grad_inputsr@cGs tddS)aDefines a formula for differentiating the operation with forward mode automatic differentiation. This function is to be overridden by all subclasses. It must accept a context :attr:`ctx` as the first argument, followed by as many inputs as the :func:`forward` got (None will be passed in for non tensor inputs of the forward function), and it should return as many tensors as there were outputs to :func:`forward`. Each argument is the gradient w.r.t the given input, and each returned value should be the gradient w.r.t. the corresponding output. If an output is not a Tensor or the function is not differentiable with respect to that output, you can just pass None as a gradient for that input. You can use the :attr:`ctx` object to pass any value from the forward to this functions. z`You must implement the jvp function for custom autograd.Function to use it with forward mode AD.N)rA)r?rDr r r r/:sz Function.jvpN) rrrr:r4r> is_traceabler&rrBr)r*r/r r r r r+sr+cstjfdd}|S)Nc stj|f|}WdQRXtjs.|Stdd|D}|sH|St|tsX|f}tjdt|}dd|fdd|DS)Ncss |]}t|tjo|jVqdS)N) isinstancerr requires_grad).0argr r r bsz7once_differentiable..wrapper..sRtrying to differentiate twice a function that was marked with @once_differentiablecSs|dk r|j}d|_|S)NT)detachrG)varr r r fake_requires_gradqsz@once_differentiable..wrapper..fake_requires_gradcsg|] }|qSr r )rHv)rMr r wsz8once_differentiable..wrapper..) rZno_gradZis_grad_enabledanyrFtuplerZ DelayedErrorlen)r?routputsrGZerr_fn)fn)rMr wrapperQs     z$once_differentiable..wrapper) functoolswraps)rTrUr )rTr once_differentiableOs'rXcCs d|_|S)aMarks Function as traceable for the JIT. Traceable functions have additional restrictions - they can't pass any data-dependent values to backward (e.g. Prod passes the output, which makes it non-traceable), and their backward should be implemented entirely in terms of operations on autograd Tensors in all cases. DON'T USE THIS DECORATOR. IT IS FOR INTERNAL USE ONLY AND SHOULD BE HANDLED WITH CARE (or can give incorrect results otherwise). T)rE)Zfn_clsr r r traceable{s rYcseZdZdfdd ZZS)InplaceFunctionFcstt|j||_dS)N)r3rZr4inplace)r r[)r9r r r4szInplaceFunction.__init__)F)rrrr4r;r r )r9r rZsrZcsfddS)NcsrSdkrdStttfr^fddD}tdrRt|St|Sttr|fddDStdtjrddnd dS) Nc3s|]}|VqdS)Nr )rHx)_mapr r rJsz,_nested_map.._map.._fieldscsi|]}||qSr r )rHr\)r]objr r sz-_nested_map.._map..zAAuto nesting doesn't know how to process an input object of type z. Accepted types: z, or lists/tuples of them) rFlistrQhasattrr2dict ValueErrorrtypename)r_Zmapped)r] condition condition_msgrT)r_r r]s     z_nested_map.._mapr )rgrTrhr )r]rgrhrTr _nested_mapsricCst|dr|jS|S)N _jit_unwrap)rcrj)r_r r r _jit_unwrap_structureds rkFcsfddS)Nc3sdk r|}|r |Vn|dkr,dSt|ttfrbx|D]}x|D] }|VqNWq@Wnht|trx\|jD]}x|D] }|VqWqvWn2r|Vn&tdtj|rddnddS)NzAAuto nesting doesn't know how to process an input object of type z. Accepted types: z, or lists/tuples of themra)rFrbrQrdvaluesrerrf)r_orL)_iter allow_unknownrgrh conversionr r rns&   z_iter_filter.._iterr )rgrorhrpr )rnrorgrhrpr _iter_filtersrqcsfdd||dS)Ncsg}t|dr|j|St|ttfs:|d|ddfSx8|D]0}|dkrX|j|q@||\}}|j|q@Wt|||fS)N _jit_wrapr)rcrrrFrbrQappendr2)inputprotoreseZres_e)unflatten_helperr r rys    z$_unflatten..unflatten_helperrr )rurvr )ryr _unflattens rzcCs|dkpt|tjjS)N)rFr_CValue)rmr r r sr}zjit's Values or None)rhcCs t|tjS)N)rFrr)r\r r r r}sZTensors)rhrpcCs t|tjS)N)rFrr)r\r r r r}sTzTensors (permissive))rorhcCs|dkpt|tjS)N)rFrr)rmr r r r}szTensors or NonecCs t|tjS)N)rFrr)r\r r r r}scCs|jS)N)data)rmr r r r}scseZdZfddZfddZeedddZeZeedd d Zed dd d Z e fddZ eed dddZ eed dddZ ed dddZed dddZZS)NestedIOFunctioncs8||_tt|}tt|j|}|j}t||j}|S)N) _nested_inputrQ _iter_tensorsr3r _do_forward_nested_outputrz)r ruZ flat_inputZ flat_outputZ nested_outputnested_tensors)r9r r rs   zNestedIOFunction._do_forwardcs(||_tt|j||}|s$|`|`|S)N)retain_variablesr3r _do_backwardr_to_save_nested)r gradientsrresult)r9r r rs zNestedIOFunction._do_backward)rr@cGs"t||j}|j|}tt|S)N)rzrbackward_extendedrQ_iter_None_tensors)r rZnested_gradientsrr r r r)s  zNestedIOFunction.backward)rr@cGs*t|j}|j|}|`||_tt|S)N)_map_tensor_datarforward_extendedrrQr)r rrrr r r rB s   zNestedIOFunction.forwardNcGstt||_||_dS)N)rQrr r)r rr r r rsz"NestedIOFunction.save_for_backwardcstt|j}t||jS)N)r3r saved_tensorsrzr)r Z flat_tensors)r9r r rs zNestedIOFunction.saved_tensors)rr=r@cOstt||f|_dS)N)rQrr)r rr=r r r rszNestedIOFunction.mark_dirtycOstt||f|_dS)N)rQrr)r rr=r r r rsz(NestedIOFunction.mark_non_differentiable)rur@cGstdS)N)rA)r rur r r rsz!NestedIOFunction.forward_extended) grad_outputr@cGstdS)N)rA)r rr r r r"sz"NestedIOFunction.backward_extended)rrrrrrr)r>rBrpropertyrrrrrr;r r )r9r rs  r)N)FNN)'rZtorch._Cr{rZtorch.utils.hooksutilsr!Z torch._sixrrVr collectionsrtypingrrrobjectrZ_ContextMethodMixinr Z _FunctionBaser'r2r1r+rXrYrZrirkrqrzZ_iter_jit_valuesrZ_iter_tensors_permissiverrrr r r r sF     $ q,