o
    pi!.                     @  s   d dl mZ d dlZd dlmZ d dlZd dlZd dlmZ d dl	m
Z
mZ d dlmZ d dlmZmZ erPd dlmZ d d	lmZ d d
lmZ d dlmZmZ G dd dZdS )    )annotationsN)TYPE_CHECKING)_C_ops)check_variable_and_dtypeconvert_dtype)Variable)in_dynamic_or_pir_modein_pir_mode)Sequence)	TypeGuard)Tensor)NestedNumericSequence
TensorLikec                      s   e Zd ZdZ	d?d@ fdd	ZedAd
dZedAddZedBddZedBddZ	g fdCddZ
g fdCddZdBddZdDddZdEddZdEd d!ZdEd"d#ZdFd&d'ZdGd+d,ZdHd.d/ZdId1d2Z	3dJdKd8d9Z	3dJdLd;d<ZdHd=d>Z  ZS )MDistributiona>  
    The abstract base class for probability distributions. Functions are
    implemented in specific distributions.

    Args:
        batch_shape(Sequence[int], optional):  independent, not identically
            distributed draws, aka a "collection" or "bunch" of distributions.
        event_shape(Sequence[int], optional): the shape of a single
            draw from the distribution; it may be dependent across dimensions.
            For scalar distributions, the event shape is []. For n-dimension
            multivariate distribution, the event shape is [n].
     batch_shapeSequence[int]event_shapereturnNonec                   s>   t |tr|nt|| _t |tr|nt|| _t   d S N)
isinstancetuple_batch_shape_event_shapesuper__init__)selfr   r   	__class__r   g/home/app/PaddleOCR-VL/.venv_paddleocr/lib/python3.10/site-packages/paddle/distribution/distribution.pyr   6   s   zDistribution.__init__c                 C     | j S )zeReturns batch shape of distribution

        Returns:
            Sequence[int]: batch shape
        )r   r   r   r   r    r   F      zDistribution.batch_shapec                 C  r!   )zeReturns event shape of distribution

        Returns:
            Sequence[int]: event shape
        )r   r"   r   r   r    r   O   r#   zDistribution.event_shaper   c                 C     t )zMean of distributionNotImplementedErrorr"   r   r   r    meanX      zDistribution.meanc                 C  r$   )zVariance of distributionr%   r"   r   r   r    variance]   r(   zDistribution.varianceshapec                 C  r$   )zSampling from the distribution.r%   r   r*   r   r   r    sampleb      zDistribution.samplec                 C  r$   )zreparameterized sampler%   r+   r   r   r    rsamplef   r-   zDistribution.rsamplec                 C  r$   )z The entropy of the distribution.r%   r"   r   r   r    entropyj   r-   zDistribution.entropyotherc                 C  r$   )z7The KL-divergence between self distributions and other.r%   )r   r0   r   r   r    kl_divergencen   r-   zDistribution.kl_divergencevaluec                 C  s   |  | S )zProbability density/mass function evaluated at value.

        Args:
            value (Tensor): value which will be evaluated
        )log_probexpr   r2   r   r   r    probr   s   zDistribution.probc                 C  r$   )z&Log probability density/mass function.r%   r5   r   r   r    r3   z   r-   zDistribution.log_probc                 C  r$   )zProbability density/mass function.

        Note:

            This method will be deprecated in the future, please use `prob`
            instead.
        r%   r5   r   r   r    probs~   s   zDistribution.probssample_shapeSequence[int] | Tensorc                 C  s   t |t | j t | j S )zcompute shape of the sample

        Args:
            sample_shape (Sequence[int]|Tensor): sample shape

        Returns:
            Tensor: generated sample data shape
        )r   r   r   )r   r8   r   r   r    _extend_shape   s   
zDistribution._extend_shapeargs"TensorLike | NestedNumericSequenceTypeGuard[Tensor]c                 G  sB   d}d}|D ]}t |ttjjfrd}qd}q|r|rtd|S )z
        Argument validation for distribution args
        Args:
            value (float, list, numpy.ndarray, Tensor)
        Raises
            ValueError: if one argument is Tensor, all arguments should be Tensor
        FTz9if one argument is Tensor, all arguments should be Tensor)r   r   paddlepirValue
