o
    xi                     @  s  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ZddlZddl	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mZmZmZmZ ddlZddlZddlmZmZ ddlmZ ddlmZmZm Z  dd	l!m"Z" dd
l#m$Z$ ddl%m&Z&m'Z' ddl(m)Z) ddl*m+Z, ddl*m-Z-m.Z.m/Z/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z? ddl@mAZAmBZBmCZC ddlDmEZE ddlFmGZG ddlHmIZImJZJmKZK ddlLmMZM dfddZNdgd!d"ZOejPd#d$G d%d& d&ZQG d'd( d(eZRdhd)d*ZSdid-d.ZTG d/d0 d0ZU		djdd1dkd6d7ZVdld:d;ZWdmd<d=ZXdmd>d?ZYdnd@dAZZddddddddddddddddddddddddeAfdodddeZ[dS )pa  Defines wandb.init() and associated classes and methods.

`wandb.init()` indicates the beginning of a new run. In an ML training pipeline,
you could add `wandb.init()` to the beginning of your training script as well as
your evaluation script, and each step would be tracked as a run in W&B.

For more on using `wandb.init()`, including code snippets, check out our
[guide and FAQs](https://docs.wandb.ai/guides/track/launch).
    )annotationsN)IterableIteratorSequence)AnyLiteralProtocolSelf)envtrigger)
get_sentry)	CommErrorError
UsageError)url_registry)ProtobufErrorHandler)	sagemakerweave)
Deprecated)ipython)progressrunid
wb_logging)StrPath)_is_artifact_representation   )wandb_loginwandb_setup)Backend)SummaryDisabled
filesystemmodulepathsprinter	telemetry)UNSETDoNotSetwarn_and_record_deprecation)wait_with_progress)parse_config)RunTeardownHookTeardownStage)Settingsreturn
str | Nonec                  C  s.   dt jv rtjd} t| drt| jS d S )Ntransformers__version__)sysmoduleswandbutil
get_modulehasattrstrr1   )trans r:   H/home/ubuntu/.local/lib/python3.10/site-packages/wandb/sdk/wandb_init.py_huggingface_version4   s
   


r<   settingsr-   dict[str, Any]c              	   C  sH  i }| j s|S tjdd ur.zttjdd}W |S  ttfy-   t	d Y |S w | j
r_tj| j
r_t| j
}t| }W d    n1 sOw   Y  |di d}|S d}g }	 d| }|tjv r{|tj|  |d	7 }nnqdt|dkrd
|}zt|}W |S  ttfy   t	d Y |S w |S )NWANDB_CONFIGz{}z-Malformed WANDB_CONFIG, using original config	overrides
run_configr   TWANDB_CONFIG_r    )launchosenvirongetjsonloads
ValueErrorSyntaxErrorr4   termwarnlaunch_config_pathpathexistsopenreadappendlenjoin)r=   launch_run_configfplaunch_configichunkskeyconfig_stringr:   r:   r;   _handle_launch_config<   sH   



r\   T)frozenc                   @  s4   e Zd ZU ded< 	 ded< 	 ded< 	 ded< dS )_ConfigPartsr>   base_no_artifactssweep_no_artifactslaunch_no_artifacts	artifactsN)__name__
__module____qualname____annotations__r:   r:   r:   r;   r^   ]   s   
 r^   c                   @  s   e Zd ZdZd	ddZdS )
_PrinterCallbackzA callback for displaying messages after a printer is configured.

    This is used for a few messages that may be generated before run settings
    are computed, which are necessary for creating a printer.
    run_printerprinter.Printerr.   Nonec                 C     dS )z.Display information through the given printer.Nr:   )selfrh   r:   r:   r;   __call__w       z_PrinterCallback.__call__Nrh   ri   r.   rj   )rc   rd   re   __doc__rm   r:   r:   r:   r;   rg   p   s    rg   c                   C  s   dd S )z0A printer callback that does not print anything.c                 S     d S Nr:   _r:   r:   r;   <lambda>}   rn   z(_noop_printer_callback.<locals>.<lambda>r:   r:   r:   r:   r;   _noop_printer_callback{   s   rv   cbsIterable[_PrinterCallback]c                   s   d fdd}|S )	zBReturns a printer callback that runs the given callbacks in order.rh   ri   r.   rj   c                   s    D ]}||  qd S rr   r:   )rh   cbrw   r:   r;   do_callbacks   s   
z/_concat_printer_callbacks.<locals>.do_callbacksNro   r:   )rw   r{   r:   rz   r;   _concat_printer_callbacks   s   r|   c                   @  s   e Zd ZdQddZedRd
dZdSddZdTddZdUddZdVddZ	dWddZ
dXdd ZdYd"d#ZdYd$d%Z	&	&	&dZd[d-d.Zd\d/d0Zd]d5d6Z	7d^d_d=d>Zd\d?d@Zd\dAdBZd\dCdDZdYdEdFZejd`dHdIZdadKdLZdbdOdPZd&S )c
_WandbInitwlwandb_setup._WandbSetupr$   telemetry.TelemetryRecordr.   rj   c                 C  s6   || _ || _	 d | _d | _d | _g | _d | _g | _d S rr   )_wl
_telemetrykwargsrunbackend_teardown_hooksnotebookdeprecated_features_used)rl   r~   r$   r:   r:   r;   __init__   s   
z_WandbInit.__init__wandb_setup.Loggerc                 C  s
   | j  S rr   )r   _get_loggerrl   r:   r:   r;   _logger   s   
