o
    niR                     @  s4  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ZddlZddl	Z	ddl
Z
ddlmZmZmZmZ ejdkrAddlmZ n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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'm(Z( ddl)m*Z* ddl+m,Z,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z2m3Z3 ddl4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z:m;Z;m<Z< ddl=m>Z> erddl?m@ZA daBdeCd< d[dd ZDd\d"d#ZEd]d'd(ZFd^d,d-ZGG d.d/ d/ZH		d_dd0d`d5d6ZI																									dadbdYdZZJdS )ca  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)TYPE_CHECKINGAnyLiteralSequence)      )Self)trigger)	CommErrorError
UsageError)url_registry)ProtobufErrorHandler)	sagemaker)runid)StrPath)_is_artifact_representation   )wandb_loginwandb_setup)Backend)SummaryDisabled
filesystemmoduleprinter	telemetry)
Deprecated	deprecate)MailboxMailboxProgress)parse_config)RunTeardownHookTeardownStage)Settings)wandb_internal_pb2zlogging.Logger | Nonelogger
log_objectlogging.LoggerreturnNonec                 C  s   | a dS )zConfigure module logger.N)r'   )r(    r,   R/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/wandb/sdk/wandb_init.py_set_logger6   s   r.   
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   )transr,   r,   r-   _huggingface_version<   s
   


r:   backendr   boolc                 C  sH   t | jdd }|r| d uS | j }|jdkrdS |jdr"dS dS )Nparent_processMainProcessFzProcess-T)getattr_multiprocessingcurrent_processname
startswith)r;   r=   processr,   r,   r-   _maybe_mp_processD   s   


rE   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)rF   launch_run_configfplaunch_configichunkskeyconfig_stringr,   r,   r-   _handle_launch_configR   sH   



re   c                   @  s   e Zd ZU ded< dBddZdBddZ										dCdDddZdBddZdEddZdFdGd!d"Z		#dHdId)d*Z
dJd.d/ZdJd0d1ZdBd2d3ZdKd5d6ZdKd7d8ZdLd:d;ZdMd>d?ZdLd@dAZd	S )N
_WandbInitztelemetry.TelemetryRecord_init_telemetry_objr*   r+   c                 C  s\   d | _ d | _i | _i | _i | _d | _d | _g | _d | _d | _	t
 | _
t | _t | _d S N)kwargsrF   sweep_configr`   configrunr;   _teardown_hooks_wlnotebookr   new_printerr   TelemetryRecordrg   dictdeprecated_features_usedselfr,   r,   r-   __init__v   s   

z_WandbInit.__init__c                   s   t jj}|du r
dS ddh  fdd|j D } fddtj D }t| t| ks>t|	 t|	 krVd| j
tdd	 d
}| j
j|dd dS dS )zWarn if environment variables change after wandb singleton is initialized.

        Any settings from environment variables set after the singleton is initialized
        (via login/setup/etc.) will be ignored.
        NWANDB_SERVICEWANDB_KUBEFLOW_URLc                   (   i | ]\}}| d r| vr||qS WANDB_rC   .0kvexclude_env_varsr,   r-   
<dictcomp>       z?_WandbInit.warn_env_vars_change_after_setup.<locals>.<dictcomp>c                   ry   rz   r|   r}   r   r,   r-   r      r   zChanges 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)r   _WandbSetup	_instance_environitemsrN   rO   setkeysvaluesr   linkr   urldisplay)ru   	singletonsingleton_envos_envliner,   r   r-    warn_env_vars_change_after_setup   s*   


