
    קg[0                     z    d dl Z d dlmZmZmZ d dlmZ d dlZd dlm	Z	 d dl
mZ d dlmZ dgZ G d d          ZdS )	    N)AnyDictOptional)
deprecated)constraints)lazy_property)_sizeDistributionc                       e Zd ZdZdZdZdZededdfd            Z	 e
j                     e
j                    dfde
j        d	e
j        d
ee         f fdZd'defdZede
j        fd            Zede
j        fd            Zedeeej        f         fd            Zedee         fd            Zede
j        fd            Zede
j        fd            Zede
j        fd            Zede
j        fd            Z e
j                    fdede
j        fdZ e
j                    fdede
j        fdZ  e!de"          de#de
j        fd            Z$de
j        de
j        fdZ%de
j        de
j        fdZ&de
j        de
j        fdZ'd(dede
j        fd Z(de
j        fd!Z)de
j        fd"Z* e
j                    fdede
j        fd#Z+de
j        ddfd$Z,d'd%Z-defd&Z. xZ/S ))r
   zP
    Distribution is the abstract base class for probability distributions.
    FTvaluereturnNc                 4    | dvrt           | t          _        dS )a  
        Sets whether validation is enabled or disabled.

        The default behavior mimics Python's ``assert`` statement: validation
        is on by default, but is disabled if Python is run in optimized mode
        (via ``python -O``). Validation may be expensive, so you may want to
        disable it once a model is working.

        Args:
            value (bool): Whether to enable validation.
        )TFN)
ValueErrorr
   _validate_args)r   s    \/var/www/html/ai-engine/env/lib/python3.11/site-packages/torch/distributions/distribution.pyset_default_validate_argsz&Distribution.set_default_validate_args   s#     %%&+###    batch_shapeevent_shapevalidate_argsc                    || _         || _        ||| _        | j        r>	 | j        }n4# t          $ r' i }t          j        | j         ddz   dz              Y nw xY w|                                D ]\  }}t          j
        |          r|| j        vr1t          t          t          |           |          t                    rTt          | |          }|                    |          }|                                s_t%          d| dt          |          j         dt)          |j                   dt-          |            dt-          |           d	|           t/                                                       d S )
