o
    -wi?                     @  sH  U d Z ddlmZ ddlZddlZddlZddlZddlmZm	Z	m
Z
 ddlZddlm  m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r`dd
lmZ ddlmZ ddlmZ G dd dZe
ej ef Z G dd dZ!da"de#d< 	 d&ddZ$d'ddZ%e& 		d(d)ddZ'd*d+dd Z(e& d*d,d$d%Z)dS )-aa  Global W&B library state.

This module manages global state, which for wandb includes:

- Settings configured through `wandb.setup()`
- The list of active runs
- A subprocess ("the internal service") that asynchronously uploads metrics

This module is fork-aware: in a forked process such as that spawned by the
`multiprocessing` module, `wandb.singleton()` returns a new object, not the
one inherited from the parent process. This requirement comes from backward
compatibility with old design choices: the hardest one to fix is that wandb
was originally designed to have a single run for the entire process that
`wandb.init()` was meant to return. Back then, the only way to create
multiple simultaneous runs in a single script was to run subprocesses, and since
the built-in `multiprocessing` module forks by default, this required a PID
check to make `wandb.init()` ignore the inherited global run.

Another reason for fork-awareness is that the process that starts up
the internal service owns it and is responsible for shutting it down,
and child processes shouldn't also try to do that. This is easier to
redesign.
    )annotationsN)TYPE_CHECKINGAnyUnion)
CONFIG_DIR)import_hooks
wb_logging   )wandb_settings)config_utilserver)	wandb_run)ServiceConnection)Settingsc                   @  sj   e Zd ZdZdddZd ddZd ddZd ddZd ddZd ddZ	d ddZ
d!ddZd"ddZdS )#_EarlyLoggerzKEarly logger which captures logs in memory until logging can be configured.returnNonec                 C  s   g | _ g | _| j| _d S N)_log
_exceptionwarningwarnself r   R/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/wandb/sdk/wandb_setup.py__init__2   s   z_EarlyLogger.__init__msgstrargsr   kwargsc                 O     | j tj|||f d S r   )r   appendloggingDEBUGr   r   r   r    r   r   r   debug8      z_EarlyLogger.debugc                 O  r!   r   )r   r"   r#   INFOr%   r   r   r   info;   r'   z_EarlyLogger.infoc                 O  r!   r   )r   r"   r#   WARNINGr%   r   r   r   r   >   r'   z_EarlyLogger.warningc                 O  r!   r   )r   r"   r#   ERRORr%   r   r   r   errorA   r'   z_EarlyLogger.errorc                 O  r!   r   )r   r"   r#   CRITICALr%   r   r   r   criticalD   r'   z_EarlyLogger.criticalc                 O  s   | j |||f d S r   )r   r"   r%   r   r   r   	exceptionG   s   z_EarlyLogger.exceptionlevelc                 O  s   | j ||||f d S r   )r   r"   )r   r0   r   r   r    r   r   r   logJ   s   z_EarlyLogger.log
new_loggerLoggerc                 C  sh   | |usJ | j D ]\}}}}|j||g|R i | q	| jD ]\}}}|j|g|R i | q d S r   )r   r1   r   r/   )r   r2   r0   r   r   r    r   r   r   _flushM   s   z_EarlyLogger._flushNr   r   )r   r   r   r   r    r   r   r   )
r0   r   r   r   r   r   r    r   r   r   r2   r3   r   r   )__name__
__module____qualname____doc__r   r&   r)   r   r,   r.   r/   r1   r4   r   r   r   r   r   /   s    







r   c                   @  s   e Zd ZdZ		d@dAddZdBddZdBddZedCddZdDddZ	dEddZ
dFdGddZdDddZdHd!d"ZdId#d$ZedJd%d&ZdKd(d)ZdKd*d+ZdLd-d.ZedMd0d1ZdNd3d4ZdDd5d6ZdFdOd9d:ZdPd<d=ZdPd>d?ZdS )Q_WandbSetupzW&B library singleton.NpidintsettingsSettings | Noneenvirondict | Noner   r   c                 C  sb   d | _ g | _|pttj| _d | _d | _d | _|| _	t
 | _| || _t| jd  |   d S r   )_connection_active_runsdictosr@   _environ_sweep_config_config_server_pidr   _logger_settings_setup	_settingswandb	termsetup_setup)r   r<   r>   r@   r   r   r   r   [   s   z_WandbSetup.__init__runwandb_run.Runc                 C  s   || j vr| j | dS dS )zAppend a run to the active runs list.

        This must be called when a run is initialized.

        Args:
            run: A newly initialized run.
        N)rC   r"   r   rQ   r   r   r   add_active_runu   s   
z_WandbSetup.add_active_runc                 C  s(   z	| j | W dS  ty   Y dS w )zRemove the run from the active runs list.

        This must be called when a run is finished.

        Args:
            run: A run that is finished or crashed.
        N)rC   remove
ValueErrorrS   r   r   r   remove_active_run   s
   z_WandbSetup.remove_active_runwandb_run.Run | Nonec                 C  s   | j sdS | j d S )z;The most recently initialized run that is not yet finished.N)rC   r   r   r   r   most_recent_active_run   s   
z"_WandbSetup.most_recent_active_runc                 C  s    t | j}|D ]}|  qdS )a  Finish all unfinished runs.

        NOTE: This is slightly inefficient as it finishes runs one at a time.
        This only exists to support using the `reinit="finish_previous"`
        setting together with `reinit="create_new"` which does not seem to be a
        useful pattern. Since `"create_new"` should eventually become the
        default and only behavior, it does not seem worth optimizing.
        N)listrC   finish)r   	runs_copyrQ   r   r   r   finish_all_active_runs   s   


z"_WandbSetup.finish_all_active_runswandb_settings.Settingsc                 C  sF  t  }t }| jdtj  | jd|  ||_|r(|j	r(|j	|_	n$t
td  }r?t| }t|d |_	nttdddd |_	|j	rY| jd|j	  |  |jrj| jd|j  |  | jd || j |  |j }|r|jrd	}|rt r| jd
 t| |r|| |S )NzCurrent SDK version is zConfigure stats pid to r>   ~z.configrN   zLoading settings from z+Loading settings from environment variablesFzLoading SageMaker settings)r
   r   rE   getpidrK   r)   rN   __version__x_stats_pidsettings_systemgetenvr   pathlibPath
expanduserr   update_from_system_config_filesettings_workspace!update_from_workspace_config_fileupdate_from_env_varsrF   update_from_system_environmentsagemaker_disable	sagemakeris_using_sagemakerset_global_settingsupdate_from_settings)r   r>   sr<   config_dir_str
config_dircheck_sagemaker_envr   r   r   rL      s>   




z_WandbSetup._settings_setupc                 C  s   |sd S | j | d S r   )rM   rr   )r   r>   r   r   r   _update   s   z_WandbSetup._updatec                 C  s*   d | _ |  }|d ur| j| d S d S r   )rI   _load_user_settingsrM   update_from_dict)r   user_settingsr   r   r   _update_user_settings   s
   z!_WandbSetup._update_user_settingsr2   r3   c                 C  s0   | j |u rd S t| j tr| j | || _ d S r   )rK   
isinstancer   r4   )r   r2   r   r   r   _early_logger_flush   s
   

z_WandbSetup._early_logger_flushc                 C     | j S r   )rK   r   r   r   r   _get_logger   s   z_WandbSetup._get_loggerc                 C  r~   r   )rM   r   r   r   r   r>      s   z_WandbSetup.settings
str | Nonec                 C  s"   | j r	| j jr	d S | jd}|S )NentityrM   _offlineviewerget)r   r   r   r   r   _get_entity   s   z_WandbSetup._get_entityc                 C  s   | j r	| j jr	d S | jdS )Nusernamer   r   r   r   r   _get_username   s   z_WandbSetup._get_username	list[str]c                 C  s<   | j r	| j jr	g S | jd}|rdd |d D }|pg S )Nteamsc                 S  s   g | ]}|d  d qS )nodenamer   ).0teamr   r   r   
<listcomp>  s    z*_WandbSetup._get_teams.<locals>.<listcomp>edgesr   )r   r   r   r   r   
_get_teams   s   z_WandbSetup._get_teamsdict[str, Any]c                 C  s"   | j d u rtj| jd| _ | j jS )Nr>   )rI   r   ServerrM   r   r   r   r   r   r     s   
z_WandbSetup.viewerdict[str, Any] | Nonec                 C  sN   | j d u rd S | j j}t }d|v r|d |d< | jdd }|r%||d< |S )Ncode_saving_enabled	save_codeemail)rI   _flagsrD   r   r   )r   flagsrz   r   r   r   r   rx     s   
z_WandbSetup._load_user_settingsc                 C  sl   | j j}|rtj|dd| _| j jr2| j jD ]}t|}|d u r"q| jd ur.| j| q|| _qd S d S )NT)
must_exist)rM   sweep_param_pathr   dict_from_config_filerG   config_pathsrH   update)r   
sweep_pathconfig_pathconfig_dictr   r   r   rP     s   

z_WandbSetup._setup	exit_code
int | Nonec                 C  sF   t   | js	d S | j}d | _||pd}|dvr!t| d S d S )Nr   )Nr   )r    unregister_all_post_import_hooksrB   teardownsysexit)r   r   
connectioninternal_exit_coder   r   r   	_teardown0  s   z_WandbSetup._teardownr   c                 C  s,   | j r| j S ddlm} || j| _ | j S )zBReturns a connection to the service process creating it if needed.r   )service_connection)rB   wandb.sdk.lib.servicer   connect_to_servicerM   )r   r   r   r   r   ensure_service>  s
   z_WandbSetup.ensure_servicec                 C  s   | j std| j S )zReturns a connection to the service process, asserting it exists.

        Unlike ensure_service(), this will not start up a service process
        if it didn't already exist.
        z"Expected service process to exist.)rB   AssertionErrorr   r   r   r   assert_serviceH  s   z_WandbSetup.assert_service)NN)r<   r=   r>   r?   r@   rA   r   r   )rQ   rR   r   r   )r   rX   r5   )r>   r?   r   r_   r   )r>   r?   r   r   r6   )r   r3   )r   r_   )r   r   )r   r   )r   r   )r   r   r   r   r   r   )r   r   )r7   r8   r9   r:   r   rT   rW   propertyrZ   r^   rL   rw   r{   r}   r   r>   r   r   r   r   rx   rP   r   r   r   r   r   r   r   r;   X   s6    



5









r;   _WandbSetup | None
_singletonr   c                   C  s
   t ddS )a  The W&B singleton for the current process.

    The first call to this in this process (which may be a fork of another
    process) creates the singleton, and all subsequent calls return it
    until teardown(). This does not start the service process.
    F)start_servicerP   r   r   r   r   	singleton[  s   
r   c                   C  s   t rt jt krt S dS )a  The W&B singleton for the current process or None if it isn't set up.

    Always prefer singleton() over this function.

    Unlike singleton(), this never creates the singleton and therefore never
    initializes global settings from the environment. This is useful only
    during tests, which may modify the environment after having imported wandb
    and called certain functions.
    N)r   rJ   rE   ra   r   r   r   r   singleton_if_setupe  s   
r   Tr>   r?   r   boolc                 C  sH   t  }trtj|krtj| d nt| |da|r"tjjs"t  tS )a  Set up library context.

    Args:
        settings: Global settings to set, or updates to the global settings
            if the singleton has already been initialized.
        start_service: Whether to start up the service process.
            NOTE: A service process will only be started if allowed by the
            global settings (after the given updates). The service will not
            start up if the mode resolves to "disabled".
    r   )r>   r<   )	rE   ra   r   rJ   rw   r;   r>   _noopr   )r>   r   r<   r   r   r   rP   u  s   rP   c                 C  s
   t | dS )a  Prepares W&B for use in the current process and its children.

    You can usually ignore this as it is implicitly called by `wandb.init()`.

    When using wandb in multiple processes, calling `wandb.setup()`
    in the parent process before starting child processes may improve
    performance and resource utilization.

    Note that `wandb.setup()` modifies `os.environ`, and it is important
    that child processes inherit the modified environment variables.

    See also `wandb.teardown()`.

    Args:
        settings: Configuration settings to apply globally. These can be
            overridden by subsequent `wandb.init()` calls.

    Example:
        ```python
        import multiprocessing

        import wandb


        def run_experiment(params):
            with wandb.init(config=params):
                # Run experiment
                pass


        if __name__ == "__main__":
            # Start backend and set global config
            wandb.setup(settings={"project": "my_project"})

            # Define experiment parameters
            experiment_params = [
                {"learning_rate": 0.01, "epochs": 10},
                {"learning_rate": 0.001, "epochs": 20},
            ]

            # Start multiple processes, each running a separate experiment
            processes = []
            for params in experiment_params:
                p = multiprocessing.Process(target=run_experiment, args=(params,))
                p.start()
                processes.append(p)

            # Wait for all processes to complete
            for p in processes:
                p.join()

            # Optional: Explicitly shut down the backend
            wandb.teardown()
        ```
    r   r   r   r   r   r   setup  s   
8r   r   r   r   c                 C  s    t }da |r|j| d dS dS )a  Waits for wandb to finish and frees resources.

    Completes any runs that were not explicitly finished
    using `run.finish()` and waits for all data to be uploaded.

    It is recommended to call this at the end of a session
    that used `wandb.setup()`. It is invoked automatically
    in an `atexit` hook, but this is not reliable in certain setups
    such as when using Python's `multiprocessing` module.
    N)r   )r   r   )r   orig_singletonr   r   r   r     s
   r   )r   r;   )r   r   )NT)r>   r?   r   r   r   r;   r   )r>   r?   r   r;   r   )*r:   
__future__r   r#   rE   rf   r   typingr   r   r   rN   wandb.integration.sagemakerintegrationro   	wandb.envr   wandb.sdk.libr   r    r
   libr   r   	wandb.sdkr   (wandb.sdk.lib.service.service_connectionr   wandb.sdk.wandb_settingsr   r   r3   r;   r   __annotations__r   r   log_to_all_runsrP   r   r   r   r   r   r   <module>   s@    & }


;