
    uki                        d dl mZ d dlZd dlZd dlmZ d dlmZ d dlm	Z	 d dlm
Z
 d dlmZ d dlmZ d d	lmZ d d	lmZ d d
lmZ d dlmZ ej*                  Ze	j,                  Zedej0                  f   ZeZej6                  Zej8                  Zdej0                  dej0                  fdZdej<                  defdZ dejB                  fdZ"dej0                  de#defdZ$dejJ                  dej0                  fdZ&dej0                  defdZ' ej<                  de"e'e$e&dd      Z( ejR                  e(       dejB                  fdZ*dej0                  de#defdZ+dej0                  dej0                  fd Z,dej0                  defd!Z- ej<                  d"e*e-e+e,d#d$      Z. ejR                  e.       d%edefd&Z/ e/ej`                        Z1 e/ejd                        Z3 e/ejh                        Z5 e/ejl                        Z7	 d.d'ed(ej0                  d)ed*ed+ed,e8ejr                  df   dz  dej0                  fd-Z:y)/    )CallableN)numpy)random)blocked_sampler)dtypes)prng)typing)
primitivesprng_random_bits)	prng_seed.keyreturnc                    t        j                  t        j                  j                  t
        j                  t        j                        }d}t        j                  | j                  t        j                        rt        | j                        dkD  rd}nt        | j                        dkD  rd}|r t        j                  |      |       }n ||       }t!        j"                  |d      S )zEHelper function for converting non-Pallas PRNG keys into Pallas keys.)shapedtypeFr   T   
pallas_tpuimpl)	functoolspartialjaxr   bitstpu_key_impl	key_shapejnpuint32
issubdtyper   r   prng_keylenr   vmapjax_api_randomwrap_key_data)r   generate_keyvmapped_keypallas_key_datas       X/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/jax/_src/pallas/mosaic/random.pyto_pallas_keyr)   '   s     ""	jjoo\333::, +^^CIIv/
399~k
399~k,chh|,S1O"3'O		%	%oL	II    r   c                 *    | t         k(  xs	 | t        k(  S )zAReturns True if the PRNGImpl is a Pallas-specific implementation.)r   tpu_internal_stateful_implr   s    r(   is_pallas_implr-   ;   s    			C)C!CCr*   seedc                     t        j                  t        j                  t         j                        }|| z   j                  t         j                        S )Nr   )r   zerosr   r   int32astyper   )r.   	seed_datas     r(   
_seed_funcr5   @   s6    ii..cii@)
d
	"	"3::	..r*   	bit_widthr   c                 N    |dk7  rt        d      t        |        t        |      S N    zBit width must be 32)