z+_WandbInit.warn_env_vars_change_after_setupNinit_settingsr%   rk   dict | str | Noneconfig_exclude_keyslist[str] | Noneconfig_include_keysallow_val_changebool | Nonemonitor_gymc                 C  sf  |    i }|jdkr|j|d< |jr|j|d< |r"tjdi |nd}tj|d| _| jdus2J t| j	  | jj
 }	|	jrJ|	j|_|  |	jrU|	j|_|  |	| |	jr`t nt }
|
r|
dd}t \}}|r|rz||d< |	| tj|	d |	| tj| jd}d	|j_W d   n1 sw   Y  tj| jd+}|durd	|j_|	jdurd	|j_|	j durd	|j_!|	j"durd	|j_#W d   n1 sw   Y  |rd
| j$d< |rd| j$d< t%|pt ||d}t | _&| jj'pt }t | _(t | _)|
| jj*|fD ]}|sq| +|| j( q|r,| +|| j& |r>t,tj-d dkr>tj./  tj-d r`tj| jd}d	|j_0W d   n	1 s[w   Y  |	j1rt,tj-d dkrstj23  tj| jd}d	|j_4W d   n	1 sw   Y  |	j5s|	j6st7j8|	j9|	j:d	|	j;p|	j<|	j=d t }|dusJ dd |j
j9|j
j>|j
j?|j
j:|j
j@dA D }|r|	| |	B  |	jC}|	j5s|	j6s| jD }|dur|	| |du rd|	_C|	jEdu r	tjFG|	jH|	_EtII |	_J|	j6s | K|	 |	jLr | M|	 tN|	}|r.| +|| jO |	| _
dS )zComplete setup for `wandb.init()`.

        This includes parsing all arguments, applying them with settings and enabling logging.
        disabledmodex_disable_serviceNrF   wandb_api_keyWANDB_API_KEY)objTzPUse `config=wandb.helper.parse_config(config_object, exclude=('key',))` instead.r   zPUse `config=wandb.helper.parse_config(config_object, include=('key',))` instead.r   )includeexcludegymr   tensorboard)	anonymousforce_disable_warning_silent_entityc                 S  s   i | ]\}}|d ur||qS rh   r,   r}   r,   r,   r-   r   ,  s
    z$_WandbInit.setup.<locals>.<dictcomp>)r   api_keybase_urlr   login_timeoutFr,   )Pr   r   r   r4   r%   r   setuprn   r.   _get_loggerrF   copysweep_idhandle_sweep_logicrM   handle_launch_logicupdate_from_settingssagemaker_disablerr   r   parse_sm_configrP   parse_sm_resourcesupdate_from_env_varsupdate_from_dictr   contextrg   featureset_init_configrun_nameset_init_namerun_idset_init_idrun_tagsset_init_tagsrs   r!   rj   _sweep_configrk   init_artifact_config_config_split_artifacts_from_configr\   patchedr   monitortensorboard_patchsync_tensorboardr   patchtensorboard_sync_offline_noopr   _loginr   r   quietsilententityr   r   r   r   handle_resume_logic	save_code_load_user_settingsprojectr5   auto_project_nameprogramtimex_start_time
_log_setup_jupyter_jupyter_setupre   r`   )ru   r   rk   r   r   r   r   setup_settings_dictsetup_settingsrF   sagemaker_configsagemaker_api_keysagemaker_runsagemaker_envtelrj   config_datawllogin_settingssave_code_pre_user_settingsuser_settingsr`   r,   r,   r-   r      s   













	








z_WandbInit.setupc                 C  s*   t sJ t d | jD ]}|  qd S )Nztearing down wandb.init)r'   inform   call)ru   hookr,   r,   r-   teardown^  s
   


z_WandbInit.teardownconfig_sourcerr   config_targetc                 C  s6   |  D ]\}}t|r|| j|< q||| qd S rh   )r   r   r   
setdefault)ru   r   r   r   r   r,   r,   r-   r   f  s
   z'_WandbInit._split_artifacts_from_config	log_fnamer8   r   r/   c                   s   t |  t j G fdddt j}rt d}nt d} | r0 |  tdus6J dt_	t
  tt j | jt fddtj dS )	zEnable logging to the global debug log.

        This adds a run_id to the log, in case of multiple processes on the same machine.
        Currently, there is no way to disable logging after it's enabled.
        c                      s   e Zd Zd fddZdS )	z,_WandbInit._enable_logging.<locals>.WBFilterrecordlogging.LogRecordr*   r<   c                   s
    |_ dS )NTr   )ru   r   r   r,   r-   filtery  s   z3_WandbInit._enable_logging.<locals>.WBFilter.filterN)r   r   r*   r<   )__name__