z_WandbInit._loggerinit_settingsr-   c                 C  sT   | j j }|| |js|jrdS |j}tj|j	|j
|jp!|j||du d dS )zLog in if we are not creating an offline or disabled run.

        This may change the W&B singleton settings.

        Args:
            init_settings: Settings passed to `wandb.init()` or set via
                keyword arguments.
        N)hostforce_silentrZ   update_api_key)r   r=   
model_copyupdate_from_settings_noop_offlineapi_keyr   _loginbase_urlr   quietsilent)rl   r   run_settingsexplicit_keyr:   r:   r;   maybe_login   s   


z_WandbInit.maybe_loginrg   c                 C  s   | j  st S ddd}|S )	zWarn if environment variables changed after `wandb.setup()`.

        Returns:
            A callback to print any generated warnings.
        rh   ri   r.   rj   c                 S  s,   d|  tdd d}| j|dd d S )NzChanges to your `wandb` environment variables will be ignored because your `wandb` session has already started. For more information on how to modify your settings with `wandb.init()` arguments, please refer to z
wandb-initzthe W&B docs.warnlevel)linkr   urldisplay)rh   liner:   r:   r;   print_warning   s
   zB_WandbInit.warn_env_vars_change_after_setup.<locals>.print_warningNro   )r   did_environment_changerv   )rl   r   r:   r:   r;    warn_env_vars_change_after_setup   s   


z+_WandbInit.warn_env_vars_change_after_setupc                   s   d| j jjr
dn| j jjrdst S g  d fd	d
}|jdur.|d|j d|_|jdur<|d|j d|_|jdurJ|d|j d|_d fdd}|S )zClear project/entity/run_id keys if in a Sweep or a Launch context.

        Args:
            init_settings: Settings specified in the call to `wandb.init()`.

        Returns:
            A callback to print any generated warnings.
        rC   zwhen running a sweepz(when running from a wandb launch contextrZ   r8   valuer.   rj   c              	     s"     d|  d|d d d S )Nz	Ignoring  r   )rR   )rZ   r   warningswhen_doing_thingr:   r;   r      s   "z:_WandbInit.clear_run_path_if_sweep_or_launch.<locals>.warnNprojectentityrun_idrh   ri   c                   s    D ]	}| j |dd qd S )Nr   r   )r   )rh   warning)r   r:   r;   print_warnings  s   zD_WandbInit.clear_run_path_if_sweep_or_launch.<locals>.print_warnings)rZ   r8   r   r8   r.   rj   ro   )r   r=   sweep_idrD   rv   r   r   r   )rl   r   r   r   r:   r   r;   !clear_run_path_if_sweep_or_launch   s(   




z,_WandbInit.clear_run_path_if_sweep_or_launch!tuple[Settings, _PrinterCallback]c                 C  s   |   | |g}| jj }|| |js+t r+t	|r+| j
d d| jj_|j}|jsB|jsB| j }|durB|| |du rId|_|jdu rVtj|j|_t |_|jrv|jsv|jped}t }|rs| d| n||_|t|fS )zReturns the run's settings and any warnings.

        Args:
            init_settings: Settings passed to `wandb.init()` or set via
                keyword arguments.
        z'set run ID and group based on SageMakerTNFrC   -) r   r   r   r=   r   r   sagemaker_disabler   is_using_sagemaker
set_run_idr   infor   feature	save_coder   r   _load_user_settingsupdate_from_dictr   r4   r5   auto_project_nameprogramtimex_start_time_sharedx_labelr   r   generate_idr|   )rl   r   warning_callbacksr=   save_code_pre_user_settingsuser_settingsprefixlabelr:   r:   r;   make_run_settings	  s8   






z_WandbInit.make_run_settingsresume_filepathlib.Pathr/   c                 C  s   |  sdS | P}zt|d W W  d   S  tjy@ } z| jjd| d|d W Y d}~W d   dS d}~w tyY   | jd| d Y W d   dS w 1 s]w   Y  dS )zReturns the run_id stored in the auto-resume file, if any.

        Returns `None` if the file does not exist or is not in a valid format.

        Args:
            resume_file: The file path to use for resume='auto' mode.
        Nr   zcould not decode z
, ignoringexc_infozresume file at z did not store a run_id)rO   rP   rH   loadJSONDecodeErrorr   	exceptionKeyError)rl   r   fer:   r:   r;   _load_autoresume_run_idI  s,   



z"_WandbInit._load_autoresume_run_idr   r8   c                C  sN   |j jdd |d}td|i| W d   dS 1 s w   Y  dS )z)Write the run ID to the auto-resume file.Texist_okwr   N)parentmkdirrP   rH   dump)rl   r   r   r   r:   r:   r;   _save_autoresume_run_ide  s   "z"_WandbInit._save_autoresume_run_idr=   c                 C  s   |j dkr|jrt|j}nd}|r?| |}|sn$|jdu r-| jd|  ||_n|j|kr?t	d| d|j d |jdu rR|j
rM|j
j|_nt |_|r^| j||jd dS dS )a  Set the run ID and possibly save it to the auto-resume file.

        After this, `settings.run_id` is guaranteed to be set.

        If a `resume_from` is provided and `run_id` is not set, initialize
        `run_id` with the `resume_from` run's `run_id`.

        Args:
            settings: The run's settings derived from the environment
                and explicit values passed to `wandb.init()`.
        autoNzloaded run ID from zIgnoring ID z: loaded due to resume='auto' because the run ID is set to r   )r   r   )resumeresume_fnamepathlibPathr   r   r   r   r4   rL   resume_fromr   r   r   r   )rl   r=   resume_pathprevious_idr:   r:   r;   r   p  s4   





