
    ёis7                    <   S SK Jr  S SKJr  S SKrS SKJr  S SKJr  SSKJ	r	  SSK
Jr  SS	KJr  SS
KJr  \(       a  S SKJr  / r\" SS/5        S       SS jj5       r S         SS jjr\" SS/5            S                 SS jj5       rg)    )annotations)TYPE_CHECKINGN)_C_ops)param_one_alias   )check_variable_and_dtype)LayerHelper)Variable)in_dynamic_or_pir_mode)Tensorxinputc                   [        U[        R                  R                  5      (       d  US:X  a  U R	                  5       S-   n[        5       (       a  [        R                  " X5      $ [        U SSS/S5        [        S0 [        5       D6nUR                  SS9n[        U[        5      (       d
  S	U 0nUS
S.nOSUl        XS.nSS
0nUR                  SUUSU0SS9  U$ )am	  

The operator converts each id in the input `x` to an one-hot vector with a
`num_classes` length. The value in the vector dimension corresponding to the id
is 1, and the value in the remaining dimension is 0.

The shape of output Tensor is generated by appending `num_classes` dimension
behind the last dimension of the `x` shape.

.. code-block:: text

    Example 1:

    input:
        x.shape = [4]
        x.data = [1, 1, 3, 0]
        num_classes = 4

    output:
        Out.shape = [4, 4]
        Out.data = [[0., 1., 0., 0.],
                    [0., 1., 0., 0.],
                    [0., 0., 0., 1.],
                    [1., 0., 0., 0.]]

    Example 2:

    input:
        x.shape = [4]
        x.data = [1, 1, 5, 0]
        num_classes = 4

    output: Throw an exception for Illegal value
        The second dimension in X is 5, which is greater than num_classes,
        so it throws an exception.


.. note::
    Alias Support: The parameter name ``input`` can be used as an alias for ``x``.
    For example, ``one_hot(input=tensor_x, ...)`` is equivalent to ``one_hot(x=tensor_x, ...)``.


Args:
    x(Tensor): Tensor with shape :math:`[N_1, N_2, ..., N_k]` ,
        which contains at least one dimension. The data type is int32 or int64.
        alias: ``input``.
    num_classes(int): An integer defining the `num_classes` of the one hot dimension. If input `x`
        is word id, `num_classes` is generally the dictionary size. Default value: -1.
    name(str|None, optional): For detailed information, please refer
       to :ref:`api_guide_Name`. Usually name is no need to set and
       None by default.

Returns:
    Tensor, The one-hot representations of `x`. A Tensor with type float32.

Examples:
    .. code-block:: pycon

        >>> import paddle
        >>> # Correspond to the first example above, where label.shape is 4 and one_hot_label.shape is [4, 4].
        >>> label = paddle.to_tensor([1, 1, 3, 0], dtype='int64')
        >>> print(label.shape)
        paddle.Size([4])
        >>> one_hot_label = paddle.nn.functional.one_hot(label, num_classes=4)
        >>> print(one_hot_label.shape)
        paddle.Size([4, 4])
        >>> print(one_hot_label)
        Tensor(shape=[4, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
               [[0., 1., 0., 0.],
                [0., 1., 0., 0.],
                [0., 0., 0., 1.],
                [1., 0., 0., 0.]])

   r   int32int64
one_hot_v2float32)dtypeXF)depthallow_out_of_rangeT)r   depth_tensorr   Out)typeinputsattrsoutputsstop_gradient)r   )
isinstancepaddlepirValuemaxr   r   one_hotr   r	   locals"create_variable_for_type_inferencer
   r    	append_op)r   num_classesnamehelperone_hot_outr   r   s          Z/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/nn/functional/input.pyr&   r&   !   s    ` k6::#3#3449Jeegk~~a-- Ggw-?N6VX6??i?P+x001XF)GE(,K%:F)51EK( 	 	
     c                   [         R                  " S5         [         R                  " U 5      n[         R                  " X5      n[         R                  " XSSSS9nXb:  nX&S-   -  n[         R
                  " Xx[         R                  " U5      5      n[         R                  " X5      nXX-  n	[         R                  " XU	SS9  UsSSS5        $ ! , (       d  f       g= f)at  
Renorm the weight of embedding with respect to the provided :attr:`max_norm` and :attr:`norm_type` .

Note:
    In the dynamic graph mode, the input weight will be updated in-place, and the return value will be the changed weight.

Args:
    x(Tensor): A Tensor with type int32/int64, which contains the id information. The value of the input id should
        satisfy :math:`0<= id < weight.shape[0]` .
    weight (Tensor): The weight. A Tensor with shape of lookup table parameter. It should have two elements which
        indicates the size of the dictionary of embeddings and the size of each embedding vector respectively.
    max_norm(float): The maximum norm for each embedding vector.
    norm_type(float, optional): The p of the p-norm to compute for the max_norm option. Default: 2.0.

Returns:
    Tensor, The updated weight. The data type is the same as :attr:`weight`.
Fr   T)paxiskeepdimgHz>)	overwriteN)	r"   set_grad_enableduniqueindex_selectnormwhere	ones_like	expand_asscatter_)
r   weightmax_norm	norm_typeunique_xselected_rowsr8   maskscaleupdated_rowss
             r.   embedding_renorm_rE      s    ( 
	 	 	'==#++F={{=AtL4K(T&*:*:5*AB  6$,,$G 
(	'	's   B*C
Cc           
        Uc  SOUS:  a  UOUR                   S   U-   nUR                   S   S:w  aQ  X!R                   S   :  d  X!R                   S   * :  a,  [        SUR                   S    SUR                   S    S35      eU(       a  UR                  S:w  a
  [        XX4S9nU(       a  U(       a  [	        S5      e[        5       (       a  [        R                  " XU5      $ [        S0 [        5       D6nUR                  S	S
9n	[        U S/ SQS5        UR                  U	5      n
UR                  SXS.SU
0SU0S9  U
$ [        5       (       a  [        R                  " XX%5      $ [        S0 [        5       D6nUR                  S	S
9n	[        U S/ SQS5        SnU=(       a    U(       + nUR                  U	5      n
UR                  SXS.SU
0UUUUS.S9  U
$ )a  
Used to lookup embeddings vector of ids provided by :attr:`x` .

The shape of output Tensor is generated by appending the last dimension of the input Tensor shape
with embedding size.

Note:
    The id in :attr:`x` must satisfy :math:`0 <= id < weight.shape[0]` ,
    otherwise the program will throw an exception and exit.

.. code-block:: text

        x is a Tensor.
            padding_idx = -1
            x.data = [[1, 3], [2, 4], [4, 127]]
            x.shape = [3, 2]
            weight.shape = [128, 16]
        output is a Tensor:
            out.shape = [3, 2, 16]
            out.data = [[[0.129435295, 0.244512452, ..., 0.436322452],
                        [0.345421456, 0.524563927, ..., 0.144534654]],
                        [[0.345249859, 0.124939536, ..., 0.194353745],
                        [0.945345345, 0.435394634, ..., 0.435345365]],
                        [[0.945345345, 0.435394634, ..., 0.435345365],
                        [0.0,         0.0,         ..., 0.0        ]]]  # padding data

        The input padding_idx is less than 0, it is automatically converted to padding_idx = -1 + 128 = 127
        It will pad all-zero data when id is 127.

.. note::
    Alias Support: The parameter name ``input`` can be used as an alias for ``x``.
    For example, ``embedding(input=tensor_x, ...)`` is equivalent to ``embedding(x=tensor_x, ...)``.

Args:
    x(Tensor): A Tensor with type int32/int64, which contains the id information. The value of the input id should
        satisfy :math:`0 <= id < weight.shape[0]` .
        alias: ``input``.
    weight (Tensor): The weight. A Tensor with shape of lookup table parameter. It should have two elements which
        indicates the size of the dictionary of embeddings and the size of each embedding vector respectively.
    sparse(bool, optional): The flag indicating whether to use sparse update. This parameter only
        affects the performance of the backwards gradient update. It is recommended to set
        True because sparse update is faster. But some optimizers does not support sparse update,
        such as :ref:`api_paddle_optimizer_adadelta_Adadelta` , :ref:`api_paddle_optimizer_adamax_Adamax` , :ref:`api_paddle_optimizer_lamb_Lamb`.
        In these cases, sparse must be False. Default: False.
    padding_idx(int|None, optional): padding_idx needs to be in the interval [-weight.shape[0], weight.shape[0]).
        If :math:`padding\_idx < 0`, the :math:`padding\_idx` will automatically be converted
        to :math:`weight.shape[0] + padding\_idx` . It will output all-zero padding data whenever lookup
        encounters :math:`padding\_idx` in id. And the padding data will not be updated while training.
        If set None, it makes no effect to output. Default: None.
    max_norm(float, optional): If provided, will renormalize the embedding vectors to have a norm larger than
        :attr:`max\_norm` . It will inplace update the input embedding weight in dynamic graph mode. Default: None.
    norm_type(float, optional): The p of the p-norm to compute for the max_norm option. Default: 2.0.
    scale_grad_by_freq(bool, optional): Indicating whether to scale the gradients by the inverse frequency of the
        word ids in input `x`. Default: False.
    name(str|None, optional): For detailed information, please refer
       to :ref:`api_guide_Name`. Usually name is no need to set and
       None by default.

Returns:
    Tensor, Embedding Tensor mapped by x. The data type is the same as :attr:`weight`.

Examples:

    .. code-block:: pycon

        >>> import paddle
        >>> import paddle.nn as nn

        >>> x0 = paddle.arange(3, 6).reshape((3, 1)).astype(paddle.int64)
        >>> w0 = paddle.full(shape=(10, 3), fill_value=2).astype(paddle.float32)

        >>> x = paddle.to_tensor(x0, stop_gradient=False)
        >>> print(x.numpy())
        [[3]
         [4]
         [5]]
        >>> print(x.shape)
        paddle.Size([3, 1])

        >>> w = paddle.to_tensor(w0, stop_gradient=False)
        >>> print(w.numpy())
        [[2. 2. 2.]
         [2. 2. 2.]
         [2. 2. 2.]
         [2. 2. 2.]
         [2. 2. 2.]
         [2. 2. 2.]
         [2. 2. 2.]
         [2. 2. 2.]
         [2. 2. 2.]
         [2. 2. 2.]]
        >>> print(w.shape)
        paddle.Size([10, 3])

        >>> emb = nn.functional.embedding(x=x, weight=w, sparse=True, name="embedding")
        >>> print(emb.numpy())
        [[[2. 2. 2.]]
         [[2. 2. 2.]]
         [[2. 2. 2.]]]
        >>> print(emb.shape)
        paddle.Size([3, 1, 3])

r   r   zpadding_idx must be within [-z, ))r>   r?   z>scale_grad_by_freq = True is not supported with sparse update.embedding_with_scaled_gradientr=   )input_param_namer   )uint8int8int16r   r   )r   r=   outpadding_idx)r   r   r   r   	embeddingFlookup_table_v2)IdsWr   )	is_sparseis_distributedremote_prefetchrN   )rH   )rO   )shape
ValueErrorsizerE   AttributeErrorr   r   rH   r	   r'   input_dtyper   r(   r)   rO   )r   r=   rN   r>   r?   sparsescale_grad_by_freqr+   r,   r   tmprT   rU   s                r.   rO   rO      s   h  	 '!+K&,,q/K2O	  ||A!||A&+a8H*H+FLLO+<Bv||A>OqQ
 	
 FKK1$"
  P  "##88KPP NVXNF&&&AE$<0	 ;;EBC51$k2	   J!####A{CC 99F&&&AE$<	 #N$=n*<O;;EBC& .!'&4'6#.		  
 Jr/   )r   N)r   r   r*   intr+   
str | Nonereturnr   )       @)
r   r   r=   r   r>   floatr?   rb   r`   r   )NNra   FFN)r   r   r=   r   rN   z
int | Noner>   zfloat | Noner?   rb   r[   boolr\   rc   r+   r_   r`   r   )
__future__r   typingr   r"   r   paddle.utils.decorator_utilsr   base.data_feederr   base.layer_helperr	   common_ops_importr
   	frameworkr   r   __all__r&   rE   rO    r/   r.   <module>rm      sD   #     8 8 , ) /
 #w  ggg g 	g !gV DG).;@B #w  #!$}}} } 	}
 } } } } } !}r/   