__module____qualname__r   r,   r   r,   r-   WBFilterx  s    r   zy%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d [%(run_id)s:%(filename)s:%(funcName)s():%(lineno)s] %(message)szn%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d [%(filename)s:%(funcName)s():%(lineno)s] %(message)sNFc                     s      t fS rh   )closer'   removeHandlerr,   )handlerr,   r-   <lambda>  s    z,_WandbInit._enable_logging.<locals>.<lambda>)loggingFileHandlersetLevelINFOFilter	FormattersetFormatter	addFilterr'   	propagate
addHandlerDEBUGrm   r[   r#   r$   LATE)ru   r   r   r   	formatterr,   )r   r   r-   _enable_loggingo  s.   



z_WandbInit._enable_loggingFbasetargetrB   deleter<   c                 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   rN   getpidrW   r]   removeOSErrorrelpathr  rename)ru   r  r  rB   r  pidtmp_namer,   r,   r-   _safe_symlink  s"   
z_WandbInit._safe_symlinkargsr   ri   c                 O  sj   | j d u rd S | j r | jd usJ | jjd d}td| | j jd ur3td | j j  d S d S )Nrootzsaved code: %szpausing backend)	r;   ro   
save_ipynbrl   log_coder'   r   	interfacepublish_pause)ru   r  ri   resr,   r,   r-   _pause_backend  s   


z_WandbInit._pause_backendc                 O  s8   | j d ur| j jd urtd | j j  d S d S d S )Nzresuming backend)r;   r!  r'   r   publish_resumeru   r  ri   r,   r,   r-   _resume_backend  s   
z_WandbInit._resume_backendc                 C  s   | j sJ | j j}| j   | j  r'| jdusJ | jjdd}td| td |jj	d D ]}d|j
v r@|jd| q2|jj	d D ]}d|j
v rU|jd| qG|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_cellr'  post_run_cellr$  )ro   shellsave_historyr  rl   r   r'   r   events	callbacksr   
unregisterdisplay_pub_orig_publishpublish)ru   ipythonr#  r   r,   r,   r-   _jupyter_teardown  s$   






z_WandbInit._jupyter_teardownrF   c                   s   t j|_jj t jds8t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.r0  zconfiguring jupyter hooks %sr(  r)  Nr*   r+   c                   s@    j j| fd|i| jd usJ j j| |d d S )Nmetadata)datar4  )r/  r0  ro   save_displayexecution_count)r5  r4  ri   r2  ru   r,   r-   r1    s
   z*_WandbInit._jupyter_setup.<locals>.publishrh   r*   r+   )r4   jupyterNotebookro   r*  r7   r/  r'   r   r1  r0  r,  registerr'  r$  rm   r[   r#   r3  r$   EARLY)ru   rF   r1  r,   r8  r-   r     s   z_WandbInit._jupyter_setupc                 C  s:  t tj|j t tj|j t tj|j t |j t |j	 |j
rm| 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 ttd | |j | jsJ tsJ | jt td|j  td|j  dS )zSet up logging from settings.T)r  r4   zLogging user logs to zLogging internal logs to N)r   mkdir_exists_okrN   rW   dirnamelog_userlog_internal	sync_file	files_dir_tmp_code_dirr  r  sync_symlink_latestbasenamelog_symlink_userlog_symlink_internalr.   r  	getLoggerr  rn   r'   _early_logger_flushr   )ru   rF   r,   r,   r-   r     s>   
z_WandbInit._log_setupr"   c                   s6  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  qOG 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 wandb.init(mode="disabled") is called or WANDB_MODE=disabled
        is set. 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.
        r   Nzdummy-dummy)	r   x_files_dirr   r   	run_notes	run_groupr   r   r   r   c                   s    j | S rh   )summaryupdate)r5  ___)drunr,   r-   r  1  s    z/_WandbInit._make_run_disabled.<locals>.<lambda>c                  _  s   t  S rh   )r   unset_globalsrQ  rR  r,   r,   r-   r  2  s    c                  _  s   t jjdS )NrK  )r4   sdkwandb_metricMetricrU  r,   r,   r-   r  4  s    c                  _  s   dS )NFr,   rU  r,   r,   r-   r  5      )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                  _     d S rh   r,   rU  r,   r,   r-   r  J  rY  c                   @  s$   e Zd ZdZdddZdd
