/usr/local/lib64/python3.6/site-packages/torch/nn/modules/__pycache__
NameSizeModeActions
activation.cpython-36.pyc476350644editdlrm
adaptive.cpython-36.pyc97250644editdlrm
batchnorm.cpython-36.pyc310390644editdlrm
channelshuffle.cpython-36.pyc19010644editdlrm
container.cpython-36.pyc279700644editdlrm
conv.cpython-36.pyc577890644editdlrm
distance.cpython-36.pyc36840644editdlrm
dropout.cpython-36.pyc103100644editdlrm
flatten.cpython-36.pyc58130644editdlrm
fold.cpython-36.pyc128070644editdlrm
instancenorm.cpython-36.pyc188080644editdlrm
lazy.cpython-36.pyc116900644editdlrm
linear.cpython-36.pyc101880644editdlrm
loss.cpython-36.pyc914650644editdlrm
module.cpython-36.pyc665300644editdlrm
normalization.cpython-36.pyc113600644editdlrm
padding.cpython-36.pyc222170644editdlrm
pixelshuffle.cpython-36.pyc43980644editdlrm
pooling.cpython-36.pyc532030644editdlrm
rnn.cpython-36.pyc446530644editdlrm
sparse.cpython-36.pyc209560644editdlrm
transformer.cpython-36.pyc207370644editdlrm
upsampling.cpython-36.pyc107800644editdlrm
utils.cpython-36.pyc25280644editdlrm
_functions.cpython-36.pyc54410644editdlrm
__init__.cpython-36.pyc52360644editdlrm
Edit: /usr/local/lib64/python3.6/site-packages/torch/nn/modules/__pycache__/module.cpython-36.pyc (66530B)
3 Eg<2@sUddlmZmZddlZddlZddlZddlZddlmZddl j j Z ddlm Z m Z mZddlmZmZmZmZmZmZmZmZmZmZmZmZddlmZeee d fe fZed d d ZGd ddedddgZ ddZ!eZ"ee#ef"da$ee%$eZ&ee#ef&eZ'ee#ef'dZ(ed"edddZ)ed#edddZ*ed eegede ffedddZ+ed eegede ffedddZ,edddd Z-Gd!d d Z.dS)$) OrderedDict namedtupleN) Parameter)Tensordevicedtype) UnionTupleAnyCallableIteratorSetOptionaloverloadTypeVarMappingDictList)RemovableHandle.TModule)boundcs eZdZfddZeZZS)_IncompatibleKeyscs"|j r|j rdStt|jS)Nz) missing_keysunexpected_keyssuperr__repr__)self) __class__C/usr/local/lib64/python3.6/site-packages/torch/nn/modules/module.pyrsz_IncompatibleKeys.__repr__)__name__ __module__ __qualname__r__str__ __classcell__r!r!)r r"rs rZIncompatibleKeysrrcsP|jd}t|dkr|S|jd}fdd|D}dj|}|d|}|S)N rcsg|]}d|qS) r!).0line) numSpacesr!r" #sz_addindent..)splitlenpopjoin)Zs_r-sfirstr!)r-r" _addindents     r5Z _extra_state)hookreturncCstjt}|t|j<|S)aRegisters a forward pre-hook common to all modules. .. warning :: This adds global state to the `nn.module` module and it is only intended for debugging/profiling purposes. The hook will be called every time before :func:`forward` is invoked. It should have the following signature:: hook(module, input) -> None or modified input The input contains only the positional arguments given to the module. Keyword arguments won't be passed to the hooks and only to the ``forward``. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned(unless that value is already a tuple). This hook has precedence over the specific module hooks registered with ``register_forward_pre_hook``. Returns: :class:`torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling ``handle.remove()`` )hooksr_global_forward_pre_hooksid)r6handler!r!r" register_module_forward_pre_hook4s  r<cCstjt}|t|j<|S)aRegisters a global forward hook for all the modules .. warning :: This adds global state to the `nn.module` module and it is only intended for debugging/profiling purposes. The hook will be called every time after :func:`forward` has computed an output. It should have the following signature:: hook(module, input, output) -> None or modified output The input contains only the positional arguments given to the module. Keyword arguments won't be passed to the hooks and only to the ``forward``. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called after :func:`forward` is called. Returns: :class:`torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling ``handle.remove()`` This hook will be executed before specific module hooks registered with ``register_forward_hook``. )r8r_global_forward_hooksr:)r6r;r!r!r"register_module_forward_hookTs  r>cCs,tdkrtddatjt}|t|j<|S)aRegisters a backward hook common to all the modules. This function is deprecated in favor of :func:`torch.nn.modules.module.register_module_full_backward_hook` and the behavior of this function will change in future versions. Returns: :class:`torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling ``handle.remove()`` TztCannot use both regular backward hooks and full backward hooks as a global Module hook. Please use only one of them.F)_global_is_full_backward_hook RuntimeErrorr8r_global_backward_hooksr:)r6r;r!r!r"register_module_backward_hookss   rBcCs,tdkrtddatjt}|t|j<|S)aRegisters a backward hook common to all the modules. .. warning :: This adds global state to the `nn.module` module and it is only intended for debugging/profiling purposes. The hook will be called every time the gradients with respect to module inputs are computed. The hook should have the following signature:: hook(module, grad_input, grad_output) -> Tensor or None The :attr:`grad_input` and :attr:`grad_output` are tuples. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place of :attr:`grad_input` in subsequent computations. :attr:`grad_input` will only correspond to the inputs given as positional arguments and all kwarg arguments will not appear in the hook. Entries in :attr:`grad_input` and :attr:`grad_output` will be ``None`` for all non-Tensor arguments. For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module's forward function. Global hooks are called before hooks registered with `register_backward_hook` Returns: :class:`torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling ``handle.remove()`` FztCannot use both regular backward hooks and full backward hooks as a global Module hook. Please use only one of them.T)r?r@r8rrAr:)r6r;r!r!r""register_module_full_backward_hooks #  rC)inputr7cGstdS)aDefines the computation performed at every call. Should be overridden by all subclasses. .. note:: Although the recipe for forward pass needs to be defined within this function, one should call the :class:`Module` instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them. N)NotImplementedError)rrDr!r!r"_forward_unimplementeds rFc@seZdZUdZdZedZeee e ddddZ e Z edef dee eedd d d Zee edd ddZee dddddZeddddZeddddZeddddZedddZeddd Zd!d"Zeedgdfed#d$d%Zdee eeefed&d'd(Z dee eeefed&d)d*Z!eed+d,d-Z"eee#efed.d/d0Z$eed+d1d2Z%eed+d3d4Z&eed+d5d6Z'eed+d7d8Z(eeeefed&d9d:Z)e*dee eeefe ee#efeed;dd?d=Z+e*deeeed@dAd=Z+dBd=Z+ede,e,gedeffe-dCdDdEZ.ede,e,gedeffe-dCdFdGZ/dHdIZ0dJdKZ1ede-dCdLdMZ2ede-dCdNdOZ3dPdQZ4dRdSZ5e5Z6edef6dTdUZ7eeedfdVdWdXZ8eeedfddYdZd[Z9d\d]Z:d^d_Z;d`daZeefdcZ?e*de?eee?dddedfZ@e*deedgdhdidfZ@ddkdfZ@ddldmZAdndoZBddgedpdqdrZCddsdtZDdeeEedudvdwZFdeeeEeGeefdxdydzZHdeeEedud{d|ZIdeeeEeGeefdxd}d~ZJeEddddZKeEeGedfdddZLeEddddZMde eNdeedddZOdeeedddZPeed+ddZQdeeedddZRdeddddZSeed+ddZTddZUedddZVddZWddZXddZYdS)raBase class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing to nest them in a tree structure. You can assign the submodules as regular attributes:: import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x)) Submodules assigned in this way will be registered, and will have their parameters converted too when you call :meth:`to`, etc. :ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool Fr)N)r7cCsdtjjdd|_t|_t|_t|_t|_ d|_ t|_ t|_ t|_ t|_t|_dS)z_ Initializes internal Module state, shared by both nn.Module and ScriptModule. zpython.nn_moduleTN)torch_CZ_log_api_usage_oncetrainingr _parameters_buffersset_non_persistent_buffers_set_backward_hooks_is_full_backward_hook_forward_hooks_forward_pre_hooks_state_dict_hooks_load_state_dict_pre_hooks_modules)rr!r!r"__init__s zModule.__init__.T)nametensor persistentr7cCs|dkrt|tjjrtdd|jkr2tdnt|tjjsVt dj tj |nd|krht dn|dkrzt d nzt ||r||jkrt d j |nV|d k rt|tj rt d j tj ||n(||j|<|r|jj|n |jj|d S) aAdds a buffer to the module. This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm's ``running_mean`` is not a parameter, but is part of the module's state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by setting :attr:`persistent` to ``False``. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module's :attr:`state_dict`. Buffers can be accessed as attributes using given names. Args: name (string): name of the buffer. The buffer can be accessed from this module using the given name tensor (Tensor or None): buffer to be registered. If ``None``, then operations that run on buffers, such as :attr:`cuda`, are ignored. If ``None``, the buffer is **not** included in the module's :attr:`state_dict`. persistent (bool): whether the buffer is part of this module's :attr:`state_dict`. Example:: >>> self.register_buffer('running_mean', torch.zeros(num_features)) Fz4ScriptModule does not support non-persistent buffersrKz2cannot assign buffer before Module.__init__() callz&buffer name should be a string. Got {}.zbuffer name can't contain "."z$buffer name can't be empty string ""zattribute '{}' already existsNzHcannot assign '{}' object to buffer '{}' (torch Tensor or None required)) isinstancerGjitZ ScriptModuler@__dict__AttributeError_sixstring_classes TypeErrorformattypenameKeyErrorhasattrrKrrMdiscardadd)rrVrWrXr!r!r"register_buffers*    zModule.register_buffer)rVparamr7cCsd|jkrtdnjt|tjjs8tdjtj|nFd|krJt dn4|dkr\t dn"t ||r~||j kr~t dj||d krd |j |<nBt|t std jtj||n |j rtd j|n ||j |<d S) a-Adds a parameter to the module. The parameter can be accessed as an attribute using given name. Args: name (string): name of the parameter. The parameter can be accessed from this module using the given name param (Parameter or None): parameter to be added to the module. If ``None``, then operations that run on parameters, such as :attr:`cuda`, are ignored. If ``None``, the parameter is **not** included in the module's :attr:`state_dict`. rJz5cannot assign parameter before Module.__init__() callz)parameter name should be a string. Got {}rYz parameter name can't contain "."rZz'parameter name can't be empty string ""zattribute '{}' already existsNzQcannot assign '{}' object to parameter '{}' (torch.nn.Parameter or None required)zCannot assign non-leaf Tensor to parameter '{0}'. Model parameters must be created explicitly. To express '{0}' as a function of another Tensor, compute the value in the forward() method.)r]r^r[rGr_r`rarbrcrdrerJrgrad_fn ValueError)rrVrir!r!r"register_parameterDs,      zModule.register_parameter)rVmoduler7cCst|t r*|dk r*tdjtj|npt|tjjsNtdjtj|nLt||rr||j krrt dj|n(d|krt dj|n|dkrt d||j |<dS) a]Adds a child module to the current module. The module can be accessed as an attribute using the given name. Args: name (string): name of the child module. The child module can be accessed from this module using the given name module (Module): child module to be added to the module. Nz{} is not a Module subclassz&module name should be a string. Got {}zattribute '{}' already existsrYz&module name can't contain ".", got: {}rZz$module name can't be empty string "") r[rrarbrGrcr_r`rerTrd)rrVrmr!r!r" add_modulens zModule.add_module)targetr7cCsv|dkr |S|jd}|}xV|D]N}t||sFt|jd|dt||}t|tjjs td|dq W|S)a Returns the submodule given by ``target`` if it exists, otherwise throws an error. For example, let's say you have an ``nn.Module`` ``A`` that looks like this: .. code-block::text A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) ) (The diagram shows an ``nn.Module`` ``A``. ``A`` has a nested submodule ``net_b``, which itself has two submodules ``net_c`` and ``linear``. ``net_c`` then has a submodule ``conv``.) To check whether or not we have the ``linear`` submodule, we would call ``get_submodule("net_b.linear")``. To check whether we have the ``conv`` submodule, we would call ``get_submodule("net_b.net_c.conv")``. The runtime of ``get_submodule`` is bounded by the degree of module nesting in ``target``. A query against ``named_modules`` achieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists, ``get_submodule`` should always be used. Args: target: The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.) Returns: torch.nn.Module: The submodule referenced by ``target`` Raises: AttributeError: If the target string references an invalid path or resolves to something that is not an ``nn.Module`` rZrYz has no attribute ``z` is not an nn.Module) r/rer^ _get_namegetattrr[rGnnr)rroZatomsmoditemr!r!r" get_submodules0    zModule.get_submodulercCsh|jd\}}}|j|}t||sx|jD]}|j|q Wdd}x|jjD]\}}|dkrBq0tj||}WdQRX|||}|rx||_|}n.t|tst |j st t||j }||j|<|j dk r0tj||j } WdQRX||j | }|r| |j _q0|j j st | j |j j |_ q0Wx0|jjD]"\}} | dk r|| |j|<qW|S)NcSs tj||rtjj SdSdS)NF)rGZ!_has_compatible_shallow_copy_type __future__Z)get_overwrite_module_params_on_conversion)rWZtensor_appliedr!r!r"compute_should_use_set_data<s z2Module._apply..compute_should_use_set_data)children_applyrJitemsrGno_graddatar[rAssertionErrorZis_leaf requires_gradgradrequires_grad_rK) rfnrmrkeyriZ param_appliedZshould_use_set_dataZ out_paramZ grad_appliedbufr!r!r"r8s8           z Module._apply)rrr7cCs(x|jD]}|j|q W|||S)abApplies ``fn`` recursively to every submodule (as returned by ``.children()``) as well as self. Typical use includes initializing the parameters of a model (see also :ref:`nn-init-doc`). Args: fn (:class:`Module` -> None): function to be applied to each submodule Returns: Module: self Example:: >>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[ 1., 1.], [ 1., 1.]]) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[ 1., 1.], [ 1., 1.]]) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) )rapply)rrrmr!r!r"rls&z Module.apply)rrr7cs|jfddS)aMoves all model parameters and buffers to the GPU. This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized. .. note:: This method modifies the module in-place. Args: device (int, optional): if specified, all parameters will be copied to that device Returns: Module: self cs |jS)N)cuda)t)rr!r"szModule.cuda..)r)rrr!)rr"rsz Module.cudacs|jfddS)aMoves all model parameters and buffers to the XPU. This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized. .. note:: This method modifies the module in-place. Arguments: device (int, optional): if specified, all parameters will be copied to that device Returns: Module: self cs |jS)N)xpu)r)rr!r"rszModule.xpu..)r)rrr!)rr"rsz Module.xpu)rr7cCs|jddS)zMoves all model parameters and buffers to the CPU. .. note:: This method modifies the module in-place. Returns: Module: self cSs|jS)N)cpu)rr!r!r"rszModule.cpu..)r)rr!r!r"rs z Module.cpu)rdst_typer7cs|jfddS)zCasts all parameters and buffers to :attr:`dst_type`. .. note:: This method modifies the module in-place. Args: dst_type (type or string): the desired type Returns: Module: self cs |jS)N)type)r)rr!r"rszModule.type..)r)rrr!)rr"rs z Module.typecCs|jddS)zCasts all floating point parameters and buffers to ``float`` datatype. .. note:: This method modifies the module in-place. Returns: Module: self cSs|jr|jS|S)N)is_floating_pointfloat)rr!r!r"rszModule.float..)r)rr!r!r"rs z Module.floatcCs|jddS)zCasts all floating point parameters and buffers to ``double`` datatype. .. note:: This method modifies the module in-place. Returns: Module: self cSs|jr|jS|S)N)rdouble)rr!r!r"rszModule.double..)r)rr!r!r"rs z Module.doublecCs|jddS)zCasts all floating point parameters and buffers to ``half`` datatype. .. note:: This method modifies the module in-place. Returns: Module: self cSs|jr|jS|S)N)rhalf)rr!r!r"rszModule.half..)r)rr!r!r"rs z Module.halfcCs|jddS)zCasts all floating point parameters and buffers to ``bfloat16`` datatype. .. note:: This method modifies the module in-place. Returns: Module: self cSs|jr|jS|S)N)rbfloat16)rr!r!r"rsz!Module.bfloat16..)r)rr!r!r"rs zModule.bfloat16cs|jfddS)aMoves the parameters and buffers to the specified device without copying storage. Args: device (:class:`torch.device`): The desired device of the parameters and buffers in this module. Returns: Module: self cstj|dS)N)r)rGZ empty_like)r)rr!r"r sz!Module.to_empty..)r)rrr!)rr"to_emptys zModule.to_empty)rrr non_blockingr7cCsdS)Nr!)rrrrr!r!r"tosz Module.to)rrrr7cCsdS)Nr!)rrrr!r!r"rs)rrWrr7cCsdS)Nr!)rrWrr!r!r"rscsftjjj||\dk rJjp*js:tdjjrJtj dfdd}|j |S)a= Moves and/or casts the parameters and buffers. This can be called as .. function:: to(device=None, dtype=None, non_blocking=False) :noindex: .. function:: to(dtype, non_blocking=False) :noindex: .. function:: to(tensor, non_blocking=False) :noindex: .. function:: to(memory_format=torch.channels_last) :noindex: Its signature is similar to :meth:`torch.Tensor.to`, but only accepts floating point or complex :attr:`dtype`\ s. In addition, this method will only cast the floating point or complex parameters and buffers to :attr:`dtype` (if given). The integral parameters and buffers will be moved :attr:`device`, if that is given, but with dtypes unchanged. When :attr:`non_blocking` is set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices. See below for examples. .. note:: This method modifies the module in-place. Args: device (:class:`torch.device`): the desired device of the parameters and buffers in this module dtype (:class:`torch.dtype`): the desired floating point or complex dtype of the parameters and buffers in this module tensor (torch.Tensor): Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module memory_format (:class:`torch.memory_format`): the desired memory format for 4D parameters and buffers in this module (keyword only argument) Returns: Module: self Examples:: >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128) NzTnn.Module.to only accepts floating point or complex dtypes, but got desired dtype={}a@Complex modules are a new feature under active development whose design may change, and some modules might not work as expected when using complex tensors as parameters or buffers. Please file an issue at https://github.com/pytorch/pytorch/issues/new?template=bug-report.md if a complex module does not work as expected.cs\dk r:|jdkr:|j|js*|jr.nddS|j|jsP|jrTndS)N)Z memory_format)rr)Zdimrr is_complex)r)convert_to_formatrrrr!r"convert}s zModule.to..convert) rGrHZ_nnZ _parse_torrrarbwarningswarnr)rargskwargsrr!)rrrrr"rsU )r6r7cCs4|jdkrtdd|_tj|j}||j|j<|S)aRegisters a backward hook on the module. This function is deprecated in favor of :meth:`~torch.nn.Module.register_full_backward_hook` and the behavior of this function will change in future versions. Returns: :class:`torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling ``handle.remove()`` TzoCannot use both regular backward hooks and full backward hooks on a single Module. Please use only one of them.F)rOr@r8rrNr:)rr6r;r!r!r"register_backward_hooks    zModule.register_backward_hookcCs4|jdkrtdd|_tj|j}||j|j<|S)aRegisters a backward hook on the module. The hook will be called every time the gradients with respect to module inputs are computed. The hook should have the following signature:: hook(module, grad_input, grad_output) -> tuple(Tensor) or None The :attr:`grad_input` and :attr:`grad_output` are tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place of :attr:`grad_input` in subsequent computations. :attr:`grad_input` will only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries in :attr:`grad_input` and :attr:`grad_output` will be ``None`` for all non-Tensor arguments. For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module's forward function. .. warning :: Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error. Returns: :class:`torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling ``handle.remove()`` FzoCannot use both regular backward hooks and full backward hooks on a single Module. Please use only one of them.T)rOr@r8rrNr:)rr6r;r!r!r"register_full_backward_hooks !   z"Module.register_full_backward_hookcCshg}tdkr|tj7}|jdkr0||jj7}g}tdkrH|tj7}|jdkr`||jj7}||fS)zReturns the backward hooks for use in the call function. It returns two lists, one with the full backward hooks and one with the non-full backward hooks. TF)r?rAvaluesrOrN)rfull_backward_hooksnon_full_backward_hooksr!r!r"_get_backward_hookss    zModule._get_backward_hookscCst|tjs8t|to&tdd|Ds>tjddSn|f}t|tjsvt|todtdd|Ds|tjddSn|f}dd|D}t|dkst|d kr||krtjd nJt|d krtjd n2d d|D}d d|jD}||krtjddS)NcSsg|]}t|tjqSr!)r[rGr)r+rr!r!r"r.sz=Module._maybe_warn_non_full_backward_hook..aUsing non-full backward hooks on a Module that does not return a single Tensor or a tuple of Tensors is deprecated and will be removed in future versions. This hook will be missing some of the grad_output. Please use register_full_backward_hook to get the documented behavior.cSsg|]}t|tjqSr!)r[rGr)r+ir!r!r"r.saUsing non-full backward hooks on a Module that does not take as input a single Tensor or a tuple of Tensors is deprecated and will be removed in future versions. This hook will be missing some of the grad_input. Please use register_full_backward_hook to get the documented behavior.cSsh|]}|jdk r|jqS)N)rj)r+rr!r!r" sz.rr)zUsing a non-full backward hook when outputs are nested in python data structure is deprecated and will be removed in future versions. This hook will be missing some grad_output.zUsing a non-full backward hook when outputs are generated by different autograd Nodes is deprecated and will be removed in future versions. This hook will be missing some grad_output. Please use register_full_backward_hook to get the documented behavior.cSsh|]}|jdk r|jqS)N)rj)r+rr!r!r"rscSsh|] }|dqS)rr!)r+nr!r!r"rszUsing a non-full backward hook when the forward contains multiple autograd Nodes is deprecated and will be removed in future versions. This hook will be missing some grad_input. Please use register_full_backward_hook to get the documented behavior.) r[rGrtupleallrrr0next_functions)rinputsresultrjZ out_grad_fnZinputs_grad_fnrr!r!r""_maybe_warn_non_full_backward_hooks&         z)Module._maybe_warn_non_full_backward_hookcCstj|j}||j|j<|S)a5Registers a forward pre-hook on the module. The hook will be called every time before :func:`forward` is invoked. It should have the following signature:: hook(module, input) -> None or modified input The input contains only the positional arguments given to the module. Keyword arguments won't be passed to the hooks and only to the ``forward``. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned(unless that value is already a tuple). Returns: :class:`torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling ``handle.remove()`` )r8rrQr:)rr6r;r!r!r"register_forward_pre_hooks  z Module.register_forward_pre_hookcCstj|j}||j|j<|S)aRegisters a forward hook on the module. The hook will be called every time after :func:`forward` has computed an output. It should have the following signature:: hook(module, input, output) -> None or modified output The input contains only the positional arguments given to the module. Keyword arguments won't be passed to the hooks and only to the ``forward``. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called after :func:`forward` is called. Returns: :class:`torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling ``handle.remove()`` )r8rrPr:)rr6r;r!r!r"register_forward_hooks  zModule.register_forward_hookc Ostjj}| s t|jtjjr,|j||Stjjjdk }|rr|tjjjkrZtjjj|nd}|rn|j |nd}z|j||}Wd|r|j X|S)NF) rGrH_get_tracing_stater[forwardZ ScriptMethodr\Z_traceZ_trace_module_mapZ push_scopeZ pop_scope)rrDrZ tracing_stateZrecording_scopesrVrr!r!r" _slow_forward4s     zModule._slow_forwardc Ostjjr|jn|j}|jp2|jp2|jp2tp2t p2t s>|||Sgg}}|jsRtr^|j \}}t sh|jrx@t j |jj D]*}|||}|dk r|t |ts|f}|}q|Wd}|rtj||}|j|}|||}t s|jrx2t j |jj D]}||||} | dk r| }qW|r"|j|}|r|} x@t | tjslt | tr`tdd| j D} n| d} q.W| j} | dk rx0|D](}tj||} tj| || j| qW|j||| |S)Ncss|]}t|tjr|VqdS)N)r[rGr)r+vr!r!r" osz$Module._call_impl..r)rGrHrrrrNrPrQrAr=r9rrr[rr8Z BackwardHookZsetup_input_hookZsetup_output_hookrdictnextrj functoolspartialupdate_wrapper register_hookr) rrDrZ forward_callrrr6rZbw_hook hook_resultvarrjwrapperr!r!r" _call_implHsP                  zModule._call_implcCsh|jj|d|jkrt|_d|jkr0t|_d|jkrBt|_d|jkrTt|_d|jkrdd|_dS)NrQrRrSrMrO) r]updaterrQrRrSrLrMrO)rrr!r!r" __setstate__~s      zModule.__setstate__)rVr7cCsd|jkr$|jd}||kr$||Sd|jkrH|jd}||krH||Sd|jkrl|jd}||krl||Stdjt|j|dS)NrJrKrTz!'{}' object has no attribute '{}')r]r^rbrr#)rrVrJrKmodulesr!r!r" __getattr__s      zModule.__getattr__)rVvaluer7csfdd}|jjd}t|trX|dkr2td||j|j|j|j|j|n&|dk r|kr|dk rt dj t j ||j|n|jjd}t|t r|dkrtd||j|j|j|j||<n|dk o|kr|dk r t dj t j |||<nh|jjd }|dk rp|krp|dk rft|t j rft d j t j |||<ntj||dS) Ncs6x0|D](}|krt|tr$|=q|jqWdS)N)r[rrf)Z dicts_or_setsd)rVr!r" remove_froms   z'Module.__setattr__..remove_fromrJz6cannot assign parameters before Module.__init__() callzJcannot assign '{}' as parameter '{}' (torch.nn.Parameter or None expected)rTz2cannot assign module before Module.__init__() callzJcannot assign '{}' as child module '{}' (torch.nn.Module or None expected)rKzAcannot assign '{}' as buffer '{}' (torch.Tensor or None expected))r]getr[rr^rKrTrMrlrarbrGrcrrJrobject __setattr__)rrVrrparamsrbuffersr!)rVr"rs@          zModule.__setattr__cCsX||jkr|j|=n@||jkr4|j|=|jj|n ||jkrH|j|=n tj||dS)N)rJrKrMrfrTr __delattr__)rrVr!r!r"rs     zModule.__delattr__cCstj|j}||j|j<|S)aVThese hooks will be called with arguments: `self`, `state_dict`, `prefix`, `local_metadata`, after the `state_dict` of `self` is set. Note that only parameters and buffers of `self` or its children are guaranteed to exist in `state_dict`. The hooks may modify `state_dict` inplace or return a new one. )r8rrRr:)rr6r;r!r!r"_register_state_dict_hooks  z Module._register_state_dict_hookcCsx6|jjD](\}}|dk r |r$|n|j|||<q Wx@|jjD]2\}}|dk rD||jkrD|rf|n|j|||<qDW|t}t|jdtj tj k r|j ||<dS)aSaves module state to `destination` dictionary, containing a state of the module, but not its descendants. This is called on every submodule in :meth:`~torch.nn.Module.state_dict`. In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic. Args: destination (dict): a dict where state will be stored prefix (str): the prefix for parameters and buffers used in this module Nr~) rJrdetachrKrM_EXTRA_STATE_KEY_SUFFIXrrr rr~)r destinationprefix keep_varsrVrirextra_state_keyr!r!r"_save_to_state_dicts zModule._save_to_state_dict T_destination)r)rrrr7cCsdS)Nr!)rrrrr!r!r" state_dictszModule.state_dictzOrderedDict[str, Tensor])rrr7cCsdS)Nr!)rrrr!r!r"rsrZc Cs|dkrt}t|_t|jd|j|dd<}|j|||x6|jjD](\}}|dk rN|j|||d|dqNWx,|jj D]}|||||}|dk r|}qW|S)aReturns a dictionary containing a whole state of the module. Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to ``None`` are not included. Returns: dict: a dictionary containing a whole state of the module Example:: >>> module.state_dict().keys() ['bias', 'weight'] N)versionr)rY)r) r _metadatar_versionrrTrrrRr) rrrrlocal_metadatarVrmr6rr!r!r"rscCs,tj|j}|rtj||}||j|j<|S)aThese hooks will be called with arguments: `state_dict`, `prefix`, `local_metadata`, `strict`, `missing_keys`, `unexpected_keys`, `error_msgs`, before loading `state_dict` into `self`. These arguments are exactly the same as those of `_load_from_state_dict`. If ``with_module`` is ``True``, then the first argument to the hook is an instance of the module. Arguments: hook (Callable): Callable hook that will be invoked before loading the state dict. with_module (bool, optional): Whether or not to pass the module instance to the hook as the first parameter. )r8rrSrrr:)rr6Z with_moduler;r!r!r""_register_load_state_dict_pre_hook%s    z)Module._register_load_state_dict_pre_hookcsNx&jjD]}||||||||q WfddjjD} tjjj| j} dd| D} x | jD]\} } || }||krb||}tjj j | }| rt | j dkrt |j dkr|d}| r|j | j kr|j dj||j | j qpy"tj| j|WdQRXWnDtk r^}z&|j dj|| j|j|jWYdd}~XnXqp|rp|j |qpW|t}tjd tjtjk r||krj||n|r|j |n|r||kr|j ||rJxh|jD]\}|j|r||kr|t |d}|jd dd}|jkr|| kr|j |qWdS) ayCopies parameters and buffers from :attr:`state_dict` into only this module, but not its descendants. This is called on every submodule in :meth:`~torch.nn.Module.load_state_dict`. Metadata saved for this module in input :attr:`state_dict` is provided as :attr:`local_metadata`. For state dicts without metadata, :attr:`local_metadata` is empty. Subclasses can achieve class-specific backward compatible loading using the version number at `local_metadata.get("version", None)`. .. note:: :attr:`state_dict` is not the same object as the input :attr:`state_dict` to :meth:`~torch.nn.Module.load_state_dict`. So it can be modified. Args: state_dict (dict): a dict containing parameters and persistent buffers. prefix (str): the prefix for parameters and buffers used in this module local_metadata (dict): a dict containing the metadata for this module. See strict (bool): whether to strictly enforce that the keys in :attr:`state_dict` with :attr:`prefix` match the names of parameters and buffers in this module missing_keys (list of str): if ``strict=True``, add missing keys to this list unexpected_keys (list of str): if ``strict=True``, add unexpected keys to this list error_msgs (list of str): error messages should be added to this list, and will be reported together in :meth:`~torch.nn.Module.load_state_dict` cs i|]\}}|jkr||qSr!)rM)r+kr)rr!r" ^sz0Module._load_from_state_dict..cSsi|]\}}|dk r||qS)Nr!)r+rrr!r!r"r`srr)zfsize mismatch for {}: copying a param with shape {} from checkpoint, the shape in current model is {}.NzWhile copying the parameter named "{}", whose dimensions in the model are {} and whose dimensions in the checkpoint are {}, an exception occurred : {}.rrY)rSrrKr itertoolschainrJrGrs parameterZis_lazyr0shapeappendrbrZcopy_ Exceptionsizerrrrr rrkeys startswithr/rT)rrrrstrictrr error_msgsr6Zpersistent_buffersZlocal_name_paramsZ local_staterVrirZ input_paramZ is_param_lazyexrZ input_namer!)rr"_load_from_state_dict:sN! " ,   zModule._load_from_state_dict)rrcsgggtddjdk r._dfdd ||rtdkrjddjdjd d Dtdkrjdd jdjd d Dtdkrtd j|jj djt S)abCopies parameters and buffers from :attr:`state_dict` into this module and its descendants. If :attr:`strict` is ``True``, then the keys of :attr:`state_dict` must exactly match the keys returned by this module's :meth:`~torch.nn.Module.state_dict` function. Args: state_dict (dict): a dict containing parameters and persistent buffers. strict (bool, optional): whether to strictly enforce that the keys in :attr:`state_dict` match the keys returned by this module's :meth:`~torch.nn.Module.state_dict` function. Default: ``True`` Returns: ``NamedTuple`` with ``missing_keys`` and ``unexpected_keys`` fields: * **missing_keys** is a list of str containing the missing keys * **unexpected_keys** is a list of str containing the unexpected keys Note: If a parameter or buffer is registered as ``None`` and its corresponding key exists in :attr:`state_dict`, :meth:`load_state_dict` will raise a ``RuntimeError``. rNrZcsldkr inj|ddi}|j||dx0|jjD]"\}}|dk rB|||dqBWdS)Nr)TrYr)rrrTr)rmrrrVchild)rloadmetadatarrrr!r"rs  z$Module.load_state_dict..loadrz%Unexpected key(s) in state_dict: {}. z, css|]}dj|VqdS)z"{}"N)rb)r+rr!r!r"rsz)Module.load_state_dict..z"Missing key(s) in state_dict: {}. css|]}dj|VqdS)z"{}"N)rb)r+rr!r!r"rsz*Error(s) in loading state_dict for {}: {}z )rZ) rrcopyrr0insertrbr2r@r r#r)rrrr!)rrrrrrr"load_state_dicts.    zModule.load_state_dictc cst}|r|j|dn||fg}xd|D]\\}}||}xJ|D]B\} } | dks<| |krVq<|j| ||rjdnd| } | | fVqHelper method for yielding various names + members of modules.)rNrYrZ)rL named_modulesrg) rZget_members_fnrrecursememorZ module_prefixrmmembersrrrVr!r!r"_named_memberss zModule._named_members)rr7ccs$x|j|dD]\}}|VqWdS)aRReturns an iterator over module parameters. This is typically passed to an optimizer. Args: recurse (bool): if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module. Yields: Parameter: module parameter Example:: >>> for param in model.parameters(): >>> print(type(param), param.size()) (20L,) (20L, 1L, 5L, 5L) )rN)named_parameters)rrrVrir!r!r" parametersszModule.parameters)rrr7ccs,|jdd||d}x|D] }|VqWdS)aReturns an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself. Args: prefix (str): prefix to prepend to all parameter names. recurse (bool): if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module. Yields: (string, Parameter): Tuple containing the name and parameter Example:: >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size()) cSs |jjS)N)rJr)rmr!r!r"rsz)Module.named_parameters..)rrN)r)rrrgenelemr!r!r"rs   zModule.named_parametersccs$x|j|dD]\}}|VqWdS)a Returns an iterator over module buffers. Args: recurse (bool): if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Yields: torch.Tensor: module buffer Example:: >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) (20L,) (20L, 1L, 5L, 5L) )rN) named_buffers)rrryrr!r!r"r szModule.buffersccs,|jdd||d}x|D] }|VqWdS)aReturns an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself. Args: prefix (str): prefix to prepend to all buffer names. recurse (bool): if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Yields: (string, torch.Tensor): Tuple containing the name and buffer Example:: >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size()) cSs |jjS)N)rKr)rmr!r!r"r8sz&Module.named_buffers..)rrN)r)rrrrrr!r!r"r#s   zModule.named_buffersccs x|jD]\}}|Vq WdS)zqReturns an iterator over immediate children modules. Yields: Module: a child module N)named_children)rrVrmr!r!r"r=szModule.childrenccsFt}x:|jjD],\}}|dk r||kr|j|||fVqWdS)aReturns an iterator over immediate children modules, yielding both the name of the module as well as the module itself. Yields: (string, Module): Tuple containing a name and child module Example:: >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module) N)rLrTrrg)rrrVrmr!r!r"rFs  zModule.named_childrenccs x|jD]\}}|Vq WdS)aReturns an iterator over all modules in the network. Yields: Module: a module in the network Note: Duplicate modules are returned only once. In the following example, ``l`` will be returned only once. Example:: >>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True) N)r)rryrmr!r!r"rZszModule.modules)rrremove_duplicateccs|dkrt}||kr|r$|j|||fVxR|jjD]D\}}|dkrLq:||rVdnd|}x|j|||D] }|VqpWq:WdS)aDReturns an iterator over all modules in the network, yielding both the name of the module as well as the module itself. Args: memo: a memo to store the set of modules already added to the result prefix: a prefix that will be added to the name of the module remove_duplicate: whether to remove the duplicated module instances in the result or not Yields: (string, Module): Tuple of name and module Note: Duplicate modules are returned only once. In the following example, ``l`` will be returned only once. Example:: >>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True)) NrYrZ)rLrgrTrr)rrrrrVrmZsubmodule_prefixmr!r!r"rus   zModule.named_modules)rmoder7cCs8t|tstd||_x|jD]}|j|q"W|S)aSets the module in training mode. This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`, etc. Args: mode (bool): whether to set training mode (``True``) or evaluation mode (``False``). Default: ``True``. Returns: Module: self z'training mode is expected to be boolean)r[boolrkrIrtrain)rrrmr!r!r"r s  z Module.traincCs |jdS)a9Sets the module in evaluation mode. This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`, etc. This is equivalent with :meth:`self.train(False) `. See :ref:`locally-disable-grad-doc` for a comparison between `.eval()` and several similar mechanisms that may be confused with it. Returns: Module: self F)r )rr!r!r"evalsz Module.eval)rrr7cCs x|jD]}|j|q W|S)aChange if autograd should record operations on parameters in this module. This method sets the parameters' :attr:`requires_grad` attributes in-place. This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training). See :ref:`locally-disable-grad-doc` for a comparison between `.requires_grad_()` and several similar mechanisms that may be confused with it. Args: requires_grad (bool): whether autograd should record operations on parameters in this module. Default: ``True``. Returns: Module: self )rr)rrpr!r!r"rszModule.requires_grad_) set_to_noner7cCspt|ddrtjdxT|jD]H}|jdk r |r:d|_q |jjdk rR|jjn |jjd|jjq WdS)a7Sets gradients of all model parameters to zero. See similar function under :class:`torch.optim.Optimizer` for more context. Args: set_to_none (bool): instead of setting to zero, set the grads to None. See :meth:`torch.optim.Optimizer.zero_grad` for details. _is_replicaFaGCalling .zero_grad() from a module created with nn.DataParallel() has no effect. The parameters are copied (in a differentiable manner) from the original module. This means they are not leaf nodes in autograd and so don't accumulate gradients. If you need gradients in your forward method, consider using autograd.grad instead.N) rrrrrrrjZdetach_rZzero_)rr r r!r!r" zero_grads     zModule.zero_gradcCs|jddS)z&See :meth:`torch.Tensor.share_memory_`cSs|jS)N)Z share_memory_)rr!r!r"rsz%Module.share_memory..)r)rr!r!r" share_memoryszModule.share_memorycCs|jjS)N)r r#)rr!r!r"rqszModule._get_namecCsdS)zSet the extra representation of the module To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable. rZr!)rr!r!r" extra_reprszModule.extra_reprc Csg}|j}|r|jd}g}x>|jjD]0\}}t|}t|d}|jd|d|q*W||}|jd}|rt|dkr| r||d7}n|ddj |d7}|d7}|S) Nr(r(z): r)rz )) rr/rTrreprr5rrqr0r2) rZ extra_linesrZ child_linesrrmZmod_strlinesZmain_strr!r!r"r s"   zModule.__repr__cCslt|j}t|jj}t|jj}t|jj}t|jj}|||||}dd|D}t|S)NcSsg|]}|djs|qS)r)isdigit)r+rr!r!r"r..sz"Module.__dir__..) dirr listr]rrJrTrKsorted)rZ module_attrsattrsrrrrr!r!r"__dir__%s zModule.__dir__cCsD|jt|}|jj|_t|_|jj|_|jj|_d|_|S)NT) __new__rr]rrrJrKrTr)rZreplicar!r!r"_replicate_for_data_parallel2s   z#Module._replicate_for_data_parallel)T)N)N)...).).).N).N)..)..)NrZF)F)T)rZT)T)rZT)T)rZT)NrZT)T)T)F)Zr#r$r%__doc__Z dump_patchesr rintrIrrOrUrFrr r strrrhrrlrnrvr{r}r~rrrrr rrrrrrrrrrrrr_grad_trrrrrrrrr__call__rrrrrrrrrrrrrrr rr rrrrrrrrr r rrrrqrrrrr!r!r!r"rs  6*D&%4+        2 k)+4/    X<    -  ).N).N)/ collectionsrrrrrrGrrZtorch.utils.hooksutilsr8rrrtypingr r r r r rrrrrrrZ utils.hooksrr!rrr5rArr?r r9r=rr<r>rBrCrFrr!r!r!r"s6  8      /