ValueError)r   r;   Zis_variableZ	is_numberargr   r   r    _validate_args   s   
zDistribution._validate_argstuple[Tensor, ...]c              	   G  s&  g }g }d}|D ]M}t |ttttjttjj	fs!t
dt| t |tjj	r.|| qt|}|j}t|dkrLt|dkrGtd |d}|| }|| q|j}|D ]3}t |tjj	rj|| q[t||\}	}
t r|t|	j}ntjj|d}t|	| || q[t|S )z
        Argument convert args to Tensor

        Args:
            value (float, list, numpy.ndarray, Tensor)
        Returns:
            Tensor of args.
        g        ZType of input args must be float, list, tuple, numpy.ndarray or Tensor, but received type float32float64zadata type of argument only support float32 and float64, your argument will be convert to float32.dtype)r   floatlistr   npndarrayr   r>   r?   r@   	TypeErrortypeappendarrayrI   strwarningswarnastypeZbroadcast_arraysr	   Zzerosr*   ZtensorZcreate_tensorZassign)r   r;   Z
numpy_argsZvariable_argstmprB   Zarg_npZ	arg_dtyperI   Zarg_broadcasted_Zarg_variabler   r   r    
_to_tensor   sH   



zDistribution._to_tensorparamc                 C  s   t |r||jS t r5t rt|dddgd |j|jkr3t|jdv r3t	d t
||jS |S t|dddgd |j|jkrQt	d t j||jdS |S )a  
        Log_prob and probs methods have input ``value``, if value's dtype is different from param,
        convert value's dtype to be consistent with param's dtype.

        Args:
            param (Tensor): low and high in Uniform class, loc and scale in Normal class.
            value (Tensor): The input tensor.

        Returns:
            value (Tensor): Change value's dtype if value's dtype is different from param.
        r2   rF   rG   r3   )rF   rG   ztdtype of input 'value' needs to be the same as parameters of distribution class. dtype of 'value' will be converted.rH   )r>   Z
is_complexrU   rI   r   r	   r   r   rS   rT   r   cast)r   rY   r2   r   r   r    _check_values_dtype_in_probs   s2   
z)Distribution._check_values_dtype_in_probsFr7   float | Tensor	is_binaryboolc                 C  s$   |rt |t |  S t |S )a  
        Converts probabilities into logits. For the binary, probs denotes the
        probability of occurrence of the event indexed by `1`. For the
        multi-dimensional, values of last axis denote the probabilities of
        occurrence of each of the events.
        )r>   loglog1p)r   r7   r]   r   r   r    _probs_to_logits  s
   zDistribution._probs_to_logitslogitsc                 C  s$   |r	t jj|S t jjj|ddS )z
        Converts logits into probabilities. For the binary, each value denotes
        log odds, whereas for the multi-dimensional case, the values along the
        last dimension denote the log probabilities of the events.
        )Zaxis)r>   nnZ
functionalZsigmoidZsoftmax)r   rb   r]   r   r   r    _logits_to_probs(  s
   
zDistribution._logits_to_probsc              	     s   |D ]}t |ttttjttjj	fst
dt| qtdd |D sJt  |D ]}t |ttjj	fr;|j  nq+ fdd|D }t|S t|S )a  
        Returns a list where each arg is broadcasted. Scalar args are upcast to tensors
        having the same data type as the first Tensor passed to `args`.  If all the
        args are scalars, then they are upcasted to Tensors with paddle default data type.

        Args:
            value (float, list, numpy.ndarray, Tensor)

        Returns:
            Broadcasted Tensor of args.
        rE   c                 s  s"    | ]}t |ttjjfV  qd S r   )r   r   r>   r?   r@   .0rB   r   r   r    	<genexpr>L  s    
z.Distribution._broadcast_all.<locals>.<genexpr>c                   s0   g | ]}t |ttjjfr|ntj| d qS )rH   )r   r   r>   r?   r@   Z	to_tensorrf   rH   r   r    
<listcomp>T  s    z/Distribution._broadcast_all.<locals>.<listcomp>)r   rJ   rK   r   rL   rM   r   r>   r?   r@   rN   rO   allZget_default_dtyperI   Zbroadcast_tensors)r   r;   rB   new_argsr   rH   r    _broadcast_all6  s.   


zDistribution._broadcast_all)r   r   )r   r   r   r   r   r   )r   r   )r   r   )r*   r   r   r   )r0   r   r   r   )r2   r   r   r   )r8   r9   r   r   )r;   r<   r   r=   )r;   r<   r   rD   )rY   r   r2   r   r   r   )F)r7   r\   r]   r^   r   r   )rb   r\   r]   r^   r   r   )__name__
__module____qualname____doc__r   propertyr   r   r'   r)   r,   r.   r/   r1   r6   r3   r7   r:   rC   rX   r[   ra   re   rl   __classcell__r   r   r   r    r   (   s8    









;/r   )
__future__r   rS   typingr   numpyrL   r>   r   Zpaddle.base.data_feederr   r   Zpaddle.base.frameworkr   Zpaddle.frameworkr   r	   collections.abcr
   Ztyping_extensionsr   r   Zpaddle._typingr   r   r   r   r   r   r    <module>   s   