dZdS )z5_WandbInit._make_run_disabled.<locals>._ChainableNoOpzEAn object that allows chaining arbitrary attributes and method calls.rQ  r8   r*   r	   c                 S     | S rh   r,   )ru   rQ  r,   r,   r-   __getattr__O     zA_WandbInit._make_run_disabled.<locals>._ChainableNoOp.__getattr__r   rR  c                 _  rl  rh   r,   )ru   rQ  rR  r,   r,   r-   __call__R  rn  z>_WandbInit._make_run_disabled.<locals>._ChainableNoOp.__call__N)rQ  r8   r*   r	   )rQ  r   rR  r   r*   r	   )r   r   r   __doc__rm  ro  r,   r,   r,   r-   _ChainableNoOpL  s    
rq  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 )z:_WandbInit._make_run_disabled.<locals>._ChainableNoOpFieldr*   r+   c                 S  s
   d | _ d S rh   _valuert   r,   r,   r-   rv   X     
zC_WandbInit._make_run_disabled.<locals>._ChainableNoOpField.__init__instancer   valuec                 S  s
   || _ d S rh   rr  )ru   ru  rv  r,   r,   r-   __set__[  rt  zB_WandbInit._make_run_disabled.<locals>._ChainableNoOpField.__set__ownertypec                   s   | j d u r  S | j S rh   rr  )ru   ru  rx  rq  r,   r-   __get__^  s   zB_WandbInit._make_run_disabled.<locals>._ChainableNoOpField.__get__r  ri   rq  c                   s     S rh   r,   r&  rz  r,   r-   ro  a  s   zC_WandbInit._make_run_disabled.<locals>._ChainableNoOpField.__call__Nr9  )ru  r   rv  r   r*   r+   )ru  r   rx  ry  r*   r   )r  r   ri   r   r*   rq  )r   r   r   rv   rw  r{  ro  r,   rz  r,   r-   _ChainableNoOpFieldU  s
    

r|  r   )rl   rk   logrO  savera  log_artifactdefine_metricrZ  rg  rh  )$r   generate_idr"   r%   tempfile
gettempdirtupler4   rV  wandb_configConfigr   rP  rj   rk   r   rO  r}  finishr]   r  r~  setattrr  r   _start_time_starting_step_step
_attach_id_backendr   
set_globalra  rZ  rg  rh  )ru   r   symbolr|  r,   )rq  rS  r-   _make_run_disabled  s^   



	
z_WandbInit._make_run_disabledhandler    c                 C  s   d}|j }| jj||d d S )NzWaiting for wandb.init()...)percent_done)r  r   progress_update)ru   r  r   r  r,   r,   r-   _on_progress_init|  s   z_WandbInit._on_progress_initc                 C  s  t d u rtdt d td | jd usJ | jd us J t d| j d| j  | jj	r5| 
 S | jjsC| jjrl| jjdurlt| jjdkrlt| jjdkrXtd	 | jjd
 }t d|j  |  n6ttjtr| jj}|rt tjjkrt d t }d|j_W d    tjS 1 sw   Y  tjS t d | jj}|rt d |j| j | jj d t! }t"| j||d}|#  t d t| j| j| j| j$d}tj|| j%d}tj&|_'t() |_)t(*  dt(+  , |_(t- }|r||_.| jjrd|j/_0| jj1rd|j/_2| jj3r#d|j/_4| jj5r,d|j/_6| jj7r5d|j/_8| jj9r>d|j_9tj:ddD ]
}t;|j<|d qDd }	| jj=dkr]| jj=}	n
t>|j?ddd  }	|	dkrqd|j/_@n|	dkr{d|j/_An|	dkrd|j/_Bn	|	dkrd|j/_CtjDEdrd|j/_F| jjGrd|j/_HtjDEtj/jIrd|j_J|rd|j_| jjKrd|j_L| jjMrd|j_N| jjOsd|j_P| jjQrtd d|j_RtS||j/_TW d    n	1 sw   Y  | jjUs	| jVr|W| jV n|X  | jYZ D ]\}
}d |
 d!| }t[t>t\d"|
 ||d# qt d$ |]| j |^| |_| j` |a| |jbsIJ |c  |jbd  | jjes`| jjfs`|g  d }| jjhrtj|d%}d|j_iW d    n	1 s}w   Y  | jjjrtd&|jk d' d }| jjl}t d(| d) |jbm|}|jn|| jodd*}|r|jp}|d u rd+| d,}tq|}|r  n|sd-rttu|jv}|d urt vd.|  |s|w  | x  ||d usJ |sd/s tyd0|jjzr't d1 tj|d%}|jjz|j_zW d    n	1 s"w   Y  |{|j ||  t d2 |rL| jj s@J |j}| j | jj d |jbsRJ |jb~|}|jnd3d4}|d u rg|  | jd usoJ | jj| || _|  | jj9r| jjrtj| jjr|| jj | jZ D ]\}}|jj||idd5 q|jEtjj}|r|| || _|  t d6 |S )7NzLogger not initializedzcalling init triggerson_initz%wandb.init called with sweep_config: z	
config: Fr   r   zLaunching multiple wandb runs using Python's threading module is not well-supported. Please use multiprocessing instead. Finishing previous run before initializing another.zfound existing run on stack: z.wandb.init() called when a run is still activeTzstarting backendzsending inform_init request)rF   r   rF   servicemailboxzbackend started and connected)rk   rF   rj   r`   )rl   r   -)only_importedthreadget_start_methodc                   S  rk  rh   r,   r,   r,   r,   r-   r    rY  z!_WandbInit.init.<locals>.<lambda>spawnfork
forkserverPEXz}The `_shared` feature is experimental and may change. Please contact support@wandb.com for guidance and to report any issues.`z` is deprecated. init__)
field_namewarning_messagerl   zupdated telemetryrl   z_`resume` will be ignored since W&B syncing is set to `offline`. Starting a new run with run id r   z"communicating run to backend with z second timeout)timeouton_progresscancelz'Run initialization has timed out after z sec. Please try increasing the timeout with the `init_timeout` setting: `wandb.init(settings=wandb.Settings(init_timeout=120))`.errorzencountered error: rl   zIt appears that something have gone wrong during the program execution as an unexpected missing field was encountered. (run_result is missing the 'run' field)zrun resumedzstarting run threads in backend   r  )r   z.run started, returning control to user process)r'   RuntimeErrorr   r
   r   rF   rn   rj   rk   r   r  reinitr   r\   _global_run_stackr4   rU   _run_idr  