z_WandbInit.set_run_idc                 C  s<   d}t |j r| |_|d7 }t |j s
dS dS )a  Add a suffix to sync_dir if it already exists.

        The sync_dir uses a timestamp with second-level precision which can
        result in conflicts if a run with the same ID is initialized within the
        same second. This is most likely to happen in tests.

        This can't prevent conflicts from multiple processes attempting
        to create a wandb run simultaneously.

        Args:
            settings: Fully initialized settings other than the
                x_sync_dir_suffix setting which will be modified.
        r   N)r   r   sync_dirrO   x_sync_dir_suffix)rl   r=   indexr:   r:   r;   set_sync_dir_suffix  s
   z_WandbInit.set_sync_dir_suffixNconfigdict | str | Noneconfig_exclude_keyslist[str] | Noneconfig_include_keysr^   c           	      C  s  |r| j tdddf |r| j tdddf t|pt ||d}tt t t t d}|jsJt rJt	 }| j
||j|jd d| jj_| jjrZ| j
| jj|j|jd |rkt|trk| j
||j|jd | jjr{| j
| jj|j|jd t| }r| j
||j|jd |jd	t }|jr|jrttjd
|j|d< |jdur|jj|jj d|d< |j!dur|j!j|j!j d|d< |S )ax  Construct the run's config.

        Args:
            settings: The run's finalized settings.
            config: The config passed to `init()`.
            config_exclude_keys: Deprecated. Keys to filter out from `config`.
            config_include_keys: Deprecated. Keys to include from `config`.

        Returns:
            Initial values for the run's config.
        T)init__config_exclude_keyszsconfig_exclude_keys is deprecated. Use `config=wandb.helper.parse_config(config_object, exclude=('key',))` instead.)init__config_include_keyszsconfig_include_keys is deprecated. Use `config=wandb.helper.parse_config(config_object, include=('key',))` instead.)includeexclude)r_   r`   ra   rb   )config_targetrb   _wandbcode	code_pathN)r   stepbranch_point)"r   rR   r   r)   dictr^   r   r   r   parse_sm_config_split_artifacts_from_configr_   rb   r   r   r   r   
isinstance_sweep_configr`   r\   ra   
setdefaultr   program_relpathr"   LogicalPathrE   rN   rT   	fork_fromr   r   r   )	rl   r=   r   r   r   resultsagemaker_configrW   wandb_internalr:   r:   r;   make_run_config  s   




z_WandbInit.make_run_configc                 C  s$   | j d | jD ]}|  q	d S )Nztearing down wandb.init)r   r   r   call)rl   hookr:   r:   r;   teardown  s   

z_WandbInit.teardownconfig_sourcer   r   rb   c                 C  s4   |  D ]\}}t|r|||< q||| qd S rr   )itemsr   r   )rl   r
  r   rb   kvr:   r:   r;   r   "  s
   
z'_WandbInit._split_artifacts_from_configFbasetargetnamedeleteboolc                 C  s   t tdsd S t }tj|| d| }|r/zttj|| W n	 ty.   Y nw tj||}zt|| t	|tj|| W d S  tyT   Y d S w )Nsymlinkr   )
r7   rE   getpidrN   rT   removeOSErrorrelpathr  rename)rl   r  r  r  r  pidtmp_namer:   r:   r;   _safe_symlink.  s"   
z_WandbInit._safe_symlinkc                 O  sp   | j sdS | jr"| j r"| jdusJ | jjdd}| jd| | j jdur6| jd | j j  dS dS )zHook for the IPython pre_run_cell event.

        This pauses a run, preventing system metrics from being collected
        the run's runtime from increasing. It also uploads the notebook's code.
        Nrootzsaved code: %szpausing backend)	r   r   