ValueErrorr   r   r   r6   r   s      r(   _random_bitsr<   D   s'    "_
+
,,C.	%	  r*   datac                 z    t        |       \  }}||z   }t        j                  ||gd      \  }}t        ||d      S )N   r   r   )unwrap_pallas_seedjax_prngapply_roundwrap_pallas_seed)r   r=   key0key1s       r(   _fold_inrF   J   sB    !#&*$	$%%tTlB7,4	$<	88r*   c                     ~ ~t        d      )NzDCannot split a Pallas key. Use fold_in instead to generate new keys.NotImplementedErrorr   r   s     r(   _splitrK   Q   s    	5L	 r*   )r      r   pl)r   r.   splitrandom_bitsfold_innametagc                 N    ~ t        j                  dt         j                        S )N r0   )r   emptyr2   )r.   s    r(   _pl_stateful_seed_funcrV   j   s    
	2SYY	''r*   c                 2    ~ |dk(  sJ d       t        |      S r8   r   r;   s      r(   _pl_stateful_random_bitsrX   o   s"    		b000	%	  r*   c                     ~ ~t               NrH   )r   r=   s     r(   _pl_stateful_fold_inr[   t   s    	4r*   c                     ~ ~t               rZ   rH   rJ   s     r(   _pl_stateful_splitr]   x   s    	5r*   rT   _pallas_internal_stateful_pl_statefulsamplerc                       fd} j                   r<t        d  j                   j                  d            }dj                  |      |_         |S )zConverts a jax.random sampling function to a stateful version.

  Args:
    sampler: A sampling function that consumes a key and returns
      random samples.

  Returns:
    A stateful sampling function with the key argument removed.
  c                  R    t        j                  dt              } |g| i |S )Nr   r   )r#   r   r,   )argskwargsplaceholder_keyr`   s      r(   new_samplerz+_make_stateful_sampler.<locals>.new_sampler   s-     %((1KLO?4T4V44r*   c                 
    d| vS )Nzkey:rT   )lines    r(   <lambda>z(_make_stateful_sampler.<locals>.<lambda>   s    V4' r*   
)__doc__filterrN   join)r`   rf   	doc_liness   `  r(   _make_stateful_samplerro      sG    5 __')>)>t)DFI))I.K	r*   
sampler_fn
global_key
block_size	tile_size
total_sizeblock_indexc                 ,   t        |      t        |      k7  r$t        dt        |       dt        |       d      |&t        |      }t        d t        |      D              }t	        j
                  |||||      }t	        j                  | |||fi |S )aj  Samples a block of random values with invariance guarantees.

  ``sample_block`` allows the sampling of identical blocks of random values
  across kernels with different block shapes and iteration orders. Each call
  to `sample_block` returns a `block_size`-shaped array of random samples
  corresponding to the `block_index`.

  ``tile_size`` should be chosen such that it is a divisor to all block sizes
  one needs to be invariant to. The larger the ``tile_size``, the more
  efficient the sampling process will be and therefore the best choice is
  typically the greatest common divisor between all possible block sizes.

  Args:
    sampler_fn: A sampling function that consumes a key and returns
      random samples.
    global_key: The global key to use for sampling.
    block_size: The shape of an individual block.
    tile_size: The shape of a ``tile``, which is the smallest unit at
      which samples are generated. This should be selected to be a divisor
      of all block sizes one needs to be invariant to.
    total_size: The total size of the array to sample.
    block_index: The index denoting which block to generate keys for. Defaults
      to the program_id for each block axis.
    **kwargs: Additional arguments to pass to the sampler_fn.

  Returns:
    A ``block_size`` shaped array of samples for the current block corresponding
    to ``block_index``.
  zblock_size (z) and tile_size (z) must have the same length.c              3   F   K   | ]  }t        j                  |        y wrZ   )r
   
program_id).0axiss     r(   	<genexpr>zsample_block.<locals>.<genexpr>   s       ?&*jD!?s   !)r!   r:   tupleranger   blocked_fold_insample_block)	rp   rq   rr   rs   rt   ru   rd   num_axeskeyss	            r(   r   r      s    H 	_I&
|C
O#4 5Y((DF G G :H ?.3Ho? ?K 
	(	(*j)[
B$		%	%$
I
917
9 9r*   rZ   );collections.abcr   r   r   r   r   r   r#   jax._srcr   r   r   rA   r	   jax._src.pallasr
   jax._src.pallas.mosaictpu_primitives!jax._src.pallas.mosaic.primitivesr   r   ShapeSampleFnSampleFnTypeArrayKeylessSampleFnTypeset_seedr@   rC   r)   PRNGImplboolr-   r2   r5   intr<   PRNGKeyArrayrF   rK   r   register_prngrV   rX   r[   r]   r,   ro   r   stateful_bitsuniformstateful_uniform	bernoullistateful_bernoullinormalstateful_normalr|   	ArrayLiker   rT   r*   r(   <module>r      s   %  
  ( $  %  & ? > 7 	''sCII~. #66 !22 Jsyy JSYY J(D** Dt D
/SYY /!fll !s !5 !9('' 9v|| 9 U  !x  	
	   | $( (
!&,, !3 !u !
fll &,, FLL  
 /X..	'#    1 2L 5H . '~':':;).*@*@A +N,D,DE ()>)>? EI09\ 09 YY09"09 "09 #	09
 $F$4$4c$9:TA09 "ii09r*   