
    Αin?                    p   S SK Jr  S SKJr  S SKrS SKrS SKJrJ	r	  S SK
Jr  S SKJr  S SKJr  S SKJrJrJr  \(       a  S S	KJr  S S
KJr  S SKJr  \R2                  " \R4                  5      R6                  \R2                  " \R8                  5      R6                  S.rS r " S S\R>                  5      r g)    )annotations)TYPE_CHECKINGN)
check_typeconvert_dtype)Variable)exponential_family)in_dynamic_mode) binary_cross_entropy_with_logitssigmoidsoftplus)Sequence)Tensor)_DTypeLiteral)float32float64c                z    [         R                  U5      n[        R                  " XSU-
  S9R	                  U5      $ )zClip probs from [0, 1] to (0, 1) with ``eps``.

Args:
    probs (Tensor): probs of Bernoulli.
    dtype (str): data type.

Returns:
    Tensor: Clipped probs.
   )minmax)EPSgetpaddleclipastype)probsdtypeepss      ]/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/distribution/bernoulli.py_clip_probsr   ,   s1     ''%.C;;u1s73::5AA    c                     ^  \ rS rSr% SrS\S'   S\S'   S\S'   S\S	'   SSU 4S
 jjjr\SS j5       r\SS j5       r	/ 4SS jjr
/ S4     SS jjrSS jrSS jrSS jrSS jrSS jrSrU =r$ )	Bernoulli:   a  Bernoulli distribution parameterized by ``probs``, which is the probability of value 1.

In probability theory and statistics, the Bernoulli distribution, named after Swiss
mathematician Jacob Bernoulli, is the discrete probability distribution of a random
variable which takes the value 1 with probability ``p`` and the value 0 with
probability ``q=1-p``.

The probability mass function of this distribution, over possible outcomes ``k``, is

.. math::

    {\begin{cases}
    q=1-p & \text{if }value=0 \\
    p & \text{if }value=1
    \end{cases}}

Args:
    probs (float|Tensor): The ``probs`` input of Bernoulli distribution. The data type is float32 or float64. The range must be in [0, 1].
    name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.

Examples:

    .. code-block:: python

        >>> import paddle
        >>> from paddle.distribution import Bernoulli

        >>> # init `probs` with a float
        >>> rv = Bernoulli(probs=0.3)

        >>> print(rv.mean)
        Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
        0.30000001)

        >>> print(rv.variance)
        Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
        0.21000001)

        >>> print(rv.entropy())
        Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
        0.61086434)