save_ipynbr   log_coder   r   	interfacepublish_pause)rl   argsr   resr:   r:   r;   _pre_run_cell_hookD  s   z_WandbInit._pre_run_cell_hookc                 O  s6   | j du s| j jdu rdS | jd | j j  dS )zuHook for the IPython post_run_cell event.

        Resumes collection of system metrics and the run's timer.
        Nzresuming backend)r   r   r   r   publish_resumerl   r"  r   r:   r:   r;   _post_run_cell_hookV  s   z_WandbInit._post_run_cell_hookc                 C  s   | j sJ | j j}| jr| j | j | j  r-| jdusJ | jjdd}| jd| | jd |j	d| j
 |j	d| j |jj|j_|j`dS )z<Teardown hooks and display saving, called with wandb.finish.Nr  zsaved code and history: %szcleaning up jupyter logicpre_run_cellpost_run_cell)r   shellr   save_historyr  r  r   r   events
unregisterr$  r'  display_pub_orig_publishpublish)rl   r   r#  r:   r:   r;   _jupyter_teardowna  s   


z_WandbInit._jupyter_teardownc                   s   t j|_jj t jds9jd  jj	 j_
 jdj  jdj jtjtj d
d fdd	}| j_	dS )z&Add hooks, and session history saving.r/  zconfiguring jupyter hooks %sr(  r)  Nr.   rj   c                   s@    j j| fd|i| jd usJ j j| |d d S )Nmetadata)datar2  )r.  r/  r   save_displayexecution_count)r3  r2  r   r   rl   r:   r;   r0    s
   z/_WandbInit.monkeypatch_ipython.<locals>.publishrr   r.   rj   )r4   jupyterNotebookr   r*  r7   r.  r   r   r0  r/  r,  registerr$  r'  r   rR   r+   r1  r,   EARLY)rl   r=   r0  r:   r6  r;   monkeypatch_ipythonu  s   z_WandbInit.monkeypatch_ipythonIterator[None]c                 #  s   t tj|j t tj|j t tj|j t |j t |j	 |j
rn| jtj|jtj|jtj|jdd | jtj|j|jtj|jdd | jtj|j|jtj|jdd |jssJ t|jt|jt rtj d d fdd}z.| jt|tjd | j t!d	 | j"#d
|j  | j"#d|j  dV  W dS  t$y   |   w )zSet up the run's log directory.

        This is a context manager that closes and unregisters the log handler
        in case of an uncaught exception, so that future logged messages do not
        modify this run's log file.
        T)r  Fr.   rj   c                     s(    sd t d   d S d S )NTr4   )logging	getLoggerremoveHandlercloser:   disposedhandlerr:   r;   dispose_handler  s
   z;_WandbInit.setup_run_log_directory.<locals>.dispose_handler)r  stager4   zLogging user logs to zLogging internal logs to Nr7  )%r    mkdir_exists_okrE   rN   dirnamelog_userlog_internal	sync_file	files_dir_tmp_code_dirr  r  sync_symlink_latestbasenamelog_symlink_userlog_symlink_internalr   r   add_file_handlerr   r   r
   is_debugsetLevelr>  DEBUGr   rR   r+   r,   LATEr   _early_logger_flushr?  r   r   	Exception)rl   r=   rE  r:   rB  r;   setup_run_log_directory  sb   

z"_WandbInit.setup_run_log_directoryr*   c                   sX  t  }ttdt |t ddd| ddd	dtjj	
 _j|j j|j t _fdd_d	d _j_d
d _dd _dD ]
}t|dd  qOdD ]}tt|tdd  q\G dd d G  fddd}| _t _d_d_d_d_t j!j"jjjj#jjj$j%j&d S )a)  Returns a Run-like object where all methods are no-ops.

        This method is used when the `mode` setting is set to "disabled", such as
        by wandb.init(mode="disabled") or by setting the WANDB_MODE environment
        variable to "disabled".

        It creates a Run object that mimics the behavior of a normal Run but doesn't
        communicate with the W&B servers.

        The returned Run object has all expected attributes and methods, but they
        are no-op versions that don't perform any actual logging or communication.
        disabledNzdummy-dummy)	moderoot_dirr   run_tags	run_notes	run_grouprun_namer   r   r=   c                   s    j | S rr   )summaryupdate)r3  rt   __)drunr:   r;   ru     s    z._WandbInit.make_disabled_run.<locals>.<lambda>c                  _  s   t  S rr   )r!   unset_globalsrt   re  r:   r:   r;   ru     s    c                  _  s   t jjdS )Nr[  )r4   sdkwandb_metricMetricrh  r:   r:   r;   ru     s    c                  _  rk   )NFr:   rh  r:   r:   r;   ru     rn   )alertfinish_artifactget_project_urlget_sweep_urlget_urllink_artifact
link_modeluse_artifactr  	log_model	use_modelmark_preemptingrestorestatuswatchunwatchupsert_artifact_finishc                  _  rq   rr   r:   rh  r:   r:   r;   ru     rn   )r   project_url	sweep_urlc                 S  rq   rr   r:   rs   r:   r:   r;   ru     rn   c                   @  s$   e Zd ZdZdddZdd
dZdS )z4_WandbInit.make_disabled_run.<locals>._ChainableNoOpzEAn object that allows chaining arbitrary attributes and method calls.rt   r8   r.   r	   c                 S     | S rr   r:   )rl   rt   r:   r:   r;   __getattr__     z@_WandbInit.make_disabled_run.<locals>._ChainableNoOp.__getattr__r   re  c                 _  r  rr   r:   )rl   rt   re  r:   r:   r;   rm     r  z=_WandbInit.make_disabled_run.<locals>._ChainableNoOp.__call__N)rt   r8   r.   r	   )rt   r   re  r   r.   r	   )rc   rd   re   rp   r  rm   r:   r:   r:   r;   _ChainableNoOp  s    
r  c                      s<   e Zd ZdddZddd	Zd fddZd fddZdS )z9_WandbInit.make_disabled_run.<locals>._ChainableNoOpFieldr.   rj   c                 S  s
   d | _ d S rr   _valuer   r:   r:   r;   r   "     
zB_WandbInit.make_disabled_run.<locals>._ChainableNoOpField.__init__instancer   r   c                 S  s
   || _ d S rr   r  )rl   r  r   r:   r:   r;   __set__%  r  zA_WandbInit.make_disabled_run.<locals>._ChainableNoOpField.__set__ownertypec                   s   | j d u r  S | j S rr   r  )rl   r  r  r  r:   r;   __get__(  s   zA_WandbInit.make_disabled_run.<locals>._ChainableNoOpField.__get__r"  r   r  c                   s     S rr   r:   r&  r  r:   r;   rm   +  s   zB_WandbInit.make_disabled_run.<locals>._ChainableNoOpField.__call__Nr7  )r  r   r   r   r.   rj   )r  r   r  r  r.   r   )r"  r   r   r   r.   r  )rc   rd   re   r   r  r  rm   r:   r  r:   r;   _ChainableNoOpField  s
    

r  r   )r   r   logrc  savers  log_artifactdefine_metricrl  ry  rz  )'r   r   r*   r-   tempfile
gettempdirtupler4   ri  wandb_configConfig_configrd  r`   r_   r   rc  r  finishrT   r  r  setattrr  propertyr  r   _start_time_starting_step_step
_attach_id_backendr!   
set_globalr   rs  rl  ry  rz  )rl   r   r   symbolattrr  r:   )r  rf  r;   make_disabled_run  sb   


	
z_WandbInit.make_disabled_runrh   ri   c              	   C  s  | j d td | jd usJ | j d|j d|j  | jj }r|jdv s4|jdkrDt	
 rD|d|jd | j  n=|jd	krP| j d
 n1|jdkrZtd|d|jd tj|d}d|j_W d    |S 1 szw   Y  |S | j d | j }| j d |j| |jd t||d}|  | j d t|j||j|jd}tj|| jd}tj|_t  |_ t!  dt"  # |_t$ }	|	r|	|_%|j&rd|j'_(|j)rd|j'_*|j+rd|j'_,|j-rd|j'_.|j/rd|j'_0|j1rd|j_1tj2ddD ]
}
t3|j4|
d qt5j67dr'd|j'_8|j9r/d|j'_:|j;r7d|j_<|j=r?d|j_>|j?rLt@d d|j_A|jBrTd|j_Ctj'D r^d|j_DW d    n	1 siw   Y  |jEs| jFr}|G| jF n|H  | jID ]\}}tJ|||d q| j d |K| j |L| |M| jN |jOsJ |jOP  |jQs|jRs|S  |jTr|jrt@d|jU d d }|jV}| j d| d  |jOW|}z(tXjY|d!d"}tZ||t[\tXj]||jOd#}W d    n	1 sw   Y  W n t^y#   t_d$| d%d& d' d w |j`s*J tab|j`jc }r6||j`dd(sAtd)|j`jejfrk| j d* tj|d}|j`jejf|j_fW d    n	1 sfw   Y  |g|j`je | j d+ |jOs~J |jOh|}z|jid,d- W n
 t^y   Y nw |jOj  | jd usJ || _e|k  |j1r|jlrt5jmn|jlr|o|jl |jpq D ]\}}|jrjs||idd. q|jt7tjujv}|r|w| || _x|jd	krty| |z  | j d/ |S )0Nzcalling init triggerson_initz%wandb.init called with sweep_config: z	
