
    Ǆg                     `    d dl Z d dl mZ d dlmZ d dlmZ d dlmZmZm	Z	 dgZ
 G d de      Zy)    N)nan)constraints)Distribution)lazy_propertylogits_to_probsprobs_to_logitsCategoricalc                   <    e Zd ZdZej
                  ej                  dZdZd fd	Z	d fd	Z
d Z ej                  dd      d	        Zed
        Zed        Zed        Zed        Zed        Zed        Z ej.                         fdZd Zd ZddZ xZS )r	   a  
    Creates a categorical distribution parameterized by either :attr:`probs` or
    :attr:`logits` (but not both).

    .. note::
        It is equivalent to the distribution that :func:`torch.multinomial`
        samples from.

    Samples are integers from :math:`\{0, \ldots, K-1\}` where `K` is ``probs.size(-1)``.

    If `probs` is 1-dimensional with length-`K`, each element is the relative probability
    of sampling the class at that index.

    If `probs` is N-dimensional, the first N-1 dimensions are treated as a batch of
    relative probability vectors.

    .. note:: The `probs` argument must be non-negative, finite and have a non-zero sum,
              and it will be normalized to sum to 1 along the last dimension. :attr:`probs`
              will return this normalized value.
              The `logits` argument will be interpreted as unnormalized log probabilities
              and can therefore be any real number. It will likewise be normalized so that
              the resulting probabilities sum to 1 along the last dimension. :attr:`logits`
              will return this normalized value.

    See also: :func:`torch.multinomial`

    Example::

        >>> # xdoctest: +IGNORE_WANT("non-deterministic")
        >>> m = Categorical(torch.tensor([ 0.25, 0.25, 0.25, 0.25 ]))
        >>> m.sample()  # equal probability of 0, 1, 2, 3
        tensor(3)

    Args:
        probs (Tensor): event probabilities
        logits (Tensor): event log probabilities (unnormalized)
    )probslogitsTc                 X   |d u |d u k(  rt        d      |:|j                         dk  rt        d      ||j                  dd      z  | _        n9|j                         dk  rt        d      ||j	                  dd      z
  | _        || j                  n| j
                  | _        | j                  j                         d   | _        | j                  j                         dkD  r| j                  j                         d d nt        j                         }t        | 5  ||	       y )
Nz;Either `probs` or `logits` must be specified, but not both.   z3`probs` parameter must be at least one-dimensional.T)keepdimz4`logits` parameter must be at least one-dimensional.)dimr   validate_args)
ValueErrorr   sumr   	logsumexpr   _paramsize_num_events
ndimensiontorchSizesuper__init__)selfr   r   r   batch_shape	__class__s        g/home/mcse/projects/flask_80/flask-venv/lib/python3.12/site-packages/torch/distributions/categorical.pyr   zCategorical.__init__5   s   TMv~.M  yy{Q !VWW2t!<<DJzz|a !WXX 6#3#3D#3#IIDK$)$5djj4;;;;++-b1'+{{'='='?!'CDKKs# 	 	MB    c                    | j                  t        |      }t        j                  |      }|t        j                  | j                  f      z   }d| j
                  v r1| j                  j                  |      |_        |j                  |_        d| j
                  v r1| j                  j                  |      |_	        |j                  |_        | j                  |_        t        t        |/  |d       | j                  |_        |S )Nr   r   Fr   )_get_checked_instancer	   r   r   r   __dict__r   expandr   r   r   r   _validate_args)r   r    	_instancenewparam_shaper!   s        r"   r'   zCategorical.expandJ   s    ((i@jj-!EJJ0@0@/B$CCdmm#

))+6CICJt}}$++K8CJCJ**k3(E(J!00
r#   c                 :     | j                   j                  |i |S N)r   r*   )r   argskwargss      r"   _newzCategorical._newY   s    t{{///r#   r   )is_discrete	event_dimc                 H    t        j                  d| j                  dz
        S )Nr   r   )r   integer_intervalr   r   s    r"   supportzCategorical.support\   s     ++At/?/?!/CDDr#   c                 ,    t        | j                        S r-   )r   r   r5   s    r"   r   zCategorical.logits`   s    tzz**r#   c                 ,    t        | j                        S r-   )r   r   r5   s    r"   r   zCategorical.probsd   s    t{{++r#   c                 6    | j                   j                         S r-   )r   r   r5   s    r"   r+   zCategorical.param_shapeh   s    {{!!r#   c                     t        j                  | j                         t        | j                  j
                  | j                  j                        S Ndtypedevicer   full_extended_shaper   r   r=   r>   r5   s    r"   meanzCategorical.meanl   <    zz  "**""::$$	
 	
r#   c                 :    | j                   j                  d      S )Nr   )axis)r   argmaxr5   s    r"   modezCategorical.modeu   s    zz  b ))r#   c                     t        j                  | j                         t        | j                  j
                  | j                  j                        S r;   r?   r5   s    r"   variancezCategorical.variancey   rC   r#   c                 J   t        |t        j                        st        j                  |      }| j                  j	                  d| j
                        }t        j                  ||j                         d      j                  }|j	                  | j                  |            S )Nr   T)

isinstancer   r   r   reshaper   multinomialnumelTrA   )r   sample_shapeprobs_2d
samples_2ds       r"   samplezCategorical.sample   sy    ,

3 ::l3L::%%b$*:*:;&&x1C1C1EtLNN
!!$"6"6|"DEEr#   c                    | j                   r| j                  |       |j                         j                  d      }t	        j
                  || j                        \  }}|dd df   }|j                  d|      j                  d      S )Nr   .r   )	r(   _validate_samplelong	unsqueezer   broadcast_tensorsr   gathersqueeze)r   valuelog_pmfs      r"   log_probzCategorical.log_prob   sv    !!%(

&&r*00Dwc2A2g~~b%(0044r#   c                     t        j                  | j                  j                        j                  }t        j
                  | j                  |      }|| j                  z  }|j                  d       S )N)minr   )r   finfor   r=   r_   clampr   r   )r   min_realr   p_log_ps       r"   entropyzCategorical.entropy   sS    ;;t{{00155T[[h74::%Br#   c                 &   | j                   }t        j                  |t        j                  | j                  j
                        }|j                  ddt        | j                        z  z         }|r|j                  d| j                  z         }|S )Nr<   )r   )r   )
r   r   arangerV   r   r>   viewlen_batch_shaper'   )r   r'   
num_eventsvaluess       r"   enumerate_supportzCategorical.enumerate_support   sq    %%
j

4;;CUCUVUTC0A0A,B%BBC]]54+<+<#<=Fr#   )NNNr-   )T)__name__
__module____qualname____doc__r   simplexreal_vectorarg_constraintshas_enumerate_supportr   r'   r0   dependent_propertyr6   r   r   r   propertyr+   rB   rG   rI   r   r   rS   r]   rd   rl   __classcell__)r!   s   @r"   r	   r	      s    $J !, 3 3{?V?VWO C*0 $[##BE CE + + , , " " 
 
 * * 
 
 #-%**, F5 r#   )r   r   torch.distributionsr    torch.distributions.distributionr   torch.distributions.utilsr   r   r   __all__r	    r#   r"   <module>r}      s.      + 9 U U /Q, Qr#   