isinstancerl   r"   r  rN   r  	_init_pidr   r   r   init_return_runinform_initto_protor   r   r   ensure_launchedr`   rg   r1   cli_versionplatformpython_versionsystemmachinelowerr:   huggingface_versionenvr:  _ipythonr2  _colabcolab_kagglekaggle_windowswindowsrM   list_telemetry_importsr  imports_initstart_methodr?   r@   start_spawn
start_forkstart_forkserverstart_threadrO   rP   pex_aws_lambda
aws_lambda_DISABLE_SERVICEservice_disabledx_flow_control_disabledflow_control_disabledx_flow_control_customflow_control_customx_require_legacy_servicecore_sharedshared_moderE   maybe_mplabel_disablero   _label_probe_notebook_label_probe_mainrs   r   r   r   _set_library_set_backend_set_teardown_hooksrm   _hack_set_runr!  enable_keepalivepublish_headerdisable_gitx_disable_machine_info_populate_git_infor   offlineresumeidinit_timeoutdeliver_runwaitr  
run_resultr   _cancelHasFieldr   to_exceptionr  cleanupr   r   resumed_set_run_obj_on_initinform_startdeliver_run_startabandonr[   !_handle_launch_artifact_overridesrV   rW   rX   r~  r   rP  _launch_artifact_mappingr5   LAUNCH_JOB_ARTIFACT_SLOT_NAMEra  r;   	_on_start)ru   
latest_runr  r   r  r;   rl   
hf_versionmodule_nameactive_start_methoddeprecated_featuremsgr  r  r  r  run_init_handleresulterror_messagerun_start_handlerun_start_resultr   r   job_artifactr,   r,   r-   init  s  






