config: )Tfinish_previousdefaultz1Finishing previous runs because reinit is set to r   
create_newz[wandb.init() called while a run is active, and reinit is set to 'create_new', so continuingmustzCannot resume a run while another run is active. You must either finish it using run.finish(), or use reinit='create_new' when calling wandb.init().z?wandb.init() called while a run is active and reinit is set to z , so returning the previous run.r   Tzstarting backendzsending inform_init request)r=   r   r=   servicezbackend started and connected)r   r=   sweep_configrW   )r   objr   )only_importedPEXzThe `shared` mode feature is experimental and may change. Please contact support@wandb.com for guidance and to report any issues.)r   messager   zupdated telemetryz_`resume` will be ignored since W&B syncing is set to `offline`. Starting a new run with run id z"communicating run to backend with z second timeoutzWaiting for wandb.init()...)default_text)timeoutdisplay_progressz'Run initialization has timed out after z sec.z: Please try increasing the timeout with the `init_timeout`zB setting: `wandb.init(settings=wandb.Settings(init_timeout=120))`.r   z5Assertion failed: run_result is missing the run fieldzrun resumedzstarting run threads in backend   r  )allow_val_changez.run started, returning control to user process){r   r   r   r  r   r`   r_   most_recent_active_runreinit
wb_ipythonin_notebookr   finish_all_active_runsr   r4   r   r$   contextr   init_return_runensure_serviceinform_initto_protor   r   ensure_launchedr*   ra   r   r1   cli_versionplatformpython_versionsystemmachinelowerr<   huggingface_version_jupyterr
   r8  _ipythonr   _colabcolab_kagglekaggle_windowswindowsrD   list_telemetry_importsr  imports_initrE   rF   rG   pex_aws_lambda
aws_lambdax_flow_control_disabledflow_control_disabledx_flow_control_customflow_control_customr   rL   shared_moder   user_provided_labeldcgm_profiling_enabledlabel_disabler   _label_probe_notebook_label_probe_mainr   r'   _set_library_set_backend_set_teardown_hooksr   r   publish_headerdisable_gitx_disable_machine_info_populate_git_infor   idinit_timeoutdeliver_runr   progress_printerr(   	functoolspartialloop_printing_operation_statsTimeoutErrorr   
run_resultr   to_exceptionerrorHasFieldr   resumed_set_run_objdeliver_run_startwait_orpublish_probe_system_info!_handle_launch_artifact_overridesrM   rN   rO   r  rb   r  r   rd  _launch_artifact_mappingr5   LAUNCH_JOB_ARTIFACT_SLOT_NAMErs  r   _set_global_run	_on_start)rl   r=   r   rh   previous_runtelr  r   r   
hf_versionmodule_namedeprecated_featuremsgr  r  run_init_handler  r  run_start_handler  r  job_artifactr:   r:   r;   initF  s  








/