Nz$ does not define `arg_constraints`. zAPlease set `arg_constraints = {}` or initialize the distribution z2with `validate_args=False` to turn off validation.zExpected parameter z (
 of shape z) of distribution z to satisfy the constraint , but found invalid values:
)_batch_shape_event_shaper   arg_constraintsNotImplementedErrorwarningswarn	__class__itemsr   is_dependent__dict__
isinstancegetattrtyper   checkallr   __name__tupleshapereprsuper__init__)
selfr   r   r   r   param
constraintr   validr    s
            r   r.   zDistribution.__init__)   s    ('$"/D 	"&"6&   "$~KKKYZJK     &5%:%:%<%<  !z+J77 --*DJJ..3 3- e,,"((//yy{{ $>e > > KK0> ><A%+<N<N> >+/::> > 6:*5E5E> > 7<	> >   	s   * .AAc                     t           )a/  
        Returns a new distribution instance (or populates an existing instance
        provided by a derived class) with batch dimensions expanded to
        `batch_shape`. This method calls :class:`~torch.Tensor.expand` on
        the distribution's parameters. As such, this does not allocate new
        memory for the expanded distribution instance. Additionally,
        this does not repeat any args checking or parameter broadcasting in
        `__init__.py`, when an instance is first created.

        Args:
            batch_shape (torch.Size): the desired expanded size.
            _instance: new instance provided by subclasses that
                need to override `.expand`.

        Returns:
            New distribution instance with batch dimensions expanded to
            `batch_size`.
        r   )r/   r   	_instances      r   expandzDistribution.expandP   s
    & "!r   c                     | j         S )zF
        Returns the shape over which parameters are batched.
        )r   r/   s    r   r   zDistribution.batch_shapee       
   r   c                     | j         S )zJ
        Returns the shape of a single sample (without batching).
        )r   r8   s    r   r   zDistribution.event_shapel   r9   r   c                     t           )a
  
        Returns a dictionary from argument names to
        :class:`~torch.distributions.constraints.Constraint` objects that
        should be satisfied by each argument of this distribution. Args that
        are not tensors need not appear in this dict.
        r4   r8   s    r   r   zDistribution.arg_constraintss   
     "!r   c                     t           )z
        Returns a :class:`~torch.distributions.constraints.Constraint` object
        representing this distribution's support.
        r4   r8   s    r   supportzDistribution.support}   
     "!r   c                     t           )z7
        Returns the mean of the distribution.
        r4   r8   s    r   meanzDistribution.mean   
    
 "!r   c                 0    t          | j         d          )z7
        Returns the mode of the distribution.
        z does not implement mode)r   r    r8   s    r   modezDistribution.mode   s    
 "T^"M"M"MNNNr   c                     t           )z;
        Returns the variance of the distribution.
        r4   r8   s    r   variancezDistribution.variance   rB   r   c                 4    | j                                         S )zE
        Returns the standard deviation of the distribution.
        )rF   sqrtr8   s    r   stddevzDistribution.stddev   s    
 }!!###r   sample_shapec                     t          j                    5  |                     |          cddd           S # 1 swxY w Y   dS )z
        Generates a sample_shape shaped sample or sample_shape shaped batch of
        samples if the distribution parameters are batched.
        N)torchno_gradrsampler/   rJ   s     r   samplezDistribution.sample   s    
 ]__ 	. 	.<<--	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	.s   6::c                     t           )z
        Generates a sample_shape shaped reparameterized sample or sample_shape
        shaped batch of reparameterized samples if the distribution parameters
        are batched.
        r4   rO   s     r   rN   zDistribution.rsample   r?   r   z=`sample_n(n)` will be deprecated. Use `sample((n,))` instead.)categorync                 R    |                      t          j        |f                    S )zq
        Generates n samples or n batches of samples if the distribution
        parameters are batched.
        )rP   rL   Size)r/   rS   s     r   sample_nzDistribution.sample_n   s"     {{5:qd++,,,r   c                     t           )z
        Returns the log of the probability density/mass function evaluated at
        `value`.

        Args:
            value (Tensor):
        r4   r/   r   s     r   log_probzDistribution.log_prob   r<   r   c                     t           )z
        Returns the cumulative density/mass function evaluated at
        `value`.

        Args:
            value (Tensor):
        r4   rX   s     r   cdfzDistribution.cdf   r<   r   c                     t           )z
        Returns the inverse cumulative density/mass function evaluated at
        `value`.

        Args:
            value (Tensor):
        r4   rX   s     r   icdfzDistribution.icdf   r<   r   r6   c                     t           )ar  
        Returns tensor containing all values supported by a discrete
        distribution. The result will enumerate over dimension 0, so the shape
        of the result will be `(cardinality,) + batch_shape + event_shape`
        (where `event_shape = ()` for univariate distributions).

        Note that this enumerates over all batched tensors in lock-step
        `[[0, 0], [1, 1], ...]`. With `expand=False`, enumeration happens
        along dim 0, but with the remaining batch dimensions being
        singleton dimensions, `[[0], [1], ..`.

        To iterate over the full Cartesian product use
        `itertools.product(m.enumerate_support())`.

        Args:
            expand (bool): whether to expand the support over the
                batch dims to match the distribution's `batch_shape`.

        Returns:
            Tensor iterating over dimension 0.
        r4   )r/   r6   s     r   enumerate_supportzDistribution.enumerate_support   s
    , "!r   c                     t           )z
        Returns entropy of distribution, batched over batch_shape.

        Returns:
            Tensor of shape batch_shape.
        r4   r8   s    r   entropyzDistribution.entropy   s
     "!r   c                 N    t          j        |                                           S )z
        Returns perplexity of distribution, batched over batch_shape.

        Returns:
            Tensor of shape batch_shape.
        )rL   expra   r8   s    r   
perplexityzDistribution.perplexity   s     y(((r   c                     t          |t          j                  st          j        |          }t          j        || j        z   | j        z             S )ax  
        Returns the size of the sample returned by the distribution, given
        a `sample_shape`. Note, that the batch and event shapes of a distribution
        instance are fixed at the time of construction. If this is empty, the
        returned shape is upcast to (1,).

        Args:
            sample_shape (torch.Size): the size of the sample to be drawn.
        )r$   rL   rU   r   r   rO   s     r   _extended_shapezDistribution._extended_shape  sG     ,
33 	4 :l33Lz,)::T=NNOOOr   c                    t          |t          j                  st          d          t	          |                                          t	          | j                  z
  }|                                |d         | j        k    r-t          d|                                 d| j         d          |                                }| j        | j        z   }t          t          |          t          |                    D ]-\  }}|dk    r"|dk    r||k    rt          d| d| d          .	 | j
        }n3# t          $ r& t          j        | j         dd	z   d
