
      iu                     8   d dl Z d dlZd dlZd dlmZ d dlmZ d dlmZm	Z	 d dl
Z
d dlmZ d dlmZmZmZmZ  e j$                  e      ZdZd Zdde	e   d	ed
edefdZddZddede	e   ddfdZdededededee   f
dZddedeeef   fdZ deeef   ddfdZ!y)    N)getstate)setstate)AnyOptional)_NUMPY_AVAILABLE)	_get_rankrank_prefixed_messagerank_zero_onlyrank_zero_warnl    seedworkersverbosereturnc                    | At         j                  j                  d      }|d} |r7t        d|         n(	 t	        |      } nt        | t              st	        |       } t        | cxk  r	t        k  sn t        |  dt         dt               |r*t        j                  t        d|  t                            t        |       t         j                  d<   t        j                   |        t"        rddl}|j                  j!                  |        t'        j(                  |        t	        |       t         j                  d	<   | S # t
        $ r t        dt        |             w xY w)
an  Function that sets the seed for pseudo-random number generators in: torch, numpy, and Python's random module.
    In addition, sets the following environment variables:

    - ``PL_GLOBAL_SEED``: will be passed to spawned subprocesses (e.g. ddp_spawn backend).
    - ``PL_SEED_WORKERS``: (optional) is set to 1 if ``workers=True``.

    Args:
        seed: the integer value seed for global random state in Lightning.
            If ``None``, it will read the seed from ``PL_GLOBAL_SEED`` env variable. If ``None`` and the
            ``PL_GLOBAL_SEED`` env variable is not set, then the seed defaults to 0. If seed is
            not in bounds or cannot be cast to int, a ValueError is raised.
        workers: if set to ``True``, will properly configure all dataloaders passed to the
            Trainer with a ``worker_init_fn``. If the user already provides such a function
            for their dataloaders, setting this argument will have no influence. See also:
            :func:`~lightning_fabric.utilities.seed.pl_worker_init_function`.
        verbose: Whether to print a message on each rank with the seed being set.

    NPL_GLOBAL_SEEDr   zNo seed found, seed set to z+Invalid seed specified via PL_GLOBAL_SEED: z& is not in bounds, numpy accepts from z to zSeed set to PL_SEED_WORKERS)osenvirongetr   int
ValueErrorrepr
isinstancemin_seed_valuemax_seed_valueloginfor	   r   strrandomr   r   numpytorchmanual_seed)r   r   r   env_seednps        t/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/lightning_fabric/utilities/seed.pyseed_everythingr&      s5   & |::>>"23D!<TFCDa8} c"4yd4n4D6!GGWW[\j[klmm&dV'<ikJK#&t9BJJ 
KK
		t	d'*7|nBJJ !K+  a #NtT\~N^!_``as   E !E&c                      t         j                  j                  dd      } | yt         j                  j                  dd      }t        t	        |       t        t	        |            d       y)zReset the seed to the value that :func:`~lightning_fabric.utilities.seed.seed_everything` previously set.

    If :func:`~lightning_fabric.utilities.seed.seed_everything` is unused, this function will do nothing.

    r   Nr   0F)r   r   )r   r   r   r&   r   bool)r   r   s     r%   
reset_seedr*   H   sO     ::>>*D1D|jjnn.4GCItCL'95I    	worker_idrankc                    ||nt         j                  }t        j                         }|| z
  }t        j                  d| d|  d|        t        || |d      }t        j                  |d          t        j                  |d   d	z  |d
   z         t        rOddl}|j                  j                  || |g      }|j                  d      }|j                  j                  |       yy)a.  The worker_init_fn that Lightning automatically adds to your dataloader if you previously set the seed with
    ``seed_everything(seed, workers=True)``.

    See also the PyTorch documentation on
    `randomness in DataLoaders <https://pytorch.org/docs/stable/notes/randomness.html#dataloader>`_.

    Nz1Initializing random number generators of process z worker z with base seed    )countr             )r
   r-   r!   initial_seedr   debug_generate_seed_sequencer"   r   r   r   r    SeedSequencegenerate_state)	r,   r-   global_rankprocess_seed	base_seedseed_sequencer$   ssnp_rng_seeds	            r%   pl_worker_init_functionr?   U   s     *$0C0CK%%'Ly(III
;K=QZP[[klukvw ,Iy+UVWM	mA&'
KKq!R'=+;;<YY##Y	;$GH''*
		{# r+   r;   r9   r0   c                     | dz  |dz  z  |z  }||dz	  z  }|dz  dz  }||dz	  z  }|dz  dz  }||dz	  z  }g }t        |      D ]  }|dz  dz   dz  }|j                  |         |S )	zGenerates a sequence of seeds from a base seed, worker id and rank using hash-based mixing followed by the
    linear congruential generator (LCG) algorithm.r2      !   l   Z_?z l    l   Sl5gu& l   -*PB r1   )rangeappend)r;   r,   r9   r0   combined_seedseeds_s          r%   r6   r6   q   s     "_b9KGM ]b((M"%77MJM]b((M"%77MJM]b((ME5\&)<<q@]S]#  Lr+   include_cudac                    t        j                         t               d}t        r!ddl}|j
                  j                         |d<   | rAt         j                  j                         rt         j                  j                         ng |d<   |S )z\Collect the global random state of :mod:`torch`, :mod:`torch.cuda`, :mod:`numpy` and Python.)r!   pythonr   Nr    
torch.cuda)
r!   get_rng_statepython_get_rng_stater   r    r   	get_statecudais_availableget_rng_state_all)rH   statesr$   s      r%   _collect_rng_statesrS      sl     $$&&(F ))--/wAFAXAXAZuzz;;=`b|Mr+   rng_state_dictc                    t        j                  | d          d| v r"t         j                  j                  | d          t        r&d| v r"ddl}|j                  j                  | d          | d   \  }}}t        |t        |      |f       y)zsSet the global random state of :mod:`torch`, :mod:`torch.cuda`, :mod:`numpy` and Python in the current
    process.r!   rK   r    r   NrJ   )
r!   set_rng_staterO   set_rng_state_allr   r    r   	set_statepython_set_rng_statetuple)rT   r$   versionstategausss        r%   _set_rng_statesr^      s~     
w/0~%

$$^L%ABG~5
		N734*84GUE'5<78r+   )NFT)r   N)N)T)"loggingr   r   r   rM   r   rY   typingr   r   r!   "lightning_fabric.utilities.importsr   $lightning_fabric.utilities.rank_zeror   r	   r
   r   	getLogger__name__r   r   r   r   r)   r&   r*   r?   listr6   dictr   rS   r^    r+   r%   <module>rh      s     	  3 3    ? q qg! 1(3- 1 1PT 1`c 1h
J$s $(3- $4 $8s s  UX ]abe]f ,d d38n 9DcN 9t 9r+   