D









	







z_WandbInit.initr9  )NNNNN)r   r%   rk   r   r   r   r   r   r   r   r   r   r*   r+   )r   rr   r   rr   r*   r+   rh   )r   r8   r   r/   r*   r+   )F)
r  r8   r  r8   rB   r8   r  r<   r*   r+   )r  r   ri   r   r*   r+   )rF   r%   r*   r+   )r*   r"   )r  r    r*   r+   )r   r   r   __annotations__rv   r   r   r   r   r  r  r$  r'  r3  r   r   r  r  r  r,   r,   r,   r-   rf   s   s0   
 

% 
5
	)





&
irf   r  	attach_idr   rl   
Run | Nonec             
   C  s  | p|} | du |du A st d| p|r|jnd} | du r!t dt  t }|s-J t|  tdu r;t d|j	}|sHt d|  dz|j
| d}W n tyd } zt d|  |d}~ww t|j}|| |jj|jjd t }t|||d	}	|	  td
 |du rt|d}n|j|d || ||	 |	| |	jsJ |  |	j| }
|
jdd}|s|
  t d|j j!}|j"r|j"j#rt d|j"j# |$|j% |&  |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`zlogger is not initializedzUnable to attach to run z (no service process))r
  )r   r   r   r  z$attach backend started and connectedr   r  r  zTimeout attaching to runzFailed to attach to run: )'r   r  r4   _assert_is_user_processr   _setupr.   r   r'   r  inform_attach	Exceptionr   	_settingsr   r   rv  r   r   r   r  r   r"   _initr  r  r  r!  r  deliver_attachr  r  responseattach_responser  messager  rl   
_on_attach)r
  r   rl   rn   r  attach_settingserF   r  r;   attach_handleattach_resultr  r,   r,   r-   _attach  sj   	




