/usr/local/lib64/python3.6/site-packages/torch/nn/utils/__pycache__
NameSizeModeActions
clip_grad.cpython-36.pyc39470644editdlrm
convert_parameters.cpython-36.pyc23450644editdlrm
fusion.cpython-36.pyc15280644editdlrm
init.cpython-36.pyc22840644editdlrm
memory_format.cpython-36.pyc37630644editdlrm
parametrizations.cpython-36.pyc149990644editdlrm
parametrize.cpython-36.pyc198700644editdlrm
prune.cpython-36.pyc455570644editdlrm
rnn.cpython-36.pyc159340644editdlrm
spectral_norm.cpython-36.pyc96420644editdlrm
weight_norm.cpython-36.pyc46070644editdlrm
__init__.cpython-36.pyc7320644editdlrm
Edit: /usr/local/lib64/python3.6/site-packages/torch/nn/utils/__pycache__/parametrizations.cpython-36.pyc (14999B)
3 EgW@sddlmZmZddlZddlmZddlmZddlmZddl m Z ddl m Z dd d Zd d ZGd ddeZGdddeZdddeee eeedddZGdddeZd eeeee eedddZdS)!)EnumautoN)Tensor) parametrize)Module) functional)OptionalcCs`|jd|jd}}tj||j|jd}d|tj|jj}tj|jdd j |||dS) Nr)dtypedeviceg$@)Zatolr r) sizetorcheyer r ZfinfoepsZallclose transposeconj)QrnkIdrK/usr/local/lib64/python3.6/site-packages/torch/nn/utils/parametrizations.py_is_orthogonal srcCs<tj|\}}tjj||}||jdddjjd9}|S)z Assume that A is a tall matrix. Compute the Q factor s.t. A = QR (A may be complex) and diag(R) is real and non-negative rr )dim1dim2r rr )rgeqrflinalghouseholder_productdiagonalZsgn unsqueeze)AXtaurrrr_make_orthogonalsr&c@seZdZeZeZeZdS) _OrthMapsN)__name__ __module__ __qualname__r matrix_expcayley householderrrrrr'sr'csbeZdZUeddeddfddZejejddd Zej j ejejd d d Z Z S) _OrthogonalT)use_trivializationN)orthogonal_mapreturncsFtj|jr$|tjkr$td|j|_||_|rB|jdddS)NzAThe householder parametrization does not support complex tensors.base) super__init__ is_complexr'r- ValueErrorshaper0register_buffer)selfweightr0r/) __class__rrr4(s z_Orthogonal.__init__)r$r1c Cs|jd |jd}}||k}|r8|jdd}||}}|jtjksR|jtjkr$|j}||krtj||j |||j |j dddgdd}||jddj }|jtjkrtj|}nH|jtjkrtj ||j|jd}tjjtj||ddtj||dd}||krr|dd|f}nN|jdd}d d ||jdd}tjj||}||jddd jjd}t|d r|j|}|r|jdd}|S) Nrr )dim)r r g?)alpha.)r!g@g?)rrr2r rr rr rr)rrrr rgrr r rr r r)rrr0r'r+r,ZtrilrcatZ new_zerosexpandr7rrr r rZsolveaddsumr r!intr"hasattrr2) r9r$rrZ transposedr#rrr%rrrforwardCs4  2  &     z_Orthogonal.forward)rr1c Csz|j|jkr&td|jd|jd|}|jd |jd}}||k}|rb|jdd}||}}t|ds|jtjks|jtjkrt dt j |\}}|j dddj |j ddd|d kd9<|r|jddS|S||krt|st|}n|j}nHt j|jdd|||f|j|jd }t j||gdd }t|}||_t j|} | j dddjd| SdS)Nz0Expected a matrix or batch of matrices of shape z. Got a tensor of shape .rr r2ztIt is not possible to assign to the matrix exponential or the Cayley parametrizations when use_trivialization=False.)rrg)r r )r<g?r rr rr rr rrr rr rr rg)r7r6rrrCr0r'r,r+NotImplementedErrorrrr!Zsign_rr&cloneZrandnr r r>r2Z zeros_likeZfill_) r9rZQ_initrrrr#r%NZneg_Idrrr right_inverseks4        . z_Orthogonal.right_inverse) r(r)r*rr2r'r4rrDautogradno_gradrI __classcell__rr)r;rr.%s (r.r:T)r/)modulenamer0r/r1cCst||d}t|ts&tdj|||jdkrBtd|jd|dkrn|jd |jdksf|jrjdnd}tt|d}|dkrtd |t |||d }t j |||d d |S)aApplies an orthogonal or unitary parametrization to a matrix or a batch of matrices. Letting :math:`\mathbb{K}` be :math:`\mathbb{R}` or :math:`\mathbb{C}`, the parametrized matrix :math:`Q \in \mathbb{K}^{m \times n}` is **orthogonal** as .. math:: \begin{align*} Q^{\text{H}}Q &= \mathrm{I}_n \mathrlap{\qquad \text{if }m \geq n}\\ QQ^{\text{H}} &= \mathrm{I}_m \mathrlap{\qquad \text{if }m < n} \end{align*} where :math:`Q^{\text{H}}` is the conjugate transpose when :math:`Q` is complex and the transpose when :math:`Q` is real-valued, and :math:`\mathrm{I}_n` is the `n`-dimensional identity matrix. In plain words, :math:`Q` will have orthonormal columns whenever :math:`m \geq n` and orthonormal rows otherwise. If the tensor has more than two dimensions, we consider it as a batch of matrices of shape `(..., m, n)`. The matrix :math:`Q` may be parametrized via three different ``orthogonal_map`` in terms of the original tensor: - ``"matrix_exp"``/``"cayley"``: the :func:`~torch.matrix_exp` :math:`Q = \exp(A)` and the `Cayley map`_ :math:`Q = (\mathrm{I}_n + A/2)(\mathrm{I}_n - A/2)^{-1}` are applied to a skew-symmetric :math:`A` to give an orthogonal matrix. - ``"householder"``: computes a product of Householder reflectors (:func:`~torch.linalg.householder_product`). ``"matrix_exp"``/``"cayley"`` often make the parametrized weight converge faster than ``"householder"``, but they are slower to compute for very thin or very wide matrices. If ``use_trivialization=True`` (default), the parametrization implements the "Dynamic Trivialization Framework", where an extra matrix :math:`B \in \mathbb{K}^{n \times n}` is stored under ``module.parametrizations.weight[0].base``. This helps the convergence of the parametrized layer at the expense of some extra memory use. See `Trivializations for Gradient-Based Optimization on Manifolds`_ . Initial value of :math:`Q`: If the original tensor is not parametrized and ``use_trivialization=True`` (default), the initial value of :math:`Q` is that of the original tensor if it is orthogonal (or unitary in the complex case) and it is orthogonalized via the QR decomposition otherwise (see :func:`torch.linalg.qr`). Same happens when it is not parametrized and ``orthogonal_map="householder"`` even when ``use_trivialization=False``. Otherwise, the initial value is the result of the composition of all the registered parametrizations applied to the original tensor. .. note:: This function is implemented using the parametrization functionality in :func:`~torch.nn.utils.parametrize.register_parametrization`. .. _`Cayley map`: https://en.wikipedia.org/wiki/Cayley_transform#Matrix_map .. _`Trivializations for Gradient-Based Optimization on Manifolds`: https://arxiv.org/abs/1909.09501 Args: module (nn.Module): module on which to register the parametrization. name (str, optional): name of the tensor to make orthogonal. Default: ``"weight"``. orthogonal_map (str, optional): One of the following: ``"matrix_exp"``, ``"cayley"``, ``"householder"``. Default: ``"matrix_exp"`` if the matrix is square or complex, ``"householder"`` otherwise. use_trivialization (bool, optional): whether to use the dynamic trivialization framework. Default: ``True``. Returns: The original module with an orthogonal parametrization registered to the specified weight Example:: >>> orth_linear = orthogonal(nn.Linear(20, 40)) >>> orth_linear ParametrizedLinear( in_features=20, out_features=40, bias=True (parametrizations): ModuleDict( (weight): ParametrizationList( (0): _Orthogonal() ) ) ) >>> Q = orth_linear.weight >>> torch.dist(Q.T @ Q, torch.eye(20)) tensor(4.9332e-07) Nz5Module '{}' has no parameter ot buffer with name '{}'rz8Expected a matrix or batch of matrices. Got a tensor of z dimensions.r r+r-zLorthogonal_map has to be one of "matrix_exp", "cayley", "householder". Got: )r/T)Zunsafer r) getattr isinstancerr6formatndimrr5r'r.rregister_parametrization)rMrNr0r/r:Z orth_enumZorthrrr orthogonals W   $ rTcseZdZdejeeeddfdd Zejejdd d Zej j ejedd d d Z ejejdddZ ejejdddZ ZS) _SpectralNormr r-q=N)r:n_power_iterationsr<rr1c stj|j}||ks"|| krBtd|d|dd|d|dkrXtdj||dkrd|n|||_||_|dkr||_|j |}|j \}}|j |j dd} |j |j dd} |j dtj| d|jd |j d tj| d|jd |j|d dS) Nz5Dimension out of range (expected to be in range of [-z, r z ] but got )rzIExpected n_power_iterations to be positive, but got n_power_iterations={}_u)r<r_v)r3r4rR IndexErrorr6rQr<rrW_reshape_weight_to_matrixrZ new_emptyZnormal_r8F normalize _power_method) r9r:rWr<rrR weight_mathwuv)r;rrr4s$    z_SpectralNorm.__init__)r:r1csJ|jdkstjdkr@|jjffddt|jD}|jdS)Nr rc3s|]}|jkr|VqdS)N)r<).0d)r9rr Dsz:_SpectralNorm._reshape_weight_to_matrix..)rRAssertionErrorr<Zpermuterangeflatten)r9r:r)r9rr]>s (z'_SpectralNorm._reshape_weight_to_matrix)rarWr1cCsl|jdkstxXt|D]L}tjtj||jd|j|j d|_ tjtj|j |j d|j|jd|_qWdS)Nr r)r<rout) rRrirjr^r_rmvrZrrYt)r9rarW_rrrr`Hs "z_SpectralNorm._power_methodcCsz|jdkrtj|d|jdS|j|}|jr:|j||j|jj t j d}|j j t j d}t j |t j||}||SdS)Nr r)r<r)Z memory_format)rRr^r_rr]Ztrainingr`rWrYrGrZcontiguous_formatrZdotrm)r9r:rardresigmarrrrDus  z_SpectralNorm.forward)valuer1cCs|S)Nr)r9rrrrrrIsz_SpectralNorm.right_inverse)r rrV)r(r)r*rrrBfloatr4r]rJrKr`rDrIrLrr)r;rrUs  ,rUr -q=)rMrNrWrr<r1cCspt||d}t|ts&tdj|||dkrTt|tjjtjjtjj frPd}nd}t j ||t |||||S)a Applies spectral normalization to a parameter in the given module. .. math:: \mathbf{W}_{SN} = \dfrac{\mathbf{W}}{\sigma(\mathbf{W})}, \sigma(\mathbf{W}) = \max_{\mathbf{h}: \mathbf{h} \ne 0} \dfrac{\|\mathbf{W} \mathbf{h}\|_2}{\|\mathbf{h}\|_2} When applied on a vector, it simplifies to .. math:: \mathbf{x}_{SN} = \dfrac{\mathbf{x}}{\|\mathbf{x}\|_2} Spectral normalization stabilizes the training of discriminators (critics) in Generative Adversarial Networks (GANs) by reducing the Lipschitz constant of the model. :math:`\sigma` is approximated performing one iteration of the `power method`_ every time the weight is accessed. If the dimension of the weight tensor is greater than 2, it is reshaped to 2D in power iteration method to get spectral norm. See `Spectral Normalization for Generative Adversarial Networks`_ . .. _`power method`: https://en.wikipedia.org/wiki/Power_iteration .. _`Spectral Normalization for Generative Adversarial Networks`: https://arxiv.org/abs/1802.05957 .. note:: This function is implemented using the parametrization functionality in :func:`~torch.nn.utils.parametrize.register_parametrization`. It is a reimplementation of :func:`torch.nn.utils.spectral_norm`. .. note:: When this constraint is registered, the singular vectors associated to the largest singular value are estimated rather than sampled at random. These are then updated performing :attr:`n_power_iterations` of the `power method`_ whenever the tensor is accessed with the module on `training` mode. .. note:: If the `_SpectralNorm` module, i.e., `module.parametrization.weight[idx]`, is in training mode on removal, it will perform another power iteration. If you'd like to avoid this iteration, set the module to eval mode before its removal. Args: module (nn.Module): containing module name (str, optional): name of weight parameter. Default: ``"weight"``. n_power_iterations (int, optional): number of power iterations to calculate spectral norm. Default: ``1``. eps (float, optional): epsilon for numerical stability in calculating norms. Default: ``1e-12``. dim (int, optional): dimension corresponding to number of outputs. Default: ``0``, except for modules that are instances of ConvTranspose{1,2,3}d, when it is ``1`` Returns: The original module with a new parametrization registered to the specified weight Example:: >>> snm = spectral_norm(nn.Linear(20, 40)) >>> snm ParametrizedLinear( in_features=20, out_features=40, bias=True (parametrizations): ModuleDict( (weight): ParametrizationList( (0): _SpectralNorm() ) ) ) >>> torch.linalg.matrix_norm(snm.weight, 2) tensor(1.0000, grad_fn=) Nz5Module '{}' has no parameter or buffer with name '{}'r r) rOrPrr6rQrnnZConvTranspose1dZConvTranspose2dZConvTranspose3drrSrU)rMrNrWrr<r:rrr spectral_normsL    rv)N)r:N)r:r rtN)enumrrrrutilsrmodulesrrr^typingr rr&r'r.strboolrTrUrBrsrvrrrrs&        mq