
    sg[0                     r    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y)	    N)AnyDictOptional)
deprecated)constraints)lazy_property)_sizeDistributionc                   x    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
j4                  fd       Zede
j4                  fd       Zede
j4                  fd       Zede
j4                  fd       Z e
j                         fdede
j4                  fdZ e
j                         fdede
j4                  fdZ  e!de"      de#de
j4                  fd       Z$de
j4                  de
j4                  fdZ%de
j4                  de
j4                  fdZ&de
j4                  de
j4                  fdZ'd(dede
j4                  fd Z(de
j4                  fd!Z)de
j4                  fd"Z* e
j                         fdede
j                  fd#Z+de
j4                  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                 .    | dvrt         | t        _        y)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    S/var/www/html/venv/lib/python3.12/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                  }|j                         D ]  \  }}t        j                  |      r|| j                  vr$t        t        t        |       |      t              rNt        | |      }|j!                  |      }|j#                         r|t%        d| dt        |      j&                   dt)        |j*                         dt-        |        dt-        |       d	|        t.        	| a          y # t        $ r. i }t        j                  | j                   ddz   dz          Y 'w xY w)
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__)   sr    ('$"/D"&"6"6 &5%:%:%< !z++J7-*DJ.3 e,"((/yy{$-eW 5 K001E%++<N;O P++/:, 7559*5E4F G66;W	> " 	1 ' "$~~&&JKYZJKs   D# #3EE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                 2    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^^$44L"MNNr   c                     t         )z;
        Returns the variance of the distribution.
        r4   r8   s    r   variancezDistribution.variance   rB   r   c                 6    | j                   j                         S )zE
        Returns the standard deviation of the distribution.
        )rF   sqrtr8   s    r   stddevzDistribution.stddev   s    
 }}!!##r   sample_shapec                 x    t        j                         5  | j                  |      cddd       S # 1 sw Y   yxY w)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   09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                 L    | j                  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                 H    t        j                  | 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     yy((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  sE     ,

3 ::l3Lzz,):)::T=N=NNOOr   c                    t        |t        j                        st        d      t	        |j                               t	        | j                        z
  }|j                         |d | j                  k7  r*t        d|j                          d| j                   d      |j                         }| j                  | j                  z   }t        t        |      t        |            D ](  \  }}|dk7  s|dk7  s||k7  st        d| d| d       	 | j                  }|J |j                  |      }|j!                         sRt        dt#        |      j$                   dt'        |j(                         dt+        |       dt+        |        d| 
      y# t        $ r+ t        j                  | j                   dd	z   d
z          Y yw xY w)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  s    %.NOOejjl+c$2C2C.DD::<()T->->>G

~UYZ^ZkZkYllmn  zz|**T->->>.0HI 	DAqAv!q&Q!V OP\~]abpaqqrs 	
	llG """e$yy{K(()E%++4F3G H--1']O <''+Dzl 3..3W	6   # 	MM>>""GHOPAB
 	s   F 1G
	G
c                     |Rt        |       j                  |j                  k7  r0t        d| j                  j                   d|j                   d      || j                  t        |             S |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  sp    d!4!4!D%DNN334D G> >  ,5+<t||DJ'K)Kr   c           	         | j                   j                         D cg c]  \  }}|| j                  v s| }}}dj                  |D cg c]S  }| d| j                  |   j	                         dk(  r| j                  |   n| j                  |   j                          U c}      }| j                  j                  dz   |z   dz   S c c}}w c c}w )Nz, z: ri   ())r   r!   r#   joinnumelrl   r    r)   )r/   k_param_namespargs_strings         r   __repr__zDistribution.__repr__L  s    %)%9%9%?%?%AXTQQ$--EWqXXii % #RDMM!,<,B,B,D,Ia(t}}]^O_OdOdOfgh
 ~~&&,{:S@@ Ys   C	C	AC)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
      s    K!N, ,$ , ,$ #-%**,",%**,(,	%ZZ% ZZ%  ~	%N"% "* !UZZ ! ! !UZZ ! ! "c;+A+A&A!B " " "# " " "ell " " Oell O O "%,, " " $ $ $ ,65::< .5 .ELL . -7EJJL "E "U\\ " G-# -%,, -	-"ell "u|| "" "%,, ""%,, "5<< "" " "0" ")ELL ) 5?EJJL PE PUZZ P0ell 0t 0dLA# Ar   )r   typingr   r   r   typing_extensionsr   rL   torch.distributionsr   torch.distributions.utilsr   torch.typesr	   __all__r
    r   r   <module>r      s5     & & (  + 3  
EA EAr   