L iYddlmZddlZddlmZddlmZddlmZm Z m Z m Z m Z dgZ Gdde Zd e d ed e_y) )UnionN)Tensor) _functional) _maximize_doc _params_doc _to_scalar OptimizerParamsT SparseAdamc eZdZ ddedeeefdeeefdedef fd Z e jd dZ xZ S) r paramslrbetasepsmaximizect|tr|jdk7r tdd|kstd|d|kstd|d|dcxkrdksntd|dd|dcxkrdksntd |d||||d }t |||g}g}t |jD]\} } t| tsJd t| t | d D]H\} } | jr|j| | g| js6|j| | gJ|rtd |d|rtd|dy)NrzTensor lr must be 1-elementgzInvalid learning rate: zInvalid epsilon value: rg?z#Invalid beta parameter at index 0: z#Invalid beta parameter at index 1: )rrrrz.param_groups must be a list of dicts, but got rzSparse params at indices z-: SparseAdam requires dense parameter tensorszComplex params at indices z0: SparseAdam does not support complex parameters) isinstancernumel ValueErrorsuper__init__ enumerate param_groupsdicttype is_sparseappend is_complex)selfrrrrrdefaults sparse_paramscomplex_paramsindex param_groupd_indexd_param __class__s ]/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/torch/optim/sparse_adam.pyrzSparseAdam.__init__s b& !bhhjAo:; ;Rx6rd;< <Sy6se<= =eAh$$B58*MN NeAh$$B58*MN N   * "+D,=,="> < E;k40 @kAR@ST 0%.k(.C$D < $$!((%)9:%%'"))5'*:;  < < +M?:gh  ,^,<LE5yyU3H8_ 666%$++A.66++*gLL( JJqME5zQ()f +0+;+;U-B-B,i(/4.>.>U-B-B/l+OOE)$45&&u\':;&MQ&M&&uV}5; 6> MM %LeDk*! Q3 j q ! !s F11F;)gMbP?)g?g+?g:0yE>F)N)__name__ __module__ __qualname__r rfloatrtupleboolrr2no_gradr, __classcell__)r(s@r)r r sw$(%1 .. %- .UE\" .  .  .`U]]_AAr*aZ SparseAdam implements a masked version of the Adam algorithm suitable for sparse gradients. Currently, due to implementation constraints (explained below), SparseAdam is only intended for a narrow subset of use cases, specifically parameters of a dense layout with gradients of a sparse layout. This occurs in a special case where the module backwards produces grads already in a sparse layout. One example NN module that behaves as such is ``nn.Embedding(sparse=True)``. SparseAdam approximates the Adam algorithm by masking out the parameter and moment updates corresponding to the zero values in the gradients. Whereas the Adam algorithm will update the first moment, the second moment, and the parameters based on all values of the gradients, SparseAdam only updates the moments and parameters corresponding to the non-zero values of the gradients. A simplified way of thinking about the `intended` implementation is as such: 1. Create a mask of the non-zero values in the sparse gradients. For example, if your gradient looks like [0, 5, 0, 0, 9], the mask would be [0, 1, 0, 0, 1]. 2. Apply this mask over the running moments and do computation on only the non-zero values. 3. Apply this mask over the parameters and only apply an update on non-zero values. In actuality, we use sparse layout Tensors to optimize this approximation, which means the more gradients that are masked by not being materialized, the more performant the optimization. Since we rely on using sparse layout tensors, we infer that any materialized value in the sparse layout is non-zero and we do NOT actually verify that all values are not zero! It is important to not conflate a semantically sparse tensor (a tensor where many of its values are zeros) with a sparse layout tensor (a tensor where ``.is_sparse`` returns ``True``). The SparseAdam approximation is intended for `semantically` sparse tensors and the sparse layout is only a implementation detail. A clearer implementation would be to use MaskedTensors, but those are experimental. .. note:: If you suspect your gradients are semantically sparse (but do not have sparse layout), this variant may not be the best for you. Ideally, you want to avoid materializing anything that is suspected to be sparse in the first place, since needing to convert all your grads from dense layout to sparse layout may outweigh the performance gain. Here, using Adam may be the best alternative, unless you can easily rig up your module to output sparse grads similar to ``nn.Embedding(sparse=True)``. If you insist on converting your grads, you can do so by manually overriding your parameters' ``.grad`` fields with their sparse equivalents before calling ``.step()``. Args: ad lr (float, Tensor, optional): learning rate (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability (default: 1e-8) zd .. _Adam\: A Method for Stochastic Optimization: https://arxiv.org/abs/1412.6980 )typingrr2rrr; optimizerrrr r r __all__r __doc__r*r)rTsX QQ .ssl. \   i9 r*