z_WandbInit.init)r~   r   r$   r   r.   rj   )r.   r   )r   r-   r.   rj   r.   rg   )r   r-   r.   rg   )r   r-   r.   r   )r   r   r.   r/   )r   r   r   r8   r.   rj   r=   r-   r.   rj   )NNN)
r=   r-   r   r   r   r   r   r   r.   r^   r7  )r
  r   r   r   rb   r   r.   rj   )F)
r  r8   r  r8   r  r8   r  r  r.   rj   )r=   r-   r.   r=  )r   r^   r.   r*   )r=   r-   r   r^   rh   ri   r.   r*   )rc   rd   re   r   r  r   r   r   r   r   r   r   r   r   r  r	  r   r  r$  r'  r1  r<  
contextlibcontextmanagerrY  r  r  r:   r:   r:   r;   r}      s8    


"

+
@


/
i





Eqr}   r  	attach_idr   r   
Run | Nonec             
   C  s  | p|} | du |du A st d| p|r|jnd} | du r!t dt }| }| }z|j| d}W n tyI } zt d|  |d}~ww |j	 }|
| |jj|jjd t||d}	|	  |d |du rut|d	}n|j|d	 || ||	 |	jsJ |	j| }
z|
jd
d}W n ty   t dw |jj}|jr|jjrt d|jj ||j t| |   |S )a3  Attach to a run currently executing in another process/thread.

    Args:
        attach_id: (str, optional) The id of the run or an attach identifier
            that maps to a run.
        run_id: (str, optional) The id of the run to attach to.
        run: (Run, optional) The run instance to attach
    Nz;Either (`attach_id` or `run_id`) or `run` must be specifiedzPEither `attach_id` or `run_id` must be specified or `run` must have `_attach_id`)r
  zUnable to attach to run )r   r   r\  r  z$attach backend started and connectedrb  r  r  zTimeout attaching to runzFailed to attach to run: )!r   r  r   	singletonr   r  inform_attachrX  r=   r   r   r   r   r\  r   r  r   r*   _initr  r  r   deliver_attachr  r  responseattach_responser  r  r  r   r  
_on_attach)r
  r   r   r   loggerr  attach_settingsr   r=   r   attach_handleattach_resultr  r:   r:   r;   _attach>  s\   
	



r  r*   rj   c                 C  sH   t j| | j| j| j| j| j| j| j| j	| j
| j| j| j| j| jd dS )zwSet `wandb.run` and point some top-level functions to its methods.

    Args:
        run: The run to make global.
    )r   r   r  rc  r  rs  r  r  rl  ry  rz  rv  rt  ru  rr  N)r!   r  r   r  rc  r  rs  r  r  rl  ry  rz  rv  rt  ru  rr  r  r:   r:   r;   r    s"   
r  c                  C  .   t tjd dkrdS ddlm}  |   dS )z2Patch OpenAI gym to log to the global `wandb.run`.gymr   Nr  )rS   r4   patchedwandb.integrationr  monitorr  r:   r:   r;   _monkeypatch_openai_gym     r  c                  C  r  )z3Patch TensorBoard to log to the global `wandb.run`.tensorboardr   N)r   )rS   r4   r  r  r   patch)	tb_moduler:   r:   r;   _monkeypatch_tensorboard  r  r#  c                 C  s   d}z
t j| jdd W n ty"   tjd| j dd d}Y nw t | jt jt jB s<tjd| j ddd d}|s@dS t	
 }t |t jt jB sVtd	| d
|| _tjd| ddd t j| jdd dS )a|  Try to create the root directory specified in settings.

    If creation fails due to permissions or other errors,
    falls back to using the system temp directory.

    Args:
        settings: The runs settings containing root_dir configuration.
            This function may update the root_dir to a temporary directory
            if the parent directory is not writable.
    FTr   z Unable to create root directory )repeatzPath z wasn't read/writableNzSystem temp directory (zm) is not writable/readable, please set the `dir` argument in `wandb.init()` to a writable/readable directory.z$Falling back to temporary directory r   )rE   makedirsr]  r  r4   rL   accessW_OKR_OKr  r  rJ   )r=   fallback_to_temp_dirtmp_dirr:   r:   r;   try_create_root_dir  s:   


r+  r   r   dirStrPath | Noner  r  notestagsSequence[str] | Noner   dict[str, Any] | str | Noner   r   r   r  bool | Nonegroupjob_typer\  9Literal['online', 'offline', 'disabled', 'shared'] | Noner   r  Sbool | Literal[None, 'default', 'return_previous', 'finish_previous', 'create_new']r   7bool | Literal['allow', 'never', 'must', 'auto'] | Noner   r  r   r   sync_tensorboardmonitor_gym Settings | dict[str, Any] | None	anonymousr&   c           $   
   C  s  t  }t }t|trtd
