# --------------------------------------------------------------------------
# ⚠️ WARNING - AUTO-GENERATED CODE - DO NOT EDIT ⚠️
# ⚙️ Generated by 'python -m opgen'
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
# pylint: disable=W0221,W0222,R0901,W0237
# mypy: disable-error-code=override
# ruff: noqa: N801,E741
# ruff: noqa: D214,D402,D405,D411,D412,D416,D417
# --------------------------------------------------------------------------

from __future__ import annotations

from typing import Optional, Sequence, TypeVar, Union

from onnx.defs import get_schema
from typing_extensions import TypeAlias

from onnxscript.onnx_types import (
    BOOL,
    COMPLEX64,
    COMPLEX128,
    DOUBLE,
    FLOAT,
    FLOAT16,
    INT8,
    INT16,
    INT32,
    INT64,
    STRING,
    UINT8,
    UINT16,
    UINT32,
    UINT64,
)
from onnxscript.values import Op, Opset


class Opset_ai_onnx_preview_training1(Opset):
    def __new__(cls):
        return Opset.__new__(cls, "ai.onnx.preview.training", 1)

    T1_Adagrad = TypeVar("T1_Adagrad", DOUBLE, FLOAT)

    T2_Adagrad: TypeAlias = INT64

    T3_Adagrad = TypeVar("T3_Adagrad", DOUBLE, FLOAT)

    def Adagrad(
        self,
        R: T1_Adagrad,
        T: T2_Adagrad,
        *inputs: T3_Adagrad,
        decay_factor: float = 0.0,
        epsilon: float = 9.999999974752427e-07,
        norm_coefficient: float = 0.0,
    ) -> T3_Adagrad:
        r"""[🌐 ai.onnx.preview.training::Adagrad(1)](https://onnx.ai/onnx/operators/onnx_aionnxpreviewtraining_Adagrad.html#adagrad-1 "Online Documentation")


            Compute one iteration of ADAGRAD, a stochastic gradient based optimization
            algorithm. This operator can conduct the optimization of multiple tensor variables.

            Let's define the behavior of this operator. As you can imagine, ADAGRAD requires
            some parameters:

             - The initial learning-rate "R".
             - The update count "T". That is, the number of training iterations conducted.
             - A L2-norm regularization coefficient "norm_coefficient".
             - A learning-rate decay factor "decay_factor".
             - A small constant "epsilon" to avoid dividing-by-zero.

            At each ADAGRAD iteration, the optimized tensors are moved along a direction
            computed based on their estimated gradient and accumulated squared gradient. Assume
            that only a single tensor "X" is updated by this operator. We need the value of "X",
            its gradient "G", and its accumulated squared gradient "H". Therefore, variables in
            this operator's input list are sequentially "R", "T", "X", "G", and "H". Other
            parameters are given as attributes because they are usually constants. Also, the
            corresponding output tensors are the new value of "X" (called "X_new"), and then
            the new accumulated squared gradient (called "H_new"). Those outputs are computed
            from the given inputs following the pseudo code below.

            Let "+", "-", "*", and "/" are all element-wise arithmetic operations with
            numpy-style broadcasting support. The pseudo code to compute those outputs is:

              // Compute a scalar learning-rate factor. At the first update of X, T is generally
              // 0 (0-based update index) or 1 (1-based update index).
              r = R / (1 + T * decay_factor);

              // Add gradient of 0.5 * norm_coefficient * ||X||_2^2, where ||X||_2 is the 2-norm.
              G_regularized = norm_coefficient * X + G;

              // Compute new accumulated squared gradient.
              H_new = H + G_regularized * G_regularized;

              // Compute the adaptive part of per-coordinate learning rate. Note that Sqrt(...)
              // computes element-wise square-root.
              H_adaptive = Sqrt(H_new) + epsilon

              // Compute the new value of "X".
              X_new = X - r * G_regularized / H_adaptive;

            If one assign this operators to optimize multiple inputs, for example, "X_1" and "X_2", the same
            pseudo code may be extended to handle all tensors jointly. More specifically, we can view "X" as a
            concatenation of "X_1" and "X_2" (of course, their gradient and accumulate gradient should
            be concatenated too) and then just reuse the entire pseudo code.

            Note that ADAGRAD was first proposed in http://jmlr.org/papers/volume12/duchi11a/duchi11a.pdf.
            In that reference paper, this operator is a special case of the Figure 1's composite mirror
            descent update.


        Args:
            R: The initial learning rate.

            T: The update count of "X". It should be a scalar.

            inputs: (variadic, heterogeneous) The current values of optimized tensors,
                followed by their respective gradients, followed by their respective
                accumulated squared gradients.For example, if two tensor "X_1" and "X_2"
                are optimized, The input list would be ["X_1", "X_2", gradient of "X_1",
                gradient of "X_2", accumulated squared gradient of "X_1", accumulated
                squared gradient of "X_2"].

            decay_factor: The decay factor of learning rate after one update.The
                effective learning rate is computed by r = R / (1 + T * decay_factor).
                Default to 0 so that increasing update counts doesn't reduce the
                learning rate.

            epsilon: Small scalar to avoid dividing by zero.

            norm_coefficient: Regularization coefficient in 0.5 * norm_coefficient *
                ||X||_2^2. Default to 0, which means no regularization.
        """

        schema = get_schema("Adagrad", 1, "ai.onnx.preview.training")
        op = Op(self, "Adagrad", schema)
        return op(
            *self._prepare_inputs(schema, R, T, *inputs),
            decay_factor=decay_factor,
            epsilon=epsilon,
            norm_coefficient=norm_coefficient,
        )

    T1_Adam = TypeVar("T1_Adam", DOUBLE, FLOAT)

    T2_Adam: TypeAlias = INT64

    T3_Adam = TypeVar("T3_Adam", DOUBLE, FLOAT)

    def Adam(
        self,
        R: T1_Adam,
        T: T2_Adam,
        *inputs: T3_Adam,
        alpha: float = 0.8999999761581421,
        beta: float = 0.9990000128746033,
        epsilon: float = 9.999999974752427e-07,
        norm_coefficient: float = 0.0,
        norm_coefficient_post: float = 0.0,
    ) -> T3_Adam:
        r"""[🌐 ai.onnx.preview.training::Adam(1)](https://onnx.ai/onnx/operators/onnx_aionnxpreviewtraining_Adam.html#adam-1 "Online Documentation")


            Compute one iteration of Adam, a stochastic gradient based optimization
            algorithm. This operator can conduct the optimization of multiple tensor variables.

            Let's define the behavior of this operator. First of all, Adam requires
            some parameters:

             - The learning-rate "R".
             - The update count "T". That is, the number of training iterations conducted.
             - A L2-norm regularization coefficient "norm_coefficient".
             - A small constant "epsilon" to avoid dividing-by-zero.
             - Two coefficients, "alpha" and "beta".

            At each Adam iteration, the optimized tensors are moved along a direction
            computed based on their exponentially-averaged historical gradient and
            exponentially-averaged historical squared gradient. Assume that only a tensor
            "X" is being optimized. The rest of required information is

             - the value of "X",
             - "X"'s gradient (denoted by "G"),
             - "X"'s exponentially-averaged historical gradient (denoted by "V"), and
             - "X"'s exponentially-averaged historical squared gradient (denoted by "H").

            Some of those parameters are passed into this operator as input tensors and others
            are stored as this operator's attributes. Specifically, this operator's input tensor
            list is ["R", "T", "X", "G", "V", "H"]. That is, "R" is the first input, "T" is
            the second input, and so on. Other parameters are given as attributes because they
            are constants. Moreover, the corresponding output tensors are

             - the new value of "X" (called "X_new"),
             - the new exponentially-averaged historical gradient (denoted by "V_new"), and
             - the new exponentially-averaged historical squared gradient (denoted by "H_new").

            Those outputs are computed following the pseudo code below.

            Let "+", "-", "*", and "/" are all element-wise arithmetic operations with
            numpy-style broadcasting support. The pseudo code to compute those outputs is:

              // Add gradient of 0.5 * norm_coefficient * ||X||_2^2, where ||X||_2 is the 2-norm.
              G_regularized = norm_coefficient * X + G

              // Update exponentially-averaged historical gradient.
              V_new = alpha * V + (1 - alpha) * G_regularized

              // Update exponentially-averaged historical squared gradient.
              H_new = beta * H + (1 - beta) * G_regularized * G_regularized

              // Compute the element-wise square-root of H_new. V_new will be element-wisely
              // divided by H_sqrt for a better update direction.
              H_sqrt = Sqrt(H_new) + epsilon

              // Compute learning-rate. Note that "alpha**T"/"beta**T" is alpha's/beta's T-th power.
              R_adjusted = T > 0 ? R * Sqrt(1 - beta**T) / (1 - alpha**T) : R

              // Compute new value of "X".
              X_new = X - R_adjusted * V_new / H_sqrt

              // Post-update regularization.
              X_final = (1 - norm_coefficient_post) * X_new

            If there are multiple inputs to be optimized, the pseudo code will be applied
            independently to each of them.


        Args:
            R: The initial learning rate.

            T: The update count of "X". It should be a scalar.

            inputs: (variadic, heterogeneous) The tensors to be optimized, followed by
                their respective gradients, followed by their respective accumulated
                gradients (aka momentum), followed by their respective accumulated
                squared gradients. For example, to optimize tensors "X_1" and "X_2,",
                the input list would be ["X_1", "X_2", gradient of "X_1", gradient of
                "X_2", accumulated gradient of "X_1", accumulated gradient of "X_2",
                accumulated squared gradient of "X_1", accumulated squared gradient of
                "X_2"].

            alpha: Coefficient of previously accumulated gradient in running average.
                Default to 0.9.

            beta: Coefficient of previously accumulated squared-gradient in running
                average. Default to 0.999.

            epsilon: Small scalar to avoid dividing by zero.

            norm_coefficient: Regularization coefficient of 0.5 * norm_coefficient *
                ||X||_2^2. Default to 0, which means no regularization.

            norm_coefficient_post: Regularization coefficient of 0.5 * norm_coefficient
                * ||X||_2^2. Default to 0, which means no regularization.
        """

        schema = get_schema("Adam", 1, "ai.onnx.preview.training")
        op = Op(self, "Adam", schema)
        return op(
            *self._prepare_inputs(schema, R, T, *inputs),
            alpha=alpha,
            beta=beta,
            epsilon=epsilon,
            norm_coefficient=norm_coefficient,
            norm_coefficient_post=norm_coefficient_post,
        )

    T1_Gradient = TypeVar(
        "T1_Gradient",
        BOOL,
        COMPLEX128,
        COMPLEX64,
        DOUBLE,
        FLOAT,
        FLOAT16,
        INT16,
        INT32,
        INT64,
        INT8,
        STRING,
        UINT16,
        UINT32,
        UINT64,
        UINT8,
    )

    T2_Gradient: TypeAlias = Union[DOUBLE, FLOAT, FLOAT16]

    def Gradient(
        self,
        *Inputs: T1_Gradient,
        xs: Sequence[str],
        y: str,
        zs: Optional[Sequence[str]] = None,
    ) -> T2_Gradient:
        r"""[🌐 ai.onnx.preview.training::Gradient(1)](https://onnx.ai/onnx/operators/onnx_aionnxpreviewtraining_Gradient.html#gradient-1 "Online Documentation")


        Gradient operator computes the partial derivatives of a specific tensor w.r.t.
        some other tensors. This operator is widely used in gradient-based training
        algorithms. To illustrate its use, let's consider a computation graph,

        ::

            X -----.
                   |
                   v
            W --> Conv --> H --> Gemm --> Y
                                  ^
                                  |
                                  Z



        , where W and Z are trainable tensors. Note that operators' attributes are
        omitted for the sake of simplicity. Let dY/dW (dY/dZ) be the gradient of
        Y with respect to W (Z). The user can compute gradient by inserting Gradient
        operator to form another graph shown below.

        ::

            W --> Conv --> H --> Gemm --> Y
            |      ^              ^
            |      |              |
            |      X              Z
            |      |              |
            |      |   .----------'
            |      |   |  (W/Z/X is the 1st/2nd/3rd input of Gradient as shown in
            |      |   |   "xs" followed by "zs")
            |      v   v
            '---> Gradient(xs=["W", "Z"], zs=["X"], y="Y")
                   |   |
                   |   '-----------------------------------> dY/dW (1st output of Gradient)
                   |
                   '---------------------------------------> dY/dZ (2nd output of Gradient)



        By definition, the tensor "y" is a function of independent variables in "xs"
        and "zs". Since we only compute the gradient of "y" w.r.t. the differentiable
        variables in "xs", this Gradient only outputs dY/dW and dY/dZ. Note that "H"
        cannot appear in "xs" and "zs". The reason is that "H" can be determined by
        tensors "W" and "X" and therefore "H" is not an independent variable.

        All outputs are optional. If needed, for example, user can assign an empty
        string to the 1st output name of that Gradient to skip the generation of dY/dW.
        Note that the concept of optional outputs can also be found in ONNX's RNN, GRU,
        and LSTM.

        Gradient operator can compute derivative against intermediate tensors. For
        example, the gradient of Y with respect to H can be done via

        ::

            W --> Conv --> H --> Gemm --> Y
                   ^       |      ^
                   |       |      |
                   X       |      Z
                   .-------'      |
                   |   .----------'
                   |   | (H/Z is the 1st/2nd input of Gradient as shown in "xs")
                   v   v
                  Gradient(xs=["H", "Z"], y="Y")
                   |   |
                   |   '-----------------------------------> dY/dH (1st output of Gradient)
                   |
                   '---------------------------------------> dY/dZ (2nd output of Gradient)



        It is possible to represent high-order differentiation using Gradient operators.
        For example, given the following linear model:

        ::

            W --> Gemm --> Y --> Loss --> O
                   ^              ^
                   |              |
                   X              L



        To compute the 2nd order derivative of O with respect to W (denoted by
        d^2O/dW^2), one can do

        ::

            W --> Gemm --> Y --> Loss --> O
            |      ^              ^
            |      |              |
            |      X .------------L
            |      | |            |
            |      | |            v
            +------+-+> Gradient(xs=["X", "W"], zs=["L"], y="O") ---> dO/dX (1st output of Gradient)
            |      | |    |
            |      | |    '---> dO/dW (2nd output of Gradient)
            |      v v
            '---> Gradient(xs=["X", "W"], zs=["L"], y="dO/dW") ---> d(dO/dW)dX (1st output of
                   |                                                  Gradient)
                   |
                   |
                   '---> d^2O/dW^2 (2nd output of Gradient)



        The tensors named in attributes "xs", "zs", and "y" define the differentiated
        computation graph, and the inputs to Gradient node define the values at
        which the gradient is computed. We can feed different tensors to the identified
        graph. For example, one can compute the gradient of Y with respect to H at
        a specific value of H, H_1, by providing that value as an input to the Gradient
        node.

        ::

            W --> Conv --> H --> Gemm --> Y
                   ^              ^
                   |              |
                   X              Z

                      Z_1 (2nd input of Gradient)
                       |
                       v
            H_1 --> Gradient(xs=["H", "Z"], y="Y") ---> dY/dH when H = H_1 and Y = Y_1.
                       |
                       '------------------------------> dY/dZ (2nd output of Gradient)



        When the inputs of Gradient are the tensors named in "xs" and "zs", the
        computation can be optimized. More specifically, intermediate variables in
        forward pass can be reused if the gradient is computed via reverse-mode
        auto-differentiation.



        Args:
            Inputs: (variadic, heterogeneous) The values fed into graph identified by
                the attributes. The i-th input is the value of the i-th tensor specified
                in the concatenated list of the attribute "xs" and the attribute  "zs".
                For example, if xs=["A", "B"] and zs=["C"], the first input is used as
                the value of symbol "A" and the 3rd input is substituted for all the
                occurrences of "C".

            xs: Input tensor names of the differentiated sub-graph. It contains only the
                necessary differentiated inputs of a (sub-)graph. Variables (usually
                called intermediate variables) that can be generated from inputs cannot
                be included in this attribute.

            y: The targeted tensor. It can be viewed as the output of the differentiated
                function. The attribute "xs" and attribute "zs" are the minimal
                independent variable set that determines the value of "y".

            zs: Input tensor names of the differentiated sub-graph. It contains only the
                necessary non-differentiated inputs of a (sub-)graph. Variables (usually
                called intermediate variables) that can be generated from inputs cannot
                be included in this attribute.
        """

        schema = get_schema("Gradient", 1, "ai.onnx.preview.training")
        op = Op(self, "Gradient", schema)
        return op(*self._prepare_inputs(schema, *Inputs), xs=xs, y=y, zs=zs)

    T1_Momentum = TypeVar("T1_Momentum", DOUBLE, FLOAT)

    T2_Momentum: TypeAlias = INT64

    T3_Momentum = TypeVar("T3_Momentum", DOUBLE, FLOAT)

    def Momentum(
        self,
        R: T1_Momentum,
        T: T2_Momentum,
        *inputs: T3_Momentum,
        alpha: float,
        beta: float,
        mode: str,
        norm_coefficient: float,
    ) -> T3_Momentum:
        r"""[🌐 ai.onnx.preview.training::Momentum(1)](https://onnx.ai/onnx/operators/onnx_aionnxpreviewtraining_Momentum.html#momentum-1 "Online Documentation")


            Compute one iteration of stochastic gradient update with momentum.
            This operator can conduct the optimization of multiple tensor variables.

            Let's define the behavior of this operator. As you can imagine, SG with momentum requires
            several parameters:

             - The learning-rate "R".
             - The update count "T". That is, the number of conducted training iterations. It should
               be zero in the first training iteration.
             - A L2-norm regularization coefficient "norm_coefficient".
             - A decay coefficient of previous accumulated gradient (i.e., momentum) "alpha".
             - The scaling coefficient of current gradient "beta".
             - An attribute to choose either standard momentum or Nesterov's momentum "mode" should
               be used.

            For the sake of simplicity, assume that there is only one tensor (called "X") to be optimized.
            Other necessary inputs are "X"'s gradient (called "G") and "X"'s momentum (called "V"). This
            Momentum operator maps all these inputs to the new value of "X" (called "X_new") and its new
            momentum (called "V_new").

            This operator supports two different momentum algorithms. Set the attribute "mode" to
            "nesterov" if Nesterov's momentum is desired. Otherwise, set the attribute "model" to
            "standard" to use standard momentum. Computation details are described subsequently.

            Let "+", "-", "*", and "/" are all element-wise operations with numpy-style broadcasting.

            Pseudo code for SG with standard momentum:

              // Add gradient of 0.5 * norm_coefficient * ||X||^2, where ||X|| is the sum of squared
              // values of all elements in X.
              G_regularized = norm_coefficient * X + G

              // In the first training iteration, beta should always be 1.
              beta_adjusted = T > 0 ? beta : 1

              // Compute the current momentum based on previous momentum and the current gradient.
              V_new = alpha * V + beta_adjusted * G_regularized

              // Update X.
              X_new = X - R * V_new

            Pseudo code for SG with Nesterov's momentum:

              // Add gradient of 0.5 * norm_coefficient * ||X||^2, where ||X|| is the sum of squared
              // values of all elements in X.
              G_regularized = norm_coefficient * X + G;

              // In the first training iteration, beta should always be 1.
              beta_adjusted = T > 0 ? beta : 1

              // Compute the current momentum based on previous momentum and the current gradient.
              V_new = alpha * V + beta_adjusted * G_regularized;

              // Compute final update direction and then update X.
              X_new = X - R * (G_regularized + alpha * V_new)

            If one assign this operators to optimize multiple inputs, for example, "X_1" and "X_2". The same
            pseudo code would be extended to handle all tensors jointly. More specifically, we can view "X" as a
            concatenation of "X_1" and "X_2" (of course, their gradient and accumulate gradient should
            be concatenated too) and then our pseudo code becomes applicable.


        Args:
            R: The learning rate.

            T: Update count of "X". It should be a scalar.

            inputs: (variadic, heterogeneous) It sequentially contains the current
                values of optimized tensors, then their gradient tensors, and finally
                their momentum tensors. For example, if two tensors "X_1" and "X_2" are
                optimized, The expected input list would be ["X_1", "X_2", gradient of
                "X_1", gradient of "X_2", momentum of "X_1", momentum of "X_2"].

            alpha: The decay factor of momentum. It should be a scalar.

            beta: The coefficient of gradient in computing new momentum. It should be a
                scalar.

            mode: Its value should be either "nesterov" or "standard". The value
                "nesterov" leads to the use of Nesterov's momentum while "standard"
                invokes stochastic gradient method using standard momentum

            norm_coefficient: Coefficient of 0.5 * norm_coefficient * ||X||^2.
        """

        schema = get_schema("Momentum", 1, "ai.onnx.preview.training")
        op = Op(self, "Momentum", schema)
        return op(
            *self._prepare_inputs(schema, R, T, *inputs),
            alpha=alpha,
            beta=beta,
            mode=mode,
            norm_coefficient=norm_coefficient,
        )