z              Y dS w xY w|J |                    |          }|                                s\t          dt#          |          j         dt'          |j                   dt+          |           dt+          |            d| 
          dS )a  
        Argument validation for distribution methods such as `log_prob`,
        `cdf` and `icdf`. The rightmost dimensions of a value to be
        scored via these methods must agree with the distribution's batch
        and event shapes.

        Args:
            value (Tensor): the tensor whose log probability is to be
                computed by the `log_prob` method.
        Raises
            ValueError: when the rightmost dimensions of `value` do not match the
                distribution's batch and event shapes.
        z/The value argument to log_prob must be a TensorNz5The right-most size of value must match event_shape: z vs .   z9Value is not broadcastable with batch_shape+event_shape: z% does not define `support` to enable z;sample validation. Please initialize the distribution with z-`validate_args=False` to turn off validation.zExpected value argument (r   z) to be within the support (z) of the distribution r   )r$   rL   Tensorr   lensizer   r   zipreversedr>   r   r   r   r    r'   r(   r&   r)   r*   r+   r,   )	r/   r   event_dim_startactual_shapeexpected_shapeijr>   r2   s	            r   _validate_samplezDistribution._validate_sample  sL    %.. 	PNOOOejjll++c$2C.D.DD::<<(()T->>>n

nnZ^Zknnn   zz||*T->>..0H0HII 	 	DAqAvv!q&&Q!VV sP\ssbpsss  	lGG" 	 	 	M>HHHOPAB  
 FF	 """e$$yy{{ 	6KK(6 649%+4F4F6 6-1']]6 6 (,Dzz6 6 /4	6 6  	 	s   .D6 6,E&%E&c                     |Bt          |           j        |j        k    r%t          d| j        j         d|j         d          |"|                     t          |                     n|S )Nz	Subclass z of zR that defines a custom __init__ method must also define a custom .expand() method.)r&   r.   r   r    r)   __new__)r/   clsr5   s      r   _get_checked_instancez"Distribution._get_checked_instanceD  s|    d!4!D!D%>DN3 > > > > >   ,5+<t||DJJ''')Kr   c                       fd j                                         D             }d                     fd|D                       } j        j        dz   |z   dz   S )Nc                 ,    g | ]\  }}|j         v |S  )r#   ).0k_r/   s      r   
<listcomp>z)Distribution.__repr__.<locals>.<listcomp>M  s)    XXXTQQ$-EWEWqEWEWEWr   z, c                     g | ]V}| d j         |                                         dk    rj         |         nj         |                                          WS )z: ri   )r#   numelrl   )r|   pr/   s     r   r   z)Distribution.__repr__.<locals>.<listcomp>O  st        hhDM!,<,B,B,D,D,I,Ia((t}]^O_OdOdOfOfhh  r   ())r   r!   joinr    r)   )r/   param_namesargs_strings   `  r   __repr__zDistribution.__repr__L  s    XXXXT%9%?%?%A%AXXXii   $  
 
 ~&,{:S@@r   )N)T)0r)   
__module____qualname____doc__has_rsamplehas_enumerate_supportr   staticmethodboolr   rL   rU   r   r.   r	   r6   propertyr   r   r   strr   
Constraintr   r   r>   rj   rA   rD   rF   rI   rP   rN   r   FutureWarningintrV   rY   r[   r]   r_   ra   rd   rf   rt   rx   r   __classcell__)r    s   @r   r
   r
      sm         K!N, ,$ , , , \,$ #-%*,,",%*,,(,	% %Z% Z%  ~	% % % % % %N" "% " " " "* !UZ ! ! ! X! !UZ ! ! ! X! "c;+A&A!B " " " X" "# " " " X" "el " " " X" Oel O O O XO "%, " " " X" $ $ $ $ X$ ,65:<< . .5 .EL . . . . -7EJLL " "E "U\ " " " " ZG  -# -%, - - -	 -"el "u| " " " "" "%, " " " ""%, "5< " " " "" " " " " " "0" " " " ")EL ) ) ) ) 5?EJLL P PE PUZ P P P P0el 0t 0 0 0 0dL L L LA# A A A A A A A Ar   )r   typingr   r   r   typing_extensionsr   rL   torch.distributionsr   torch.distributions.utilsr   torch.typesr	   __all__r
   r{   r   r   <module>r      s     & & & & & & & & & & ( ( ( ( ( (  + + + + + + 3 3 3 3 3 3       
EA EA EA EA EA EA EA EA EA EAr   