r  r   r   dirStrPath | Noner  rB   notestagsSequence[str] | Nonerk   dict[str, Any] | str | Noner   r   r   r   r   groupjob_typer   /Literal['online', 'offline', 'disabled'] | Noner   r   (Literal['never', 'allow', 'must'] | Noner  r  7bool | Literal['allow', 'never', 'must', 'auto'] | Noneresume_from	fork_fromr   r   r   r    Settings | dict[str, Any] | Noner"   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\||_|d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||_zt }|j||||	|
|d | W S  ty } ztdurtjd|d  d}~w ty } ztdurtjd|d t j !| t" d}~ww )uc2  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.

    Call `wandb.init()` to start a run before logging data with `wandb.log()`.
    When you're done logging data, call `wandb.finish()` to end the run. If you
    don't call `wandb.finish()`, the run will end when your script exits.

    For more on using `wandb.init()`, including detailed examples, check out our
    [guide and FAQs](https://docs.wandb.ai/guides/track/launch).

    Examples:
        ### Explicitly set the entity and project and choose a name for the run:

        ```python
        import wandb

        run = wandb.init(
            entity="geoff",
            project="capsules",
            name="experiment-2021-10-31",
        )

        # ... your training code here ...

        run.finish()
        ```

        ### Add metadata about the run using the `config` argument:

        ```python
        import wandb

        config = {"lr": 0.01, "batch_size": 32}
        with wandb.init(config=config) as run:
            run.config.update({"architecture": "resnet", "depth": 34})

            # ... your training code here ...
        ```

        Note that you can use `wandb.init()` as a context manager to automatically
        call `wandb.finish()` at the end of the block.

    Args:
        entity: The username or team name under which the runs will be logged.
            The entity must already exist, so ensure you’ve created your account
            or team in the UI before starting to log runs. If not specified, the
            run will default your defualt entity. To change the default entity,
            go to [your settings](https://wandb.ai/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: An absolute path to the directory where metadata and downloaded
            files will be stored. When calling `download()` on an artifact, files
            will be saved to this directory. If not specified, this defaults to
            the `./wandb` directory.
        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. The
            identifier must not contain any of the following special characters:
            `/ \ # ? % :`. 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.
            For more information, refer to our
            [guide to grouping runs](https://docs.wandb.com/guides/runs/grouping).
        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.
        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.
        anonymous: Specifies the level of control over anonymous data logging.
            Available options are:
            - `"never"` (default): Requires you to link your W&B account before
                tracking the run. This prevents unintentional creation of anonymous
                runs by ensuring each run is associated with an account.
            - `"allow"`: Enables a logged-in user to track runs with their account,
                but also allows someone running the script without a W&B account
                to view the charts and data in the UI.
            - `"must"`: Forces the run to be logged to an anonymous account, even
                if the user is logged in.
        reinit: Determines if multiple `wandb.init()` calls can start new runs
            within the same process. By default (`False`), if an active run
            exists, calling `wandb.init()` returns the existing run instead of
            creating a new one. When `reinit=True`, the active run is finished
            before a new run is initialized. In notebook environments, runs are
            reinitialized by default unless `reinit` is explicitly set to `False`.
        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.
            Note: If `resume` is set, `fork_from` and `resume_from` cannot be
            used. When `resume` is unset, the system will always start a new run.
            For more details, see our
            [guide to resuming runs](https://docs.wandb.com/guides/runs/resuming).
        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: 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: 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](https://wandb.ai/settings).
        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.
            saving relevant event files for viewing in the W&B UI. (Default: `False`)
        monitor_gym: Enables automatic logging of videos of the environment when
            using OpenAI Gym. For additional details, see our
            [guide for gym integration](https://docs.wandb.com/guides/integrations/openai-gym).
        settings: Specifies a dictionary or `wandb.Settings` object with advanced
            settings for the run.

    Returns:
        A `Run` object, which is a handle to the current run. Use this object
        to perform operations like logging data, saving files, and finishing
        the run. See the [Run API](https://docs.wandb.ai/ref/python/run) for
        more details.

    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 W&B server.
        UsageError: If the user provided invalid arguments to the function.
        KeyboardInterrupt: If the user interrupts the run initialization process.
            If the user interrupts the run initialization process.
    N)r   rk   r   r   r   r   interrupted)exc_infozerror in wandb.init()r,   )#r4   r  r%   r  rr   run_job_typeroot_dirr   r   r  r  r   rN  r   rM  r   r   r  r   r   r   r   r(  r'  rf   r   r  KeyboardInterruptr'   warningr  	exception_sentryreraiseAssertionError)r   r   r  r  rB   r  r  rk   r   r   r   r"  r#  r   r   r   r  r  r'  r(  r   r   r   r   rF   r   wir  r,   r,   r-   r    s    l



r  )r(   r)   r*   r+   )r*   r/   )r;   r   r*   r<   )rF   r%   r*   rG   )NN)r
  r/   r   r/   rl   r  r*   r  )NNNNNNNNNNNNNNNNNNNNNNNNN)4r   r/   r   r/   r  r  r  r/   rB   r/   r  r/   r  r   rk   r!  r   r   r   r   r   r   r"  r/   r#  r/   r   r$  r   r   r   r%  r  r   r  r&  r'  r/   r(  r/   r   r   r   r   r   r   r   r   rF   r)  r*   r"   )Krp  
__future__r   r   rQ   r  rN   r  r2   r  r   typingr   r   r   r   version_infor	   typing_extensionsr4   	wandb.envr
   wandb.errorsr   r   r   wandb.errors.linksr   wandb.errors.utilr   wandb.integrationr   wandb.sdk.libr   wandb.sdk.lib.pathsr   
wandb.utilr   rL   r   r   backend.backendr   libr   r   r   r   r   lib.deprecater   r   lib.mailboxr   r    wandb_helperr!   	wandb_runr"   r#   r$   wandb_settingsr%   wandb.protor&   pbr'   r	  r.   r:   rE   re   rf   r  r  r,   r,   r,   r-   <module>   s    





!      ,U