i |}nt|tr|}|dur"||_|dur)||_|dur0||_| dur7| |_|dur>||_	|durGt
||_|durN||_|durU||_|dur\||_|turc||_|durj||_|durq||_|durx||_|dur||_|dur||_|dur||_|dur||_|dur||_|dur||_|durd|j_d}zt }t||}|| ||\}}t|j	t r|j!"t#dddf |jdurd|j_$|jdurd|j_%|jdurd|j_&|j'rd|j_(|jdurd|j_)|jdurd|j_*|+| |,| t-.|}|| t/0 u} | 1t23|j |j4||||	d}!|j5rC|6|!W  d   W S t7| | 1|8| |j9rX|:| |r^t;  t<j=d rhd|j_>|jrst?  d|j_@|jAr{d|j_B|C||!|}"tDE|j|j |"W  d   W S 1 sw   Y  W dS  tFy }# z|r|G jHd|#d  d}#~#w tIy }# z|r|G jJd	|#d tK L|# W Y d}#~#dS d}#~#ww )u)  Start a new run to track and log to W&B.

    In an ML training pipeline, you could add `wandb.init()` to the beginning of
    your training script as well as your evaluation script, and each piece would
    be tracked as a run in W&B.

    `wandb.init()` spawns a new background process to log data to a run, and it
    also syncs data to https://wandb.ai by default, so you can see your results
    in real-time. When you're done logging data, call `wandb.Run.finish()` to end the run.
    If you don't call `run.finish()`, the run will end when your script exits.

    Run IDs must not contain any of the following special characters `/ \ # ? % :`

    Args:
        entity: The username or team name the runs are logged to.
            The entity must already exist, so ensure you create your account
            or team in the UI before starting to log runs. If not specified, the
            run will default your default entity. To change the default entity,
            go to your settings and update the
            "Default location to create new projects" under "Default team".
        project: The name of the project under which this run will be logged.
            If not specified, we use a heuristic to infer the project name based
            on the system, such as checking the git root or the current program
            file. If we can't infer the project name, the project will default to
            `"uncategorized"`.
        dir: The absolute path to the directory where experiment logs and
            metadata files are stored. If not specified, this defaults
            to the `./wandb` directory. Note that this does not affect the
            location where artifacts are stored when calling `download()`.
        id: A unique identifier for this run, used for resuming. It must be unique
            within the project and cannot be reused once a run is deleted. For
            a short descriptive name, use the `name` field,
            or for saving hyperparameters to compare across runs, use `config`.
        name: A short display name for this run, which appears in the UI to help
            you identify it. By default, we generate a random two-word name
            allowing easy cross-reference runs from table to charts. Keeping these
            run names brief enhances readability in chart legends and tables. For
            saving hyperparameters, we recommend using the `config` field.
        notes: A detailed description of the run, similar to a commit message in
            Git. Use this argument to capture any context or details that may
            help you recall the purpose or setup of this run in the future.
        tags: A list of tags to label this run in the UI. Tags are helpful for
            organizing runs or adding temporary identifiers like "baseline" or
            "production." You can easily add, remove tags, or filter by tags in
            the UI.
            If resuming a run, the tags provided here will replace any existing
            tags. To add tags to a resumed run without overwriting the current
            tags, use `run.tags += ("new_tag",)` after calling `run = wandb.init()`.
        config: Sets `wandb.config`, a dictionary-like object for storing input
            parameters to your run, such as model hyperparameters or data
            preprocessing settings.
            The config appears in the UI in an overview page, allowing you to
            group, filter, and sort runs based on these parameters.
            Keys should not contain periods (`.`), and values should be
            smaller than 10 MB.
            If a dictionary, `argparse.Namespace`, or `absl.flags.FLAGS` is
            provided, the key-value pairs will be loaded directly into
            `wandb.config`.
            If a string is provided, it is interpreted as a path to a YAML file,
            from which configuration values will be loaded into `wandb.config`.
        config_exclude_keys: A list of specific keys to exclude from `wandb.config`.
        config_include_keys: A list of specific keys to include in `wandb.config`.
        allow_val_change: Controls whether config values can be modified after their
            initial set. By default, an exception is raised if a config value is
            overwritten. For tracking variables that change during training, such as
            a learning rate, consider using `wandb.log()` instead. By default, this
            is `False` in scripts and `True` in Notebook environments.
        group: Specify a group name to organize individual runs as part of a larger
            experiment. This is useful for cases like cross-validation or running
            multiple jobs that train and evaluate a model on different test sets.
            Grouping allows you to manage related runs collectively in the UI,
            making it easy to toggle and review results as a unified experiment.
        job_type: Specify the type of run, especially helpful when organizing runs
            within a group as part of a larger experiment. For example, in a group,
            you might label runs with job types such as "train" and "eval".
            Defining job types enables you to easily filter and group similar runs
            in the UI, facilitating direct comparisons.
        mode: Specifies how run data is managed, with the following options:
        - `"online"` (default): Enables live syncing with W&B when a network
            connection is available, with real-time updates to visualizations.
        - `"offline"`: Suitable for air-gapped or offline environments; data
            is saved locally and can be synced later. Ensure the run folder
            is preserved to enable future syncing.
        - `"disabled"`: Disables all W&B functionality, making the run’s methods
            no-ops. Typically used in testing to bypass W&B operations.
        - `"shared"`: (This is an experimental feature). Allows multiple processes,
            possibly on different machines, to simultaneously log to the same run.
            In this approach you use a primary node and one or more worker nodes
            to log data to the same run. Within the primary node you
            initialize a run. For each worker node, initialize a run
            using the run ID used by the primary node.
        force: Determines if a W&B login is required to run the script. If `True`,
            the user must be logged in to W&B; otherwise, the script will not
            proceed. If `False` (default), the script can proceed without a login,
            switching to offline mode if the user is not logged in.
        reinit: Shorthand for the "reinit" setting. Determines the behavior of
            `wandb.init()` when a run is active.
        resume: Controls the behavior when resuming a run with the specified `id`.
            Available options are:
        - `"allow"`: If a run with the specified `id` exists, it will resume
            from the last step; otherwise, a new run will be created.
        - `"never"`: If a run with the specified `id` exists, an error will
            be raised. If no such run is found, a new run will be created.
        - `"must"`: If a run with the specified `id` exists, it will resume
            from the last step. If no run is found, an error will be raised.
        - `"auto"`: Automatically resumes the previous run if it crashed on
            this machine; otherwise, starts a new run.
        - `True`: Deprecated. Use `"auto"` instead.
        - `False`: Deprecated. Use the default behavior (leaving `resume`
            unset) to always start a new run.
            If `resume` is set, `fork_from` and `resume_from` cannot be
            used. When `resume` is unset, the system will always start a new run.
        resume_from: Specifies a moment in a previous run to resume a run from,
            using the format `{run_id}?_step={step}`. This allows users to truncate
            the history logged to a run at an intermediate step and resume logging
            from that step. The target run must be in the same project.
            If an `id` argument is also provided, the `resume_from` argument will
            take precedence.
            `resume`, `resume_from` and `fork_from` cannot be used together, only
            one of them can be used at a time.
            Note that this feature is in beta and may change in the future.
        fork_from: Specifies a point in a previous run from which to fork a new
            run, using the format `{id}?_step={step}`. This creates a new run that
            resumes logging from the specified step in the target run’s history.
            The target run must be part of the current project.
            If an `id` argument is also provided, it must be different from the
            `fork_from` argument, an error will be raised if they are the same.
            `resume`, `resume_from` and `fork_from` cannot be used together, only
            one of them can be used at a time.
            Note that this feature is in beta and may change in the future.
        save_code: Enables saving the main script or notebook to W&B, aiding in
            experiment reproducibility and allowing code comparisons across runs in
            the UI. By default, this is disabled, but you can change the default to
            enable on your settings page.
        tensorboard: Deprecated. Use `sync_tensorboard` instead.
        sync_tensorboard: Enables automatic syncing of W&B logs from TensorBoard
            or TensorBoardX, saving relevant event files for viewing in
            the W&B UI.
        monitor_gym: Enables automatic logging of videos of the environment when
            using OpenAI Gym.
        settings: Specifies a dictionary or `wandb.Settings` object with advanced
            settings for the run.

    Returns:
        A `Run` object.

    Raises:
        Error: If some unknown or internal error happened during the run
            initialization.
        AuthenticationError: If the user failed to provide valid credentials.
        CommError: If there was a problem communicating with the WandB server.
        UsageError: If the user provided invalid arguments.
        KeyboardInterrupt: If user interrupts the run.

    Examples:
    `wandb.init()` returns a `Run` object. Use the run object to log data,
    save artifacts, and manage the run lifecycle.

    ```python
    import wandb

    config = {"lr": 0.01, "batch_size": 32}
    with wandb.init(config=config) as run:
        # Log accuracy and loss to the run
        acc = 0.95  # Example accuracy
        loss = 0.05  # Example loss
        run.log({"accuracy": acc, "loss": loss})
    ```
    NT)run__reinit_boolzeUsing a boolean value for 'reinit' is deprecated. Use 'return_previous' or 'finish_previous' instead.)r=   r   r   r   r   interruptedr   zerror in wandb.init()r:   )Mr$   TelemetryRecordr-   r   r   run_job_typer]  r   r   r  r  r^  r`  ra  r_  r%   r;  r\  r   r   r8  r   r   r  r   r   set_init_configr   r  r}   r   r   r  r   rR   r   set_init_idset_init_nameset_init_tagsr   offline	fork_moderewind_moder   r   r#   new_printerr  	ExitStackenter_contextr   
log_to_runr  r   r  r+  rY  r  r<  r  r4   r  tensorboard_patchr#  tensorboard_syncx_server_side_derived_summaryserver_side_derived_summaryr  r   setupKeyboardInterruptr   r   rX  r   r   reraise)$r   r   r,  r  r  r.  r/  r   r   r   r  r3  r4  r\  r   r  r   r   r  r   r   r8  r9  r=   r;  init_telemetryr   r~   wir   show_warningsrh   
exit_stackrA   r   r   r:   r:   r;   r    s    N













*'r  )r.   r/   )r=   r-   r.   r>   r  )rw   rx   r.   rg   )NN)r
  r/   r   r/   r   r  r.   r  )r   r*   r.   rj   r7  r  )4r   r/   r   r/   r,  r-  r  r/   r  r/   r.  r/   r/  r0  r   r1  r   r   r   r   r  r2  r3  r/   r4  r/   r\  r5  r   r2  r  r6  r   r7  r   r/   r  r/   r   r2  r   r2  r8  r2  r9  r2  r=   r:  r;  r&   r.   r*   )\rp   
__future__r   r  dataclassesr  rH   r>  rE   r   r  r2   r  r   collections.abcr   r   r   typing_extensionsr   r   r   r	   r4   	wandb.envr
   r   wandb.analyticsr   wandb.errorsr   r   r   wandb.errors.linksr   wandb.errors.utilr   r  r   r   wandb.proto.wandb_telemetry_pb2r   wandb.sdk.libr   r  r   r   r   wandb.sdk.lib.pathsr   
wandb.utilr   rC   r   r   backend.backendr   libr   r    r!   r"   r#   r$   lib.deprecationr%   r&   r'   mailboxr(   wandb_helperr)   	wandb_runr*   r+   r,   wandb_settingsr-   r<   r\   	dataclassr^   rg   rv   r|   r}   r  r  r  r#  r+  r  r:   r:   r:   r;   <module>   s    
 


!

       :
J




0