strnamer   r   logitsr   r   c                X  > U=(       d    SU l         [        5       (       d;  [        US[        [        [
        R                  R                  4U R                   5        U R                  U5      (       a!  Xl	        [        UR                  5      U l        O2U R                  U5      u  U l	        [
        R                  " 5       U l        [        U R                  U R                  5      U l	        U R                  U R                  SS9U l        ["        TU ]I  U R                  R&                  SS9  g )Nr"   r   T)	is_binary )batch_shapeevent_shape)r%   r	   r   floatr   r   pirValue_validate_argsr   r   r   
_to_tensorget_default_dtyper   _probs_to_logitsr&   super__init__shape)selfr   r%   	__class__s      r   r4   Bernoulli.__init__k   s    'K	  &**"2"23			 u%%J&u{{3DJ??51LTZ113DJ !TZZ8
++DJJ$+GTZZ%5%52Fr    c                    U R                   $ )zRMean of Bernoulli distribution.

Returns:
    Tensor: Mean value of distribution.
)r   r6   s    r   meanBernoulli.mean   s     zzr    c                ^    [         R                  " U R                  SU R                  -
  5      $ )zZVariance of Bernoulli distribution.

Returns:
    Tensor: Variance value of distribution.
r   )r   multiplyr   r:   s    r   varianceBernoulli.variance   s!     tzzA

N<<r    c           	        U R                   S-   n[        5       (       dE  [        US[        R                  [
        [        [        [        R                  R                  4U5        [        U[        5      (       a  UO
[        U5      nU R                  U5      n[        R                  " 5          [        R                  " U R                  R!                  U5      US9sSSS5        $ ! , (       d  f       g= f)a0  Sample from Bernoulli distribution.

Args:
    shape (Sequence[int], optional): Sample shape.

Returns:
    Tensor: Sampled data with shape `sample_shape` + `batch_shape` + `event_shape`.

Examples:

    .. code-block:: pycon

        >>> import paddle
        >>> from paddle.distribution import Bernoulli

        >>> rv = Bernoulli(paddle.full([1], 0.3))
        >>> print(rv.sample([100]).shape)
        paddle.Size([100, 1])

        >>> rv = Bernoulli(paddle.to_tensor(0.3))
        >>> print(rv.sample([100]).shape)
        paddle.Size([100])

        >>> rv = Bernoulli(paddle.to_tensor([0.3, 0.5]))
        >>> print(rv.sample([100]).shape)
        paddle.Size([100, 2])

        >>> rv = Bernoulli(paddle.to_tensor([0.3, 0.5]))
        >>> print(rv.sample([100, 2]).shape)
        paddle.Size([100, 2, 2])
_sampler5   r%   N)r%   r	   r   npndarrayr   listtupler   r-   r.   
isinstance_extend_shapeno_grad	bernoullir   expand)r6   r5   r%   s      r   sampleBernoulli.sample   s    @ yy9$  XtUFJJ4D4DE	 $E511uU|""5)^^##DJJ$5$5e$<4H s   ,.C$$
C2g      ?c           
     $   U R                   S-   n[        5       (       dX  [        US[        R                  [
        [        R                  R                  [        [        4U5        [        US[        4U5        [        U[        5      (       a  UO
[        U5      nU R                  U5      n[        R                  " SX R                  S9nU R                   R#                  U5      n[        R$                  " XR                  S9n[        R&                  " [        R(                  " [        R*                  " UR-                  5       U* R/                  5       5      [        R*                  " UR-                  5       U* R/                  5       5      5      U5      $ )a
  Sample from Bernoulli distribution (reparameterized).

The `rsample` is a continuously approximate of Bernoulli distribution reparameterized sample method.
[1] Chris J. Maddison, Andriy Mnih, and Yee Whye Teh. The Concrete Distribution: A Continuous Relaxation of Discrete Random Variables. 2016.
[2] Eric Jang, Shixiang Gu, and Ben Poole. Categorical Reparameterization with Gumbel-Softmax. 2016.

Note:
    `rsample` need to be followed by a `sigmoid`, which converts samples' value to unit interval (0, 1).

Args:
    shape (Sequence[int], optional): Sample shape.
    temperature (float): temperature for rsample, must be positive.

Returns:
    Tensor: Sampled data with shape `sample_shape` + `batch_shape` + `event_shape`.

Examples:

    .. code-block:: pycon

        >>> import paddle
        >>> paddle.seed(1)
        >>> from paddle.distribution import Bernoulli

        >>> rv = Bernoulli(paddle.full([1], 0.3))
        >>> print(rv.sample([100]).shape)
        paddle.Size([100, 1])

        >>> rv = Bernoulli(0.3)
        >>> print(rv.rsample([100]).shape)
        paddle.Size([100])

        >>> rv = Bernoulli(paddle.to_tensor([0.3, 0.5]))
        >>> print(rv.rsample([100]).shape)
        paddle.Size([100, 2])

        >>> rv = Bernoulli(paddle.to_tensor([0.3, 0.5]))
        >>> print(rv.rsample([100, 2]).shape)
        paddle.Size([100, 2, 2])

        >>> # `rsample` has to be followed by a `sigmoid`
        >>> rv = Bernoulli(0.3)
        >>> rsample = rv.rsample([3])
        >>> rsample_sigmoid = paddle.nn.functional.sigmoid(rsample)
        >>> print(rsample)
        Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
        [-1.46112013, -0.01239836, -1.32765460])
        >>> print(rsample_sigmoid)
        Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
        [0.18829606, 0.49690047, 0.20954758])

        >>> # The smaller the `temperature`, the distribution of `rsample` closer to `sample`, with `probs` of 0.3.
        >>> print(
        ...     paddle.nn.functional.sigmoid(
        ...         rv.rsample(
        ...             [1000],
        ...             temperature=1.0,
        ...         )
        ...     ).sum()
        ... )
        >>> # doctest: +SKIP('output will be different')
        Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
        365.63122559)
        >>> # doctest: -SKIP

        >>> print(
        ...     paddle.nn.functional.sigmoid(
        ...         rv.rsample(
        ...             [1000],
        ...             temperature=0.1,
        ...         )
        ...     ).sum()
        ... )
        Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
        320.15057373)
_rsampler5   temperaturer)   )r5   
fill_valuer   )r   )r%   r	   r   rD   rE   r   r   r-   r.   rF   rG   r,   rH   rI   fullr   r   rL   randdivideaddsubtractloglog1p)r6   r5   rQ   r%   r   uniformss         r   rsampleBernoulli.rsample   s'   ^ yy:%  Xvzz'7'7uE	 	 $E511uU|""5)kkJJ
 

!!%(;;uJJ7}}JJ(0A0A0CD		uf^^-=> 
 	
r    c                   U R                   S-   n[        5       (       d,  [        US[        [        R
                  R                  4U5        U R                  U R                  U5      n[        R                  " U R                  U/5      u  p1[        R                  " U5      n[        R                  " U5      n[        R                  " US:  U[        R                  " US:  [        R                  " XS5      U5      US9$ )aj  Cumulative distribution function(CDF) evaluated at value.

.. math::

    { \begin{cases}
    0 & \text{if } value \lt  0 \\
    1 - p & \text{if } 0 \leq value \lt  1 \\
    1 & \text{if } value \geq 1
    \end{cases}
    }

Args:
    value (Tensor): Value to be evaluated.

Returns:
    Tensor: CDF evaluated at value.

Examples:

    .. code-block:: python

        >>> import paddle
        >>> from paddle.distribution import Bernoulli

        >>> rv = Bernoulli(0.3)
        >>> print(rv.cdf(paddle.to_tensor([1.0])))
        Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
        [1.])
_cdfvaluer   r   rC   )r%   r	   r   r   r   r-   r.   _check_values_dtype_in_probsr   broadcast_tensors
zeros_like	ones_likewhererW   )r6   r_   r%   r   zerosoness         r   cdfBernoulli.cdf3  s    < yy6!  ug&**2B2B'CTJ11$**eD//U0CD!!%(&||AILLFOOD$@$G	
 	
r    c                .   U R                   S-   n[        5       (       d,  [        US[        [        R
                  R                  4U5        U R                  U R                  U5      n[        R                  " U R                  U/5      u  p1[        X1SUS9* $ )a  Log of probability density function.

Args:
    value (Tensor): Value to be evaluated.

Returns:
    Tensor: Log of probability density evaluated at value.

Examples:

    .. code-block:: python

        >>> import paddle
        >>> from paddle.distribution import Bernoulli

        >>> rv = Bernoulli(0.3)
        >>> print(rv.log_prob(paddle.to_tensor([1.0])))
        Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
        [-1.20397282])
	_log_probr_   none	reductionr%   )r%   r	   r   r   r   r-   r.   r`   r   ra   r&   r
   )r6   r_   r%   r&   s       r   log_probBernoulli.log_probb  s    * yy;&  ug&**2B2B'CTJ11$**eD00$++u1EF0V$
 
 	
r    c                    U R                   S-   n[        5       (       d,  [        US[        [        R
                  R                  4U5        U R                  U5      R                  US9$ )aE  Probability density function(PDF) evaluated at value.

.. math::

    { \begin{cases}
        q=1-p & \text{if }value=0 \\
        p & \text{if }value=1
        \end{cases}
    }

Args:
    value (Tensor): Value to be evaluated.

Returns:
    Tensor: PDF evaluated at value.

Examples:

    .. code-block:: python

        >>> import paddle
        >>> from paddle.distribution import Bernoulli

        >>> rv = Bernoulli(0.3)
        >>> print(rv.prob(paddle.to_tensor([1.0])))
        Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
        [0.29999998])
_probr_   rC   )	r%   r	   r   r   r   r-   r.   rn   exp)r6   r_   r%   s      r   probBernoulli.prob  sU    : yy7"  ug&**2B2B'CTJ}}U#''T'22r    c                `    U R                   S-   n[        U R                  U R                  SUS9$ )a  Entropy of Bernoulli distribution.

.. math::

    {
        entropy = -(q \log q + p \log p)
    }

Returns:
    Tensor: Entropy of distribution.

Examples:

    .. code-block:: python

        >>> import paddle
        >>> from paddle.distribution import Bernoulli

        >>> rv = Bernoulli(0.3)
        >>> print(rv.entropy())
        Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
        0.61086434)
_entropyrk   rl   )r%   r
   r&   r   )r6   r%   s     r   entropyBernoulli.entropy  s0    0 yy:%/KKvD
 	
r    c           
     F   U R                   S-   n[        5       (       d  [        US[        U5        U R                  nUR                  n[        U* 5      * n[        U* 5      * n[        U5      n[        U* 5      n[        U5      * n	[        U5      * n
[        R                  " [        R                  " [        R                  " XW5      [        R                  " Xg5      5      [        R                  " [        R                  " X5      [        R                  " X5      5      5      $ )an  The KL-divergence between two Bernoulli distributions.

.. math::

    {
        KL(a || b) = p_a \log(p_a / p_b) + (1 - p_a) \log((1 - p_a) / (1 - p_b))
    }

Args:
    other (Bernoulli): instance of Bernoulli.

Returns:
    Tensor: kl-divergence between two Bernoulli distributions.

Examples:

    .. code-block:: python

        >>> import paddle
        >>> from paddle.distribution import Bernoulli

        >>> rv = Bernoulli(0.3)
        >>> rv_other = Bernoulli(0.7)

        >>> print(rv.kl_divergence(rv_other))
        Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
        0.33891910)
_kl_divergenceother)r%   r	   r   r"   r&   r   r   r   rV   rW   r>   )r6   r{   r%   a_logitsb_logitslog_palog_pbpaone_minus_palog_one_minus_palog_one_minus_pbs              r   kl_divergenceBernoulli.kl_divergence  s    : yy++  ugy$7;;<<H9%%H9%%Xy)$X..$X..zzOO+V__V-H OO 0? 0?	
 	
r    )r   r&   r%   r   )N)r   zfloat | Tensorr%   z
str | NonereturnNone)r   r   )r5   Sequence[int]r   r   )r5   r   rQ   r,   r   r   )r_   r   r   r   )r{   r"   r   r   )__name__
__module____qualname____firstlineno____doc____annotations__r4   propertyr;   r?   rM   r[   rg   rn   rs   rw   r   __static_attributes____classcell__)r7   s   @r   r"   r"   :   s    )V IMNG G0   = = -/ -I` &(cm
"m
6;m
	m
^-
^
>!3F
<5
 5
r    r"   )!
__future__r   typingr   numpyrD   r   paddle.base.data_feederr   r   paddle.base.frameworkr   paddle.distributionr   paddle.frameworkr	   paddle.nn.functionalr
   r   r   collections.abcr   r   paddle._typing.dtype_liker   finfor   r   r   r   r   ExponentialFamilyr"   r)   r    r   <module>r      s    #     = * 2 ,  (7 ||FNN+//||FNN+//B}
"44 }
r    