o
    niS                    @  s   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Zd dlZd dlZd dlZd dlmZ d dlmZ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 m!Z!m"Z"m#Z#m$Z$m%Z% d dl&Z&d dl'Z'd dl(Z'd dl)Z'd d	l'm*Z* d d
l+m,Z, d dl-m.Z.m/Z/ d dl0m1Z1 d dl2m1Z3 d dl4m5Z5m6Z6m7Z7 d dl8m9Z9 d dl:m;Z; d dl<m=Z=m>Z> d dl?m@Z@mAZAmBZBmCZC d dlDmEZE d dlFmGZG d dlHmIZImJZJ d dlKmLZLmMZMmNZN d dl)mOZOmPZPmQZQmRZRmSZSmTZTmUZU ddlVmWZWmXZXmYZY ddlZm[Z[m\Z\m]Z] ddl^m_Z_ ddl`maZambZbmcZcmdZd ddlemfZf ddlgmhZhmiZimjZjmkZkmlZlmmZmmnZnmoZompZpmqZqmrZr ddlsmtZt ddlumvZvmwZwmxZxmyZy dd lzm{Z{ dd!l|m}Z} dd"l~mZ erd d#lmZ d dlZd dl2Z'd dlZ'd dlZ'd d$l?mZmZmZ G d%d& d&eZG d'd( d(eZG d)d* d*eZG d+d, d,ed-d.Zed/Zd0Zed1ZG d2d3 d3eZG d4d5 d5e#ZG d6d7 d7ZG d8d9 d9ZeG d:d; d;ZG d<d= d=Z		-	dPdQdGdHZzejej_W n
 ey   Y nw 		dRdSdNdOZdS )T    )annotationsN)Mapping)	dataclassfield)datetime	timedeltatimezone)IntEnum)TracebackType)TYPE_CHECKINGAnyCallableLiteral
NamedTupleSequenceTextIO)trigger)_datatypes_set_callback)internalpublic)Api)	CommErrorUnsupportedError
UsageError)url_registry)wandb_torch)CustomChart	Visualize)MetricRecordPollExitResponseResult	RunRecord)Artifact)job_builder)register_post_import_hookunregister_post_import_hook)FilePathStrLogicalPathStrPath)_is_artifact_object_is_artifact_string_is_artifact_version_weave_dict!_is_py_requirements_or_dockerfile_resolve_aliasesadd_import_hookparse_artifact_string   )wandb_configwandb_metricwandb_summary)is_artifact_registry_projectvalidate_aliasesvalidate_tags)TypeRegistry)	FilesDictGlobStrInterfaceBase
PolicyName)SummaryRecord)config_util	deprecate	filenames
filesystemipythonmoduleprinterprogress
proto_utilredirect	telemetry)	ExitHooks)MailboxErrorMailboxHandleMailboxProbeMailboxProgress)
AlertLevel)Settings)_WandbSetup)	TypedDict)GetSummaryResponseInternalMessagesResponseSampledHistoryResponsec                   @  s.   e Zd ZU ded< ded< ded< ded< dS )	GitSourceDictstrremotecommit	list[str]
entrypointSequence[str]argsN__name__
__module____qualname____annotations__ ra   ra   Q/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/wandb/sdk/wandb_run.pyrT   h   s
   
 rT   c                   @  s&   e Zd ZU ded< ded< ded< dS )ArtifactSourceDictrU   artifactrX   rY   rZ   r[   Nr\   ra   ra   ra   rb   rc   n   s   
 rc   c                   @     e Zd ZU ded< ded< dS )ImageSourceDictrU   imagerZ   r[   Nr\   ra   ra   ra   rb   rf   s      
 rf   c                   @  s>   e Zd ZU ded< ded< ded< ded< ded< d	ed
< dS )JobSourceDictrU   _versionsource_typez4GitSourceDict | ArtifactSourceDict | ImageSourceDictsourcedict[str, Any]input_typesoutput_types
str | NoneruntimeNr\   ra   ra   ra   rb   ri   w   s   
 ri   F)totalwandb<   z[a-zA-Z0-9_-]+$c                   @  s   e Zd ZdZdZdS )TeardownStager0      N)r]   r^   r_   EARLYLATEra   ra   ra   rb   ru      s    ru   c                   @  re   )TeardownHookzCallable[[], None]callru   stageNr\   ra   ra   ra   rb   ry      rh   ry   c                   @  s   e Zd ZU dZded< ded< ded< ded< ded< ded	< 	
		d/d0ddZd1ddZed2ddZd3d"d#Z	d1d$d%Z
d1d&d'Zd1d(d)Zd1d*d+Zd1d,d-Zd.S )4RunStatusCheckerzPeriodically polls the background process for relevant updates.

    - check if the user has requested a stop.
    - check the network status.
    - check the run sync status.
    threading.Lock_stop_status_lockMailboxHandle | None_stop_status_handle_network_status_lock_network_status_handle_internal_messages_lock_internal_messages_handle      
   	interfacer:   stop_polling_intervalintretry_polling_interval"internal_messages_polling_intervalreturnNonec                 C  s   || _ || _|| _|| _t | _t | _d | _	tj
| jddd| _t | _d | _tj
| jddd| _t | _d | _tj
| jddd| _d S )N
ChkStopThrT)targetnamedaemon
NetStatThr	IntMsgThr)
_interface_stop_polling_interval_retry_polling_interval#_internal_messages_polling_interval	threadingEvent_join_eventLockr~   r   Threadcheck_stop_status_stop_threadr   r   check_network_status_network_status_threadr   r   check_internal_messages_internal_messages_thread)selfr   r   r   r   ra   ra   rb   __init__   s4   



zRunStatusChecker.__init__c                 C  s"   | j   | j  | j  d S N)r   startr   r   r   ra   ra   rb   r      s   

zRunStatusChecker.startlockhandlec                 C  sF   |  |r|   W d    d S W d    d S 1 sw   Y  d S r   )abandon)r   r   ra   ra   rb   _abandon_status_check   s   
"z&RunStatusChecker._abandon_status_check
set_handler   timeoutrequestprocessc                C  s  d }d}|st  }|s| }|sJ | | j r$	 W d    d S || W d    n1 s2w   Y  z	|j|dd}	W n
 tyJ   Y d S w | |d  W d    n1 s\w   Y  |	rm||	 |  d }t  | }
t||
 d}| jj|d}|rd S d S )NFr   releaser   r   )time	monotonicr   is_setwaitrI   r   max)r   r   r   r   r   r   local_handlejoin_requested
time_proberesulttime_elapsed	wait_timera   ra   rb   _loop_check_status   s:   	


z#RunStatusChecker._loop_check_statusc                   Z   d
dd}z j  j fdd j jj|d	 W d S  ty,     j j Y d S w )Nr   r    r   r   c                 S  sV   | j j}|jD ]!}|jdks|jdkrt|j  qtd|j|j  qd S )N   r   z%{} encountered ({}), retrying request)	responsenetwork_status_responsenetwork_responseshttp_status_coders   termloghttp_response_textformatrstrip)r   network_statushrra   ra   rb   _process_network_status   s   
zFRunStatusChecker.check_network_status.<locals>._process_network_statusc                      t  d| S )Nr   setattrxr   ra   rb   <lambda>      z7RunStatusChecker.check_network_status.<locals>.<lambda>r   r   r   r   r   r   r    r   r   )r   r   r   r   deliver_network_statusBrokenPipeErrorr   r   )r   r   ra   r   rb   r      s   


z%RunStatusChecker.check_network_statusc                   r   )Nr   r    r   r   c                 S  s.   | j j}|jrtjj st  d S d S d S r   )	r   stop_status_responserun_should_stoprs   agentspyagent
is_runningthreadinterrupt_main)r   stop_statusra   ra   rb   _process_stop_status  s   z@RunStatusChecker.check_stop_status.<locals>._process_stop_statusc                   r   )Nr   r   r   r   ra   rb   r   (  r   z4RunStatusChecker.check_stop_status.<locals>.<lambda>r   r   )r   r~   r   r   deliver_stop_statusr   r   r   )r   r   ra   r   rb   r     s   
	

z"RunStatusChecker.check_stop_statusc                   r   )Nr   r    r   r   c                 S  s$   | j j}|jjD ]}t| qd S r   )r   internal_messages_responsemessageswarningrs   termwarn)r   internal_messagesmsgra   ra   rb   _process_internal_messages4  s   zLRunStatusChecker.check_internal_messages.<locals>._process_internal_messagesc                   r   )Nr   r   r   r   ra   rb   r   <  r   z:RunStatusChecker.check_internal_messages.<locals>.<lambda>r   r   )r   r   r   r   deliver_internal_messagesr   r   r   )r   r   ra   r   rb   r   3  s   


z(RunStatusChecker.check_internal_messagesc                 C  s>   | j   | | j| j | | j| j | | j| j d S r   )	r   setr   r~   r   r   r   r   r   r   ra   ra   rb   stopG  s   
zRunStatusChecker.stopc                 C  s*   |    | j  | j  | j  d S r   )r   r   joinr   r   r   ra   ra   rb   r   V  s   

zRunStatusChecker.joinN)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^   r_   __doc__r`   r   r   staticmethodr   r   r   r   r   r   r   ra   ra   ra   rb   r|      s*   
 
&

,


r|   c                   @  sT   e Zd ZU dZded< G dd dZedd	d
ZeddddZedddZ	dS )_run_decorator rU   _is_attachingc                   @  s   e Zd ZdS )z_run_decorator.DummyN)r]   r^   r_   ra   ra   ra   rb   Dummy`  r   r   funcr   r   c                      t d	 fdd}|S )
Nr   	type[Run]r[   r   kwargsr   c              
     s   t | dd rCt | dd t krC jr"dj d j d}t|j _ztj| d W n ty? } zd _|d }~ww d _| g|R i |S )N
_attach_id_attach_pidzTrying to attach `z$` while in the middle of attaching ``runr   )	getattrosgetpidr   r]   RuntimeErrorrs   _attach	Exception)r   r[   r   messageeclsr   ra   rb   wrapperd  s&   

z'_run_decorator._attach.<locals>.wrapperr   r   r[   r   r   r   r   r   	functoolswrapsr  r   r  ra   r  rb   r  b  s   z_run_decorator._attachFr  	only_warnboolc                   s   d fdd}|S )Nr   r   r   c                   s    t  d	 fdd}|S )
Nr   r   r[   r   r   r   c                   s`   t | dds | g|R i |S d| j d j d}p|}r,tj|tdd d S t|)N_is_finishedFzRun (z) is finished. The call to `zE` will be ignored. Please make sure that you are using an active run.rv   )
stacklevel)r   idr]   warningswarnUserWarningr   )r   r[   r   default_messageresolved_message)r   r  r  ra   rb   
wrapper_fn  s   zH_run_decorator._noop_on_finish.<locals>.decorator_fn.<locals>.wrapper_fnr  r	  )r   r  r  r  )r   rb   decorator_fn  s   z4_run_decorator._noop_on_finish.<locals>.decorator_fnr   r   r   r   ra   )r  r  r  r  ra   r  rb   _noop_on_finish  s   z_run_decorator._noop_on_finishc                   r   )
Nr   r   r[   r   r   r   c              
     s   t | dd d u rNt | dd }|t krNdj dt  d| dtd }t | dd }|rC|jrCtj|d	d
 t	dj dtj
|d	d
   S | g|R i |S )Nr   	_init_pidr   z` ignored (called from pid=z, `init` called from pid=z). See: multiprocess	_settingsFrepeatz"` does not support multiprocessing)r   r   r   r]   r   urlstrictrs   	termerrorr   r   r   )r   r[   r   r  r  settingsr  ra   rb   r    s$   	
z%_run_decorator._noop.<locals>.wrapperr  r	  r  ra   r  rb   _noop  s   z_run_decorator._noopNr  )r   F)r  rU   r  r  r   r   )
r]   r^   r_   r   r`   r   classmethodr  r  r%  ra   ra   ra   rb   r   ]  s   
 r   c                   @  sD   e Zd ZU eddZded< eddZded< eddZded< dS )		RunStatusr   )defaultr   sync_items_totalsync_items_pendingNzdatetime | None	sync_time)r]   r^   r_   r   r)  r`   r*  r+  ra   ra   ra   rb   r'    s   
 r'  c                      s  e Zd ZU dZded< ded< ded< ded< d	ed
< ded< ded< ded< ded< ded< ded< ded< ded< ded< ded< ded< ded< d ed!< d"ed#< d$ed%< d&ed'< d(ed)< ded*< ded+< d,ed-< d.ed/< d.ed0< ded1< ded2< d3ed4< ded5< ded6< d7ed8< ded9< d:ed;< d<ed=< 	>	>	>dddEdFZ	>	>	>dddGdHZddJdKZddMdNZddOdPZ	ddSdTZ
d	dVdWZddXdYZddZd[Zd
 fd`daZddddeZddgdhZddjdkZeddmdnZeejddodpZeejddqdrZeejddtduZeejddwdxZeejddydzZeje dd|dzZeejdd}d~Zeje ddd~ZeejdddZeje dddZeejdddZeejdddZ dddZ!eejdddZ"eejdddZ#eejdddZ$eejdddZ%eejdddZ&eejdddZ'eejdddZ(eejdddZ)eejdddZ*eejdddZ+dddZ,eejdddZ-e ejdd>e.e/j0fdddZ1dddZ2dddZ3dddZ4eejdddZ5eejdddZ6	>	>	>ddddZ7	>	>	>ddddZ8dddZ9dddĄZ:dddǄZ;ejd d!dd̈́Z<ejd d"ddτZ=	>d#d$ddՄZ>e 	>	>	>dd%dd܄Z?d&ddZ@d'ddZAe d(ddZBd)ddZCd*ddZDd+ddZEd,ddZFd-ddZG	>	>d#d.ddZHd/ddZIejddd/dd ZJ	d0d1ddZKd2d	d
ZLd3ddZMd4ddZNd5ddZOd6ddZPdddZQd7ddZR	>	>d#d.d d!ZSejTe ej	>	>	>dd8d#d$ZUe ej	>	>	%d9d:d,d-ZVd;d0d1ZWej	>		>d<d=d5d6ZXejTej	>	>d#d>d9d:ZY	>d?d@d;d<ZZejTejd?d@d=d>Z[e ejdAd@dAZ\dBdFdGZ]ddHdIZ^	>d?dCdMdNZ_ddOdPZ`d?d@dQdRZaddSdTZbddUdVZcddWdXZdddYdZZedd[d\Zfdd]d^Zgdd_d`ZhddadbZidDdddeZj	>d?dEdkdlZk	>	>d#dFdrdsZl	>d?dGdtduZmdHdxdyZndId}d~ZodddZpeqdJddZre ej	>	>	>	>	>	>dKdLddZs	>	>	>	>	>	>dKdLddZtej	>			>	ɐdMdNddZuej	>d?dOddZvdPddZwdddZxe ej	>d?dQddZye ej	>	>	>ddRddZze ej	>	>	>	>dSdTddZ{e ej	>	>	>	>dSdUddZ|e ej	>	>	>	>dSdUddZ}	>	>	>	>	>			ɐdVdWddZ~d?dXddZddÐdĄZ	>	>	>ddYdƐdǄZe ej	>	>d#dZdʐd˄Ze ejd[d͐d΄Ze ej	>	>d#d\dАdфZe ej	>	>d#d]dؐdلZd^dڐdۄZd_ddZe ejdddZee ejd`ddZeqdaddZeqdaddZeqdaddZeqdaddZeq	>	>	>	>dSdbddZeq	>d?dcddZeqdaddZeq	>	>d#ddddZeq	>d?dedd ZeqdaddZ  ZS (f  Runa  A unit of computation logged by wandb. Typically, this is an ML experiment.

    Create a run with `wandb.init()`:
    <!--yeadoc-test:run-object-basic-->
    ```python
    import wandb

    run = wandb.init()
    ```

    There is only ever at most one active `wandb.Run` in any process,
    and it is accessible as `wandb.run`:
    <!--yeadoc-test:global-run-object-->
    ```python
    import wandb

    assert wandb.run is None

    wandb.init()

    assert wandb.run is not None
    ```
    anything you log with `wandb.log` will be sent to that run.

    If you want to start more runs in the same script or notebook, you'll need to
    finish the run that is in-flight. Runs can be finished with `wandb.finish` or
    by using them in a `with` block:
    <!--yeadoc-test:run-context-manager-->
    ```python
    import wandb

    wandb.init()
    wandb.finish()

    assert wandb.run is None

    with wandb.init() as run:
        pass  # log data here

    assert wandb.run is None
    ```

    See the documentation for `wandb.init` for more on creating runs, or check out
    [our guide to `wandb.init`](https://docs.wandb.ai/guides/track/launch).

    In distributed training, you can either create a single run in the rank 0 process
    and then log information only from that process, or you can create a run in each process,
    logging from each separately, and group the results together with the `group` argument
    to `wandb.init`. For more details on distributed training with W&B, check out
    [our guide](https://docs.wandb.ai/guides/track/log/distributed-training).

    Currently, there is a parallel `Run` object in the `wandb.Api`. Eventually these
    two objects will be merged.

    Attributes:
        summary: (Summary) Single values set for each `wandb.log()` key. By
            default, summary is set to the last value logged. You can manually
            set summary to the best value, like max accuracy, instead of the
            final value.
    telemetry.TelemetryRecord_telemetry_objr  _telemetry_obj_active_telemetry_obj_dirtybytes_telemetry_obj_flushedlist[TeardownHook]_teardown_hooksz(wandb.sdk.backend.backend.Backend | None_backendz9wandb.sdk.interface.interface_queue.InterfaceQueue | None_internal_run_interfacez_WandbSetup | None_wlzredirect.RedirectBase | None
_out_redir
_err_redirz!Callable[[str, str], None] | None_redirect_cb_redirect_raw_cbzfilesystem.CRDedupedFile | None_output_writer_atexit_cleanup_calledzExitHooks | None_hooks
int | None
_exit_codezRunStatusChecker | None_run_status_checkerSampledHistoryResponse | None_sampled_historyGetSummaryResponse | None_final_summaryr   _poll_exit_handlePollExitResponse | None_poll_exit_responseInternalMessagesResponse | None_internal_messages_response_stdout_slave_fd_stderr_slave_fdrX   _artifact_slotsr   r  r   
_iface_pid_iface_portrp   r   _is_attachedr  rN   r  _forkeddict[str, Any] | None_launch_artifactsprinter.Printer_printerNr$  configsweep_configlaunch_configr   r   c                 C  s0   t  | _|jr|| _d S | j||||d d S )N)r$  rV  rW  rX  )r   r   r  r%  r  _init)r   r$  rV  rW  rX  ra   ra   rb   r   2  s   

zRun.__init__c           	      C  s  || _ t | _| j| j | j| j | j| j  t	
| j| _| j| j d| _d| _t | _t| j t | _d | _d | _d | _d | _d | _g | _d | _d | _d | _ d | _!d | _"d | _#d | _$i | _%d | _&d | _'d | _(d | _)d | _*d | _+t,- | _.d| _/d| _0d| _1d| _2t3j4j5t6| j dd |pt6 }d}|7|t6  i | _8i | _9| j j:r| j j;rt<t=j>?d| j j;|| d< | j j@d ur| j j@jA| j j@jBd	|| d
< | j jCd ur| j jCjA| j jCjBd	|| d
< | jjD|dd |r| jjE|ddd |r| jjE|ddd t3jFG }|r|| j| d< t3jFH }|r+|| j| d< t3jFI }|r:|| j| d< d | _Jd | _Kd | _Ld| _Md| _Nt=O | _Pd| _Q| j jRs]| j jS| _Ld S d S )Nr   F    user)tagsprocess_context_wandbcode	code_path)run_idstepbranch_pointT)ignore_lockedsweep)r[  _allow_val_changelaunchlaunch_queue_namelaunch_queue_entitylaunch_trace_id)Tr  r1   Config_config_set_callback_config_callback_set_artifact_callback_config_artifact_callback_set_settingsr3   Summary%_summary_get_current_summary_callbacksummary_set_update_callback_summary_update_callback_step_starting_stepr   _start_timer   _datatypes_callbackrC   new_printerrU  _torch_historyr5  r6  r7  r>  r4  r<  r8  r9  rK  rL  r@  _exit_result_used_artifact_slotsrA  rC  rE  rH  rJ  rF  rG   TelemetryRecordr.  r/  r2  r0  r=  rs   _sentryconfigure_scopedict
setdefault_launch_artifact_mapping&_unique_launch_artifact_sequence_names	save_codeprogram_relpathr'   r   pathr   	fork_fromr   valueresume_from_updatemerge_lockedenvget_launch_queue_nameget_launch_queue_entityget_launch_trace_idrN  rO  r   rP  r  r   r   rQ  x_disable_servicera  )	r   r$  rV  rW  rX  	wandb_keyrh  ri  rj  ra   ra   rb   rY  H  s   










z	Run._init	iface_pidc                 C  
   || _ d S r   )rN  )r   r  ra   ra   rb   _set_iface_pid     
zRun._set_iface_pid
iface_portc                 C  r  r   )rO  )r   r  ra   ra   rb   _set_iface_port  r  zRun._set_iface_portc              	   C  s  | j jr1tjdd ur1zttjdd}W n ttfy)   t	
d Y d S w | | d S | j jr| j jrtj| j jr| | j j t| j j}t| }W d    n1 s`w   Y  |di dd ur|dd}| | d S d S d S d S d S )NWANDB_ARTIFACTSz{}z3Malformed WANDB_ARTIFACTS, using original artifacts	overrides	artifacts)r  rg  r   environgetjsonloads
ValueErrorSyntaxErrorrs   r    _initialize_launch_artifact_mapslaunch_config_pathr  existssaveopenread)r   r  fprX  ra   ra   rb   !_handle_launch_artifact_overrides  s0   z%Run._handle_launch_artifact_overridesr  rm   c                 C  sl   |  D ]/\}}|| j|< |d}t|dkr3|d dd }| j|r.| j| q|| j|< qd S )N:rv   r   /)itemsr  splitlenr  r  pop)r   r  keyitemartifact_sequence_tuple_or_slotsequence_namera   ra   rb   r    s   


z$Run._initialize_launch_artifact_maps	telem_objc                 C  s,   t | dsd S | j| d| _|   d S )Nr.  T)hasattrr.  	MergeFromr0  _telemetry_flush)r   r  ra   ra   rb   _telemetry_callback  s
   
zRun._telemetry_callbackc                 C  sp   t | dsd S | jsd S | jsd S | jr4| jjr6| j }|| jkr$d S | jj| j || _d| _d S d S d S )Nr.  F)	r  r/  r0  r5  r   r.  SerializeToStringr2  _publish_telemetry)r   
serializedra   ra   rb   r    s   



zRun._telemetry_flushc                 C  s
   d| _ d S )NT)_frozenr   ra   ra   rb   _freeze  r  zRun._freezeattrrU   r  objectc                   s8   t | dd rt| |std| dt || d S )Nr  z
Attribute z  is not supported on Run object.)r   r  r  super__setattr__)r   r  r  	__class__ra   rb   r    s   zRun.__setattr__memodict[int, Any]c                 C     | S r   ra   )r   r  ra   ra   rb   __deepcopy__     zRun.__deepcopy__r   c                 C  s2   | j r| j jr	dS | j}|sdS t|| j| jdS )z$Return run state as a custom pickle.N)r   r  r  )r  r  r   r  r  r  )r   r   ra   ra   rb   __getstate__  s   zRun.__getstate__statec                 C  sB   |sdS | d}|sdS |d t krtd| j| dS )z#Set run state from a custom pickle.Nr   r  z5attach in the same process is not supported currently)r  r   r   r   __dict__update)r   r  r   ra   ra   rb   __setstate__+  s   
zRun.__setstate__wandb_torch.TorchHistoryc                 C  s   | j d u r
t | _ | j S r   )r|  r   TorchHistoryr   ra   ra   rb   _torch9  s   

z
Run._torchc                 C  s   | j jddS )z'A frozen copy of run's Settings object.T)deep)r  
model_copyr   ra   ra   rb   r$  ?  s   zRun.settingsc                 C     | j jS )z<The directory where files associated with the run are saved.)r  	files_dirr   ra   ra   rb   dirE     zRun.dirwandb_config.Configc                 C     | j S )z'Config object associated with this run.)rl  r   ra   ra   rb   rV  K     z
Run.configwandb_config.ConfigStaticc                 C  s   t | jS r   )r1   ConfigStaticrl  r   ra   ra   rb   config_staticQ     zRun.config_staticc                 C  s   | j jr| j jS dS )zDisplay name of the run.

        Display names are not guaranteed to be unique and may be descriptive.
        By default, they are randomly generated.
        N)r  run_namer   ra   ra   rb   r   V  s   zRun.namer   c                 C  sd   t j| d}d|j_W d    n1 sw   Y  || j_| jr.| jjr0| jj|  d S d S d S Nr   T)	rG   contextfeatureset_run_namer  r  r5  r   publish_run)r   r   telra   ra   rb   r   b  s   
c                 C  r  )zNotes associated with the run, if there are any.

        Notes can be a multiline string and can also use markdown and latex equations
        inside `$$`, like `$x + 3$`.
        )r  	run_notesr   ra   ra   rb   notesk     z	Run.notesr  c                 C  s0   || j _| jr| jjr| jj|  d S d S d S r   )r  r  r5  r   r  )r   r  ra   ra   rb   r  u  s   tuple | Nonec                 C     | j jpdS )z/Tags associated with the run, if there are any.ra   )r  run_tagsr   ra   ra   rb   r\  |  s   zRun.tagsr\  r   c                 C  sh   t j| d}d|j_W d    n1 sw   Y  t|| j_| jr0| jjr2| jj	|  d S d S d S r  )
rG   r  r  set_run_tagstupler  r  r5  r   r  )r   r\  r  ra   ra   rb   r\    s   
c                 C  s   t r
| jjdus
J | jjS )zIdentifier for this run.N)r   r  ra  r   ra   ra   rb   r    s   zRun.idc                 C  r  )z9ID of the sweep associated with the run, if there is one.)r  sweep_idr   ra   ra   rb   r    r  zRun.sweep_idc                 C  s&   d dd | jj| jj| jjfD S )Nr  c                 s  s    | ]	}|d ur|V  qd S r   ra   ).0r  ra   ra   rb   	<genexpr>  s    z Run._get_path.<locals>.<genexpr>)r   r  entityprojectra  r   ra   ra   rb   	_get_path  s   
zRun._get_pathc                 C     |   S )zPath to the run.

        Run paths include entity, project, and run ID, in the format
        `entity/project/run_id`.
        )r  r   ra   ra   rb   r    r  zRun.pathfloatc                 C  r  )z4Unix timestamp (in seconds) of when the run started.)ry  r   ra   ra   rb   
start_time  r  zRun.start_timec                 C  r  )zThe first step of the run.)rx  r   ra   ra   rb   starting_step  r  zRun.starting_stepc                 C  r  )z-True if the run was resumed, False otherwise.)r  resumedr   ra   ra   rb   r    r  zRun.resumedc                 C  r  )zXCurrent value of the step.

        This counter is incremented by `wandb.log`.
        )rw  r   ra   ra   rb   rb    s   zRun.stepc                 C  s,   t | drtjtjjdd | jjrdS dS )zAFor compatibility with `0.9.x` and earlier, deprecate eventually.r.  zUThe mode property of wandb.run is deprecated and will be removed in a future release.
field_namewarning_messagedryrunr   )r  r>   
Deprecated	run__moder  _offliner   ra   ra   rb   mode  s   
zRun.modec                 C  r  r   r  r   r   ra   ra   rb   offline     zRun.offlinec                 C  r  r   )r  r%  r   ra   ra   rb   disabled  r  zRun.disabledc                 C  r  )ap  Name of the group associated with the run.

        Setting a group helps the W&B UI organize runs in a sensible way.

        If you are doing a distributed training you should give all of the
            runs in the training the same group.
        If you are doing cross-validation you should give all the cross-validation
            folds the same group.
        r   )r  	run_groupr   ra   ra   rb   group  s   z	Run.groupc                 C  r  Nr   )r  run_job_typer   ra   ra   rb   job_type  r  zRun.job_typec                 C  r  r  )r  r  r   ra   ra   rb   project_name  s   zRun.project_namec                 C  r  )z0Name of the W&B project associated with the run.)r  r   ra   ra   rb   r    r  zRun.project.root
include_fn2Callable[[str, str], bool] | Callable[[str], bool]
exclude_fnArtifact | Nonec                 C  sT  |du rE| j jr1d}| j jr| j j}n| j jr'| j jdr#| j j}n| j j}| jj d| }n| jj d| jj }t	j
d| }t	|d}d}|durqtj|}t|||D ]}	d}tj|	|}
|j|	|
d q^t| jjD ]#\}}}|D ]}tj||}	tj|	| jj}
d}|j|	|
d qqx|st	d	 dS | |S )
ar  Save the current state of your code to a W&B Artifact.

        By default, it walks the current directory and logs all files that end with `.py`.

        Args:
            root: The relative (to `os.getcwd()`) or absolute path to recursively find code from.
            name: (str, optional) The name of our code artifact. By default, we'll name
                the artifact `source-$PROJECT_ID-$ENTRYPOINT_RELPATH`. There may be scenarios where you want
                many runs to share the same artifact. Specifying name allows you to achieve that.
            include_fn: A callable that accepts a file path and (optionally) root path and
                returns True when it should be included and False otherwise. This
                defaults to: `lambda path, root: path.endswith(".py")`
            exclude_fn: A callable that accepts a file path and (optionally) root path and
                returns `True` when it should be excluded and `False` otherwise. This
                defaults to a function that excludes all files within `<root>/.wandb/`
                and `<root>/wandb/` directories.

        Examples:
            Basic usage
            ```python
            run.log_code()
            ```

            Advanced usage
            ```python
            run.log_code(
                "../",
                include_fn=lambda path: path.endswith(".py") or path.endswith(".ipynb"),
                exclude_fn=lambda path, root: os.path.relpath(path, root).startswith(
                    "cache/"
                ),
            )
            ```

        Returns:
            An `Artifact` object if code was logged
        NzfileId=-zsource-r_  FTr   z_No relevant files were detected in the specified directory. No code will be logged to your run.)r$  _jupyternotebook_namex_jupyter_path
startswithx_jupyter_namer  r  r  rs   utilmake_artifact_name_safer"   r   r  abspathr?   filtered_dirrelpathadd_filewalk_tmp_code_dirr   r   _log_artifact)r   r  r   r  r  r  name_stringartfiles_added	file_path	save_namedirpath_filesfnamera   ra   rb   log_code  sD   0


zRun.log_codec                 C     | j jrtd dS | j jS )zReturn the url for the W&B project associated with the run, if there is one.

        Offline runs will not have a project url.
         URL not available in offline runN)r  r   rs   r   project_urlr   ra   ra   rb   get_project_urlU     
zRun.get_project_urlc                 C  r,  )zFReturn the url for the sweep associated with the run, if there is one.r-  N)r  r   rs   r   	sweep_urlr   ra   ra   rb   get_sweep_url_  s   
zRun.get_sweep_urlc                 C  r,  )zdReturn the url for the W&B run, if there is one.

        Offline runs will not have a url.
        r-  N)r  r   rs   r   run_urlr   ra   ra   rb   get_urlf  r0  zRun.get_urlc                 C  r  )z$The W&B url associated with the run.)r4  r   ra   ra   rb   r!  p  r  zRun.urlc                 C  r  )zThe name of the W&B entity associated with the run.

        Entity can be a username or the name of a team or organization.
        r   )r  r  r   ra   ra   rb   r  v  s   z
Run.entityr_  repocode_versionc                 C  s   t j| d:}|rt|r||j_|rt|r||j_|r0t|r8||j_W d    d S W d    d S W d    d S 1 sCw   Y  d S )Nr   )rG   r  RE_LABELmatchlabelcode_stringrepo_stringr6  )r   r_  r5  r6  r  ra   ra   rb   _label_internal  s   
"zRun._label_internalr   c                 K  s   | j jrd S d|fd|fd|ffD ]\}}|r*t|s*tjd| d| ddd q|D ]}tjd	|d
dd q-| j|||d |   d S )Nr_  r5  r6  zLabel added for 'z' with invalid identifier 'z' (ignored).Fr  z Label added for unsupported key z (ignored).)r_  r5  r6  )r  label_disabler7  r8  rs   r   r<  r  )r   r_  r5  r6  r   kvra   ra   rb   _label  s    
z
Run._labellinesc                 C  s   |sd S t |}|sd S i }|dp|d}|r||d< |dp(|d}|r/||d< |dp8|d}|r?||d< | jdi | d S )	Nr_  cr5  rversionr?  r6  ra   )rG   _parse_label_linesr  r<  )r   rA  parsed
label_dictr_  r5  code_verra   ra   rb   _label_probe_lines  s    
zRun._label_probe_linesc                 C  s>   t jd}|s
d S t|dd }|sd S | }| | d S )N__main__r   )sysmodulesr  r   
splitlinesrI  )r   mdocdoclinesra   ra   rb   _label_probe_main  s   zRun._label_probe_mainnotebookc              
   C  s   t d d }z| }|dg d }|d}t|tr"| }W n ty> } zt d|  W Y d }~d S d }~ww |rH| | d S d S )Nzprobe notebookcellsr   rl   zUnable to probe notebook: )	loggerinfoprobe_ipynbr  
isinstancerU   r  r  rI  )r   rR  rA  datacell0r  ra   ra   rb   _label_probe_notebook  s"   


zRun._label_probe_notebook  Fheighthiddenc                 C  sb   | j jrdS t sdS zddlm} ||| || W dS  ty0   t	
d Y dS w )zDisplay this run in jupyter.Fr   )displayTz-.display() only works in jupyter environments)r  silentrA   
in_jupyterIPythonr^  HTMLto_htmlImportErrorrs   r   )r   r\  r]  r^  ra   ra   rb   r^    s   
zRun.displayc                 C  sF   | j jd }d| d}d}|r|d7 }t }|d|d|d S )	z>Generate HTML containing an iframe displaying the current run.z?jupyter=truezborder:none;width:100%;height:zpx;r   zdisplay:none;z<iframe src=z style=z
></iframe>)r  r3  rA   toggle_button)r   r\  r]  r!  styleprefixra   ra   rb   rc    s   zRun.to_htmlinclude
Any | Noneexcludedict[str, str]c                 C  s   d| j ddiS )Nz	text/htmlT)r]  )rc  )r   rh  rj  ra   ra   rb   _repr_mimebundle_  s   zRun._repr_mimebundle_r  tuple[str, ...] | str | NonevalrX  dict[str, object] | Nonec                 C  sJ   t d| d| d|  | jr!| jjr#| jjj|||d d S d S d S )Nz
config_cb  )r  rn  rX  )rT  rU  r5  r   publish_config)r   r  rn  rX  ra   ra   rb   rn    s   zRun._config_callbackstr | Artifact | dictr"   c           	      C  s   t |rt|tsJ |  }t|d |j}| j||dS t|r\t|t	s*J t
|\}}}i }|d urAd|i}t|}n|  }|rOt||j}n|j|d}| j||dS t|rg| j||dS tdt| )Nr  use_asbase_urlr  z.Cannot call _config_artifact_callback on type )r+   rW  r  _public_apir"   _from_idclientuse_artifactr*   rU   r/   r   r   _client	_artifactr)   r  type)	r   r  rn  
public_apird   artifact_stringru  is_idr  ra   ra   rb   rp    s,   zRun._config_artifact_callbackc                 C  s   | j d|f|d d S )Nr^  r  rn  rn  )r   r  rn  ra   ra   rb   _set_config_wandb'  s   zRun._set_config_wandbsummary_recordr<   c                 C  s\   t j| d}d|j_W d    n1 sw   Y  | jr*| jjr,| jj| d S d S d S r  )rG   r  r  set_summaryr5  r   publish_summary)r   r  r  ra   ra   rb   rv  *  s   
zRun._summary_update_callbackr   rL   c                 C     d S r   ra   )r   r   ra   ra   rb   _on_progress_get_summary1  r  zRun._on_progress_get_summaryc                 C  sb   | j r
td i S | jr| jjsi S | jj }|j| jj| j	d}|s'i S |j
j}t|jS )Nz*Summary data not available in finished runr   on_progress)r  rs   r   r5  r   deliver_get_summaryr   r  summary_timeoutr  r   get_summary_responserE   dict_from_proto_listr  )r   r   r   r  ra   ra   rb   rs  7  s   
z)Run._summary_get_current_summary_callbackmetric_recordr   c                 C  s(   | j r| j jr| j j| d S d S d S r   )r5  r   _publish_metric)r   r  ra   ra   rb   _metric_callbackH  s   zRun._metric_callbackr*  c                 C  s>   | j r| j js	d S ttt|dfgd}| j j| d S )Nnow)r)  )r5  r   r  r9   globescapepublish_files)r   r*  r)  ra   ra   rb   rz  L  s   zRun._datatypes_callbackc                 C  s   |s|S t  }| D ]9\}}t|tr*|j||< || | j|jj|jj	d qt|t
rD|| || | j|jj	|jjd q|D ]}||}t|t
rZ|j||jj< qG|S )Nrn  r  r  )r   r  rW  r   tableset_keyrn  specconfig_value
config_keyr   addr  	table_key)r   rX  
chart_keysr>  r?  ra   ra   rb   _serialize_custom_chartsR  s2   







zRun._serialize_custom_chartsrb  rW   bool | Nonec                 C  sT   | j r| j js	d S | }| |}ttjd dk}| j jj|| j|||d d S )Ntensorboardr   )	user_steprb  flushpublish_step)	r5  r   copyr  r  rs   patchedpublish_partial_historyrw  )r   rX  rb  rW   not_using_tensorboardra   ra   rb   _partial_history_callbackn  s   

zRun._partial_history_callbackc                 C  s*   | j r| j jr| j j|| d S d S d S r   )r5  r   publish_output)r   r   rX  ra   ra   rb   _console_callback  s   zRun._console_callbackT)r  c                 C  sF   t | dd}|t krd S | jr| jjr!| jj|| d S d S d S )Nr   r   )r   r   r   r5  r   publish_output_raw)r   r   rX  console_pidra   ra   rb   _console_raw_callback  s   zRun._console_raw_callbackr   logdirr  root_logdirc                 C  s:   t d|| | jr| jjr| jj||| d S d S d S )Nztensorboard callback: %s, %s)rT  rU  r5  r   publish_tbdata)r   r  r  r  ra   ra   rb   _tensorboard_callback  s   zRun._tensorboard_callbacklibraryrO   c                 C  r  r   )r7  )r   r  ra   ra   rb   _set_library  r  zRun._set_librarybackend!wandb.sdk.backend.backend.Backendc                 C  r  r   )r5  )r   r  ra   ra   rb   _set_backend  r  zRun._set_backendr   2wandb.sdk.interface.interface_queue.InterfaceQueuec                 C  r  r   )r6  )r   r   ra   ra   rb   _set_internal_run_interface  s   
zRun._set_internal_run_interfacehooksc                 C  r  r   )r4  )r   r  ra   ra   rb   _set_teardown_hooks  r  zRun._set_teardown_hooksrun_objr!   c                 C  s  |j r|j | _|j | _|jr|j d | _|jr0t|jj	}d|v r'|d= | j
j|ddd |jrMi }|jj	D ]}t|j||j< q9|rM| j	| |jrU|j| j_|jr]|j| j_|jre|j| j_|jrm|j| j_|jru|j| j_|jr}|j| j_|jr|j| j_|jr|j| j_|jr|j| j_|jr|j| j_|j r|j | j_ |j!r|j!j"r|j!j"| j_#|j!j$r|j!j$| j_%|j&r|j&| _'t(j)j*dt+| jd d S )Ng    .Ar^  T)allow_val_changerd  r[  )r]  r\  ),r  rx  rw  r  ToMicrosecondsry  rV  r=   dict_no_value_from_proto_listr  rl  r  rt  r  r  
value_jsonr  ra  r  r  r  r  r
  r	  display_namer  r  r  r\  r  r  hostr  git
remote_urlgit_remote_urlrW   
git_commitforkedrQ  rs   r  r  r  )r   r  c_dictsummary_dictorigra   ra   rb   _set_run_obj  sb   











zRun._set_run_objc                 C  sh   ddl m} z|| jj| jj| jj| jjdd}|j| j_|j| j_W d S  t	y3   t
d Y d S w )Nr0   )GitRepoF)r  rV   r  rW   lazyz:Cannot find valid git repo associated with this directory.)
lib.gitlibr  r  git_root
git_remoter  r  r  last_commitr  rs   r   )r   r  r5  ra   ra   rb   _populate_git_info  s   
zRun._populate_git_info	data_typedict[int | str, str]c                 C  s~   |||d}|| j d vri | j d |< || j d | v r'| j d | | }nd}||kr=|| j d | |< | j   dS dS )a  Store a singleton item to wandb config.

        A singleton in this context is a piece of data that is continually
        logged with the same value in each history step, but represented
        as a single item in the config.

        We do this to avoid filling up history with a lot of repeated unnecessary data

        Add singleton can be called many times in one run, and it will only be
        updated when the value changes. The last value logged will be the one
        persisted to the server.
        )r|  r  r  r^  N)rl  persist)r   r  r  r  value_extra	old_valuera   ra   rb   _add_singleton  s   zRun._add_singletonc                 C  s   t |ts	tdtdd | D rtd| ||| |d urLt | jks-| j	r4t
jddd tt
jd d	krDt
jd
dd || jkrL|| _|d u rT|d u sV|r_|  jd7  _d S d S )Nz%wandb.log must be passed a dictionaryc                 s  s    | ]	}t |t V  qd S r   )rW  rU   )r  r  ra   ra   rb   r  #  s    zRun._log.<locals>.<genexpr>z1Key values passed to `wandb.log` must be strings.zNote that setting step in multiprocessing can result in data loss. Please use `run.define_metric(...)` to define a custom metric to log your step values.Fr  r  r   zStep cannot be set when using tensorboard syncing. Please use `run.define_metric(...)` to define a custom metric to log your step values.r0   )rW  r   r  anykeysr  r   r   r  rP  rs   r   r  r  rw  )r   rX  rb  rW   ra   ra   rb   _log  s*   
	
zRun._logsyncc                 C  s   |durt j| d}d|j_W d   n1 sw   Y  |dur+tjtjjdd | jjrA|durAt	j
dtd dd	d
 | j|||d dS )a!  Upload run data.

        Use `log` to log data from runs, such as scalars, images, video,
        histograms, plots, and tables.

        See our [guides to logging](https://docs.wandb.ai/guides/track/log) for
        live examples, code snippets, best practices, and more.

        The most basic usage is `run.log({"train-loss": 0.5, "accuracy": 0.9})`.
        This will save the loss and accuracy to the run's history and update
        the summary values for these metrics.

        Visualize logged data in the workspace at [wandb.ai](https://wandb.ai),
        or locally on a [self-hosted instance](https://docs.wandb.ai/guides/hosting)
        of the W&B app, or export data to visualize and explore locally, e.g. in
        Jupyter notebooks, with [our API](https://docs.wandb.ai/guides/track/public-api-guide).

        Logged values don't have to be scalars. Logging any wandb object is supported.
        For example `run.log({"example": wandb.Image("myimage.jpg")})` will log an
        example image which will be displayed nicely in the W&B UI.
        See the [reference documentation](https://docs.wandb.com/ref/python/data-types)
        for all of the different supported types or check out our
        [guides to logging](https://docs.wandb.ai/guides/track/log) for examples,
        from 3D molecular structures and segmentation masks to PR curves and histograms.
        You can use `wandb.Table` to log structured data. See our
        [guide to logging tables](https://docs.wandb.ai/guides/tables/tables-walkthrough)
        for details.

        The W&B UI organizes metrics with a forward slash (`/`) in their name
        into sections named using the text before the final slash. For example,
        the following results in two sections named "train" and "validate":

        ```
        run.log(
            {
                "train/accuracy": 0.9,
                "train/loss": 30,
                "validate/accuracy": 0.8,
                "validate/loss": 20,
            }
        )
        ```

        Only one level of nesting is supported; `run.log({"a/b/c": 1})`
        produces a section named "a/b".

        `run.log` is not intended to be called more than a few times per second.
        For optimal performance, limit your logging to once every N iterations,
        or collect data over multiple iterations and log it in a single step.

        ### The W&B step

        With basic usage, each call to `log` creates a new "step".
        The step must always increase, and it is not possible to log
        to a previous step.

        Note that you can use any metric as the X axis in charts.
        In many cases, it is better to treat the W&B step like
        you'd treat a timestamp rather than a training step.

        ```
        # Example: log an "epoch" metric for use as an X axis.
        run.log({"epoch": 40, "train-loss": 0.5})
        ```

        See also [define_metric](https://docs.wandb.ai/ref/python/run#define_metric).

        It is possible to use multiple `log` invocations to log to
        the same step with the `step` and `commit` parameters.
        The following are all equivalent:

        ```
        # Normal usage:
        run.log({"train-loss": 0.5, "accuracy": 0.8})
        run.log({"train-loss": 0.4, "accuracy": 0.9})

        # Implicit step without auto-incrementing:
        run.log({"train-loss": 0.5}, commit=False)
        run.log({"accuracy": 0.8})
        run.log({"train-loss": 0.4}, commit=False)
        run.log({"accuracy": 0.9})

        # Explicit step:
        run.log({"train-loss": 0.5}, step=current_step)
        run.log({"accuracy": 0.8}, step=current_step)
        current_step += 1
        run.log({"train-loss": 0.4}, step=current_step)
        run.log({"accuracy": 0.9}, step=current_step)
        ```

        Args:
            data: A `dict` with `str` keys and values that are serializable
                Python objects including: `int`, `float` and `string`;
                any of the `wandb.data_types`; lists, tuples and NumPy arrays
                of serializable Python objects; other `dict`s of this
                structure.
            step: The step number to log. If `None`, then an implicit
                auto-incrementing step is used. See the notes in
                the description.
            commit: If true, finalize and upload the step. If false, then
                accumulate data for the step. See the notes in the description.
                If `step` is `None`, then the default is `commit=True`;
                otherwise, the default is `commit=False`.
            sync: This argument is deprecated and does nothing.

        Examples:
            For more and more detailed examples, see
            [our guides to logging](https://docs.wandb.com/guides/track/log).

            ### Basic usage
            <!--yeadoc-test:init-and-log-basic-->
            ```python
            import wandb

            run = wandb.init()
            run.log({"accuracy": 0.9, "epoch": 5})
            ```

            ### Incremental logging
            <!--yeadoc-test:init-and-log-incremental-->
            ```python
            import wandb

            run = wandb.init()
            run.log({"loss": 0.2}, commit=False)
            # Somewhere else when I'm ready to report this step:
            run.log({"accuracy": 0.8})
            ```

            ### Histogram
            <!--yeadoc-test:init-and-log-histogram-->
            ```python
            import numpy as np
            import wandb

            # sample gradients at random from normal distribution
            gradients = np.random.randn(100, 100)
            run = wandb.init()
            run.log({"gradients": wandb.Histogram(gradients)})
            ```

            ### Image from numpy
            <!--yeadoc-test:init-and-log-image-numpy-->
            ```python
            import numpy as np
            import wandb

            run = wandb.init()
            examples = []
            for i in range(3):
                pixels = np.random.randint(low=0, high=256, size=(100, 100, 3))
                image = wandb.Image(pixels, caption=f"random field {i}")
                examples.append(image)
            run.log({"examples": examples})
            ```

            ### Image from PIL
            <!--yeadoc-test:init-and-log-image-pillow-->
            ```python
            import numpy as np
            from PIL import Image as PILImage
            import wandb

            run = wandb.init()
            examples = []
            for i in range(3):
                pixels = np.random.randint(
                    low=0, high=256, size=(100, 100, 3), dtype=np.uint8
                )
                pil_image = PILImage.fromarray(pixels, mode="RGB")
                image = wandb.Image(pil_image, caption=f"random field {i}")
                examples.append(image)
            run.log({"examples": examples})
            ```

            ### Video from numpy
            <!--yeadoc-test:init-and-log-video-numpy-->
            ```python
            import numpy as np
            import wandb

            run = wandb.init()
            # axes are (time, channel, height, width)
            frames = np.random.randint(
                low=0, high=256, size=(10, 3, 100, 100), dtype=np.uint8
            )
            run.log({"video": wandb.Video(frames, fps=4)})
            ```

            ### Matplotlib Plot
            <!--yeadoc-test:init-and-log-matplotlib-->
            ```python
            from matplotlib import pyplot as plt
            import numpy as np
            import wandb

            run = wandb.init()
            fig, ax = plt.subplots()
            x = np.linspace(0, 10)
            y = x * x
            ax.plot(x, y)  # plot y = x^2
            run.log({"chart": fig})
            ```

            ### PR Curve
            ```python
            import wandb

            run = wandb.init()
            run.log({"pr": wandb.plot.pr_curve(y_test, y_probas, labels)})
            ```

            ### 3D Object
            ```python
            import wandb

            run = wandb.init()
            run.log(
                {
                    "generated_samples": [
                        wandb.Object3D(open("sample.obj")),
                        wandb.Object3D(open("sample.gltf")),
                        wandb.Object3D(open("sample.glb")),
                    ]
                }
            )
            ```

        Raises:
            wandb.Error: if called before `wandb.init`
            ValueError: if invalid data is passed

        Nr   TzN`sync` argument is deprecated and does not affect the behaviour of `wandb.log`r  ztIn shared mode, the use of `wandb.log` with the step argument is not supported and will be ignored. Please refer to zdefine-metricz! on how to customize your x-axis.Fr  )rX  rb  rW   )rG   r  r  set_step_logr>   r  run__log_syncr  _sharedrs   r   r   r!  r  )r   rX  rb  rW   r  r  ra   ra   rb   log@  s$    t
zRun.logliveglob_strstr | os.PathLike | None	base_pathpolicyr;   bool | list[str]c                 C  s   |du rt j t jjdd dS t|tr|d}t|tr-|dr-t	| d g S t
|}t
tj|}|durEt
|}n| sOt
d}ntjd	d
d |jj}|dvrbtdt
tj|}| |||S )a  Sync one or more files to W&B.

        Relative paths are relative to the current working directory.

        A Unix glob, such as "myfiles/*", is expanded at the time `save` is
        called regardless of the `policy`. In particular, new files are not
        picked up automatically.

        A `base_path` may be provided to control the directory structure of
        uploaded files. It should be a prefix of `glob_str`, and the directory
        structure beneath it is preserved. It's best understood through
        examples:

        ```
        wandb.save("these/are/myfiles/*")
        # => Saves files in a "these/are/myfiles/" folder in the run.

        wandb.save("these/are/myfiles/*", base_path="these")
        # => Saves files in an "are/myfiles/" folder in the run.

        wandb.save("/User/username/Documents/run123/*.txt")
        # => Saves files in a "run123/" folder in the run. See note below.

        wandb.save("/User/username/Documents/run123/*.txt", base_path="/User")
        # => Saves files in a "username/Documents/run123/" folder in the run.

        wandb.save("files/*/saveme.txt")
        # => Saves each "saveme.txt" file in an appropriate subdirectory
        #    of "files/".
        ```

        Note: when given an absolute path or glob and no `base_path`, one
        directory level is preserved as in the example above.

        Args:
            glob_str: A relative or absolute path or Unix glob.
            base_path: A path to use to infer a directory structure; see examples.
            policy: One of `live`, `now`, or `end`.
                * live: upload the file as it changes, overwriting the previous version
                * now: upload the file once now
                * end: upload file when the run ends

        Returns:
            Paths to the symlinks created for the matched files.

            For historical reasons, this may return a boolean in legacy code.
        NzmCalling wandb.run.save without any arguments is deprecated.Changes to attributes are automatically persisted.r  Tzutf-8)zgs://zs3://z0 is a cloud storage url, can't save file to W&B.r  zSaving files without folders. If you want to preserve subdirectories pass base_path to wandb.save, i.e. wandb.save("/mnt/folder/file.h5", base_path="/mnt")Fr  )r  endr  z>Only "live", "end" and "now" policies are currently supported.)r>   r  run__save_no_argsrW  r1  decoderU   r  rs   r   pathlibPurePathr   r  r  Pathis_absoluter   parentr  _save)r   r  r  r  	glob_pathresolved_glob_pathresolved_base_pathra   ra   rb   r  G  s@   7


zRun.saver  pathlib.PurePathc                   s  t |t |std||krtd||}|jd dkr%tdtt |}tjd}d|j_	W d    n1 s@w   Y  t
tjj|}t|dk}d|v }	tt || D ]?}
t|
 }tj|jt|jd   }tjj|}|| | | krqd|jjddd |jdd	 || qd|s|	rt| d
}t|dkr|d7 }td| d d fdd|D i}jr܈jjr܈jj| dd |D S )Nz%Glob may not walk above the base pathz(Glob cannot be the same as the base pathr   *z5Glob may not start with '*' relative to the base pathr   T)parentsexist_ok)
missing_okz filer0   sz
Symlinked zE into the W&B run directory, call wandb.save again to sync new files.r)  c                   s&   g | ]}t t|jj fqS ra   )r9   rU   relative_tor  r  r  fr  r   ra   rb   
<listcomp>  s    zRun._save.<locals>.<listcomp>c                 S  s   g | ]}t |qS ra   )rU   r  ra   ra   rb   r        )rU   r  r  r  partsr9   rG   r  r  r  r   r  r  r  r  r  r  absoluter  resolver  mkdirunlink
symlink_tors   r   r5  r   r  )r   r  r  r  relative_globrelative_glob_strr  globbed_fileshad_symlinked_filesis_star_globpath_strsource_pathrelative_pathtarget_pathfile_str
files_dictra   r  rb   r    sV   



	z	Run._saverun_pathreplaceNone | TextIOc                 C  s   t ||p|  ||p| jjS r   )restorer  r  r  )r   r   r  r  r  ra   ra   rb   r     s   

zRun.restore	exit_codequietc                 C  s$   |durt j t jjdd | |S )a  Finish a run and upload any remaining data.

        Marks the completion of a W&B run and ensures all data is synced to the server.
        The run's final state is determined by its exit conditions and sync status.

        Run States:
        - Running: Active run that is logging data and/or sending heartbeats.
        - Crashed: Run that stopped sending heartbeats unexpectedly.
        - Finished: Run completed successfully (`exit_code=0`) with all data synced.
        - Failed: Run completed with errors (`exit_code!=0`).

        Args:
            exit_code: Integer indicating the run's exit status. Use 0 for success,
                any other value marks the run as failed.
            quiet: Deprecated. Configure logging verbosity using `wandb.Settings(quiet=...)`.
        NzpThe `quiet` argument to `wandb.run.finish()` is deprecated, use `wandb.Settings(quiet=...)` to set this instead.r  )r>   r  run__finish_quiet_finish)r   r  r  ra   ra   rb   finish  s   
z
Run.finishc                 C  sJ  t d|    tj| d}d|j_W d    n1 sw   Y  | jr5t| jj	dkr5| jj	
  | jD ]}|jtjkrD|  q8d| _zR| j|d | jD ]}|jtjkr^|  qRg | _| joh| jj}|r| jjr|j| jjd W t  tj  d S W t  tj  d S W t  tj  d S t  tj  w )Nzfinishing run r   Tr   r  )ra  )rT  rU  r  rG   r  r  r  r7  r  _global_run_stackr  r4  r{   ru   rw   rz   r  _atexit_cleanuprx   servicer  ra  inform_finishrB   unset_globalsrs   r  end_session)r   r  r  hookr  ra   ra   rb   r  0  s>   
	

zRun._finishc                 C  s,   t | drtjtjjdd | j|d dS )z5Deprecated alias for `finish()` - use finish instead.r.  z>wandb.run.join() is deprecated, please use wandb.run.finish().r  r  N)r  r>   r  	run__joinr  )r   r  ra   ra   rb   r   `  s   
zRun.joinr'  c                 C  st   | j r| j js
t S | j j }|jdd}|sJ |jj}d}|jjr1t	
|jj|jjd  }t|j|j|dS )zMGet sync info from the internal backend, about the current run's sync status.r  r   Ng    eA)r)  r*  r+  )r5  r   r'  deliver_request_run_statusr   r   run_status_responser+  secondsr   fromtimestampnanosr)  r*  )r   handle_run_statusr   	sync_datar+  ra   ra   rb   statusm  s    z
Run.statusvisualize_key
panel_typepanel_configr  c                 C  s"   ||d}| j |dd|fd d S )N)r*  r+  r^  	visualizer  r  )r   r)  r*  r+  rV  ra   ra   rb   
_add_panel  s   zRun._add_panelc                 C  sH   t j| | j| j| j| j| j| j| j| j	| j
| j| j| j| j| jd d S )N)r   rV  r  rt  r  ry  log_artifactdefine_metricalertwatchunwatchmark_preempting	log_model	use_model
link_model)rB   
set_globalrV  r  rt  r  ry  r.  r/  r0  r1  r2  r3  r4  r5  r6  r   ra   ra   rb   _set_globals  s"   
zRun._set_globalsstdout_slave_fdstderr_slave_fdconsolec           	   
     s  |d u r j j}|dkr j jsd}nd}td| |dv r5tj j jt	j
} js5tt|d _|dkrntd tjd	 fd
d jjgd}tjd fdd jjgd}tjdkrmd fdd}td| nT|dkrtd tjd	 fdd jjgd}tjd fdd jjgd}n,|dkrtd tjd	 fddgd}tjd fddgd}n
|dkrd S tdz|  |  |  |  | _| _td W d S  ty } zt| tjd|d W Y d }~d S d }~ww ) Nwrapwrap_rawwrap_emuzredirect: %s>   rF   r>  wbrF   zRedirecting console.stdoutc                        d| S Nr@  r  rX  r   ra   rb   r     r   zRun._redirect.<locals>.<lambda>)srccbsstderrc                   rA  NrG  rC  rD  r   ra   rb   r     r   ntr   r   c                    sB    j r j    jr j  d} t|   jd d dd d S )NzTensorflow detected. Stream redirection is not supported on Windows when tensorflow is imported. Falling back to wrapping stdout/err.r<  )r;  )r8  	uninstallr9  rs   r   	_redirect)r   r   ra   rb   wrap_fallback  s   


z$Run._redirect.<locals>.wrap_fallback
tensorflowzWrapping output streams.c                   rA  rB  rC  rD  r   ra   rb   r     r   c                   rA  rH  rC  rD  r   ra   rb   r     r   c                   rA  rB  r  rD  r   ra   rb   r     r   c                   rA  rH  rN  rD  r   ra   rb   r     r   offzunhandled consolezRedirects installed.zFailed to redirect.exc_infor   )r  r;  r  rT  rU  r   r  r   r  r?   OUTPUT_FNAMEr<  r@   CRDedupedFiler  rF   Redirectwriter   r.   StreamWrapperStreamRawWrapperr  r  installr8  r9  r  printerror)	r   r9  r:  r;  output_log_path	out_redir	err_redirrL  r  ra   r   rb   rK    s   











zRun._redirectc                 C  s8   t d | jr| j  | jr| j  t d d S )Nr  zrestore done)rT  rU  r8  rJ  r9  r   ra   ra   rb   _restore	  s   


zRun._restorec              
   C  s
  | j d u rtd d S | jrd S d| _|p| jr| jjpd}|| _td|  |dkr=tj	
| jjr=t| jj z|   W n. tyU   tj sTtd   tyq } z|   tjd|d td  d }~ww tj| j| j| j| j| j| jd d S )	Nz)process exited without backend configuredTr   zgot exitcode: z-Control-C detected -- Run data was not syncedzProblem finishing runrP  sampled_historyfinal_summarypoll_exit_responser   r$  rC   )r5  rT  r   r=  r>  r  r@  rU  r   r  r  r  resume_fnameremove
_on_finishKeyboardInterruptrs   wandb_agent_is_runningr#  r  _console_stoprZ  r,  _footerrC  rE  rH  rJ  rU  )r   r  r  ra   ra   rb   r  	  sB   





zRun._atexit_cleanupc                   sT   t d t  _ jo jj}|s  j  t fdd  	 j
 j d S )Nz
atexit regc                     s      S r   )r  ra   r   ra   rb   r   M	  s    z$Run._console_start.<locals>.<lambda>)rT  rU  rH   r>  r7  r  r  atexitregisterrK  rK  rL  )r   r  ra   r   rb   _console_startE	  s   

zRun._console_startc                 C  s&   |    | jr| j  d | _d S d S r   )r^  r<  closer   ra   ra   rb   ri  Q	  s
   

zRun._console_stopc                 C  s   | j jrd S d S r   r  r   ra   ra   rb   _on_initW	  s   zRun._on_initc                 C  s   |    | j| j| jd | jjr| jjd ur| | jj | jjr<| jr<| jj	r<ddl
m} td | jj	|  | jrT| jj	rT| jjsTt| jj	d| _| j  |   |   d S )Nr$  rC   r   working_setzBSaving list of pip packages installed into the current environment)r   )r8  _headerr  rU  r  code_dirr+  x_save_requirementsr5  r   
wandb.utilrr  rT  debugpublish_python_packagesr   r|   rA  r   rm  	_on_ready)r   rr  ra   ra   rb   	_on_start[	  s$   
zRun._on_startc                 C  sN   t j| d}d|j_W d   n1 sw   Y  |   d| _|   dS )z4Event triggered when run is attached to another run.r   TN)rG   r  r  attachr8  rP  ry  )r   r  ra   ra   rb   
_on_attachy	  s   
zRun._on_attachc                 C  sH   d	dd}t  }t|| }| jjsd S |D ]
}t|| jj| qd S )
Nr   r,  rB   r   r   r   c              	   S  sz   t j| d-}zt|dd }|d urt|j|d W n ty*   Y W d    d S w W d    d S 1 s6w   Y  d S )Nr   r]   T)rG   r  r   r   imports_finishAttributeError)r   rB   r  r   ra   ra   rb   _telemetry_import_hook	  s   "zDRun._register_telemetry_import_hooks.<locals>._telemetry_import_hook)r   r,  rB   r   r   r   )rG   list_telemetry_importsr
  partialr  ra  r$   )r   r  import_telemetry_setimport_hook_fnmodule_namera   ra   rb    _register_telemetry_import_hooks	  s   
z$Run._register_telemetry_import_hooksc              
   C  s   |    d| _|   z|   W n ty* } ztjd|d W Y d}~nd}~ww |   | jj	sDt
j| jjrFt
| jj dS dS dS )z/Event triggered when run is ready for the user.Tz"Problem applying launch job inputsrP  N)r  r/  r  _detect_and_apply_job_inputsr  rT  rZ  r  r  resumer   r  r  rc  rd  )r   r  ra   ra   rb   ry  	  s   zRun._on_readyc                 C  s   ddl m} | |  dS )z<If the user has staged launch inputs, apply them to the run.r   )StagedLaunchInputsN) wandb.sdk.launch.inputs.internalr  apply)r   r  ra   ra   rb   r  	  s   z Run._detect_and_apply_job_inputs0tuple[list[str], dict[str, Any], dict[str, Any]]c                 C  sR   ddl m} tdd | D }t| j  }t| j	  }|||fS )Nr   rq  c                 s  s"    | ]}|j  d |j V  qdS )z==N)r  rD  )r  dra   ra   rb   r  	  s     z,Run._make_job_source_reqs.<locals>.<genexpr>)
rv  rr  sortedr7   type_ofrV  as_dictto_jsonrt  _as_dict)r   rr  installed_packages_listrn   ro   ra   ra   rb   _make_job_source_reqs	  s
   
zRun._make_job_source_reqssource_dictri   r  
patch_pathos.PathLike | Nonec                 C  s   t |}|rtj|r|tt|d |d}|	d
| W d    n1 s/w   Y  |d}|	t| W d    |S 1 sMw   Y  |S )Nz
diff.patchzrequirements.frozen.txt
zwandb-job.json)r#   JobArtifactr   r  r  r  r&   rU   new_filerU  r   r  dumps)r   r   r  r  r  job_artifactr  ra   ra   rb   _construct_job_artifact	  s   

zRun._construct_job_artifactrn   ro   docker_image_namer[   list[str] | Nonec           
      C  sj   |pt d}|sd S tjd| }|d ur|n| jj}dd||d||| jjd}| |||}	|	S )NWANDB_DOCKERzjob-v0rg   )rg   r[   )rj   rk   rl   rn   ro   rq   )	r   getenvrs   r  r  r  _args_pythonr  )
r   rn   ro   r  r  r[   r   s_argssource_infor  ra   ra   rb   _create_image_job	  s    zRun._create_image_jobc                 C  sD   |   \}}}| j|||||d}| |}|s td| |S )N)r[   r  zJob Artifact log unsuccessful: )r  r  r.  rs   Error)r   r  r[   packagesin_types	out_typesr  rd   ra   ra   rb   _log_job_artifact_with_image	  s   
z Run._log_job_artifact_with_imageprobe_handlerK   c                 C  sX   |  }|r|jddd}|sd S || | jr| jjsJ | jj }|| d S )Nr   Fr   )get_mailbox_handler   set_probe_resultr5  r   deliver_poll_exitset_mailbox_handle)r   r  r   r   ra   ra   rb   _on_probe_exit 
  s   
zRun._on_probe_exitprogress_printerprogress.ProgressPrinterprogress_handlec                 C  sD   |  }|rt|dkrd S |d  }|sd S ||jjg d S )Nr0   r   )get_probe_handlesr  get_probe_resultr  r   rb  )r   r  r  probe_handlesr   ra   ra   rb   _on_progress_exit
  s   zRun._on_progress_exitc           	      C  s  t d | jd ur| j  |   | jr| jjsJ | jjr)| jj	| j
}n| jj }|j| jd t| j| j}|jdt| j|d}W d    n1 sUw   Y  | jj }|jdd}|sjJ t| j|jj |jj| _| jj }|jdd}|sJ |jj| _| jj }| jj }|jdd}|sJ |jj| _ |jdd}|sJ |jj!| _"| jr| j#  | jr| j$  | jj%r| &| jj% d S d S )Non_finished)on_prober  r  r   )'r   rz   rA  r   ri  r5  r   r  x_update_finish_statedeliver_exitr@  deliver_finish_without_exit	add_prober  rD   r  rU  r   r
  r  r  r  print_sync_dedupe_statsr   rb  rH  r   r   rJ  r  deliver_request_sampled_historysampled_history_responserC  r  rE  cleanupr   ra  "_unregister_telemetry_import_hooks)	r   exit_handler  r(  poll_exit_handler   internal_messages_handlefinal_summary_handlesampled_history_handlera   ra   rb   re  
  sd   









zRun._on_finishra  c                 C  s    t  }|D ]}t||  qd S r   )rG   r  r%   )ra  r  r  ra   ra   rb   r  _
  s   z&Run._unregister_telemetry_import_hooksstep_metric str | wandb_metric.Metric | None	step_syncrt  goal	overwritewandb_metric.Metricc              	   C  sZ   |rd|v rt  t jjd|  |rd|v s|dur"t  t jjd|  | |||||||S )a  Customize metrics logged with `wandb.log()`.

        Args:
            name: The name of the metric to customize.
            step_metric: The name of another metric to serve as the X-axis
                for this metric in automatically generated charts.
            step_sync: Automatically insert the last value of step_metric into
                `run.log()` if it is not provided explicitly. Defaults to True
                 if step_metric is specified.
            hidden: Hide this metric from automatic plots.
            summary: Specify aggregate metrics added to summary.
                Supported aggregations include "min", "max", "mean", "last",
                "best", "copy" and "none". "best" is used together with the
                goal parameter. "none" prevents a summary from being generated.
                "copy" is deprecated and should not be used.
            goal: Specify how to interpret the "best" summary type.
                Supported options are "minimize" and "maximize".
            overwrite: If false, then this call is merged with previous
                `define_metric` calls for the same metric by using their
                values for any unspecified parameters. If true, then
                unspecified parameters overwrite values specified by
                previous calls.

        Returns:
            An object that represents this call but can otherwise be discarded.
        r  z@define_metric(summary='copy') is deprecated and will be removed.bestNzdefine_metric(summary='best', goal=...) is deprecated and will be removed. Use define_metric(summary='min') or define_metric(summary='max') instead.)r>   r  run__define_metric_copyrun__define_metric_best_goal_define_metric)r   r   r  r  r]  rt  r  r  ra   ra   rb   r/  e
  s*   &zRun.define_metricc              	   C  s  |st dt|tjr|j}d|tfd|tfd|tfd|tfd|tfd|tfd|tffD ]\}}	}
|	d urLt|	|
sLt|	j	}t d	| d
| q.|
drX|d d n|}d|v rft d| d }|rdd |dD }g }h d}|D ]}||vrt d| || q|tj| d}d|j_W d    n1 sw   Y  d }|d ur|d d  }ddh}||vrt d| tj| d}d|j_W d    n1 sw   Y  |rtj| d}d|j_W d    n1 sw   Y  |rtj| d}d|j_W d    n	1 sw   Y  tj| d}d|j_W d    n	1 s2w   Y  tj|||||||d}|| j |  |S )Nz0define_metric() requires non-empty name argumentr   r  r  r]  rt  r  r  zUnhandled define_metric() arg: z type: r  r  z:Unhandled define_metric() arg: name (glob suffixes only): c                 S  s   g | ]}|  qS ra   )lower)r  r  ra   ra   rb   r  
  r  z&Run._define_metric.<locals>.<listcomp>,>   r   minr  r  lastmeannonez+Unhandled define_metric() arg: summary op: r   T   r  r   z%Unhandled define_metric() arg: goal: )r   r  r  rt  r]  r  r  )rs   r  rW  r2   Metricr   rU   r  r|  r]   endswithr  appendrG   r  r  metric_summaryr  metric_goalmetric_hiddenmetric_step_syncmetricrm  r  _commit)r   r   r  r  r]  rt  r  r  arg_namearg_valexp_typearg_typestrippedsummary_opssummary_itemsvalidir  goal_cleaned
valid_goalrN  ra   ra   rb   r  
  s   








	zRun._define_metric	gradients  models+torch.nn.Module | Sequence[torch.nn.Module]	criteriontorch.F | Noner  0Literal['gradients', 'parameters', 'all'] | Nonelog_freqidx	log_graphc              	   C  s   t j| |||||| dS )a  Hooks into the given PyTorch model(s) to monitor gradients and the model's computational graph.

        This function can track parameters, gradients, or both during training. It should be
        extended to support arbitrary machine learning models in the future.

        Args:
            models (Union[torch.nn.Module, Sequence[torch.nn.Module]]):
                A single model or a sequence of models to be monitored.
            criterion (Optional[torch.F]):
                The loss function being optimized (optional).
            log (Optional[Literal["gradients", "parameters", "all"]]):
                Specifies whether to log "gradients", "parameters", or "all".
                Set to None to disable logging. (default="gradients")
            log_freq (int):
                Frequency (in batches) to log gradients and parameters. (default=1000)
            idx (Optional[int]):
                Index used when tracking multiple models with `wandb.watch`. (default=None)
            log_graph (bool):
                Whether to log the model's computational graph. (default=False)

        Raises:
            ValueError:
                If `wandb.init` has not been called or if any of the models are not instances
                of `torch.nn.Module`.
        N)rs   sdk_watch)r   r  r  r  r  r  r  ra   ra   rb   r1  
  s   #z	Run.watch2torch.nn.Module | Sequence[torch.nn.Module] | Nonec                 C  s   t jj| |d dS )zRemove pytorch model topology, gradient and parameter hooks.

        Args:
            models (torch.nn.Module | Sequence[torch.nn.Module]):
                Optional list of pytorch models that have had watch called on them
        )r  N)rs   r  _unwatch)r   r  ra   ra   rb   r2    s   
zRun.unwatchartifact_namert  c           
      C  s  |p|}| j |}|d ur7|d}|d}|d}|d u s)|d u s)|d u r-td| d| d| S |d u r|d u r|dd dd }| j|}	|	d ur~|	d}|	d}|	d}|d u sp|d u sp|d u rttd| d| d| S |S |S )	Nr   r  r  zTMisconfigured artifact in launch config. Must include name, project and entity keys.r  r  r   r  )r  r  r  r  r  )
r   r  rt  artifact_key_stringreplacement_artifact_infonew_namer  r  r   unique_artifact_replacement_infora   ra   rb   _swap_artifact_name$  s8   






zRun._swap_artifact_namec                 C  r  r   ra   r   ra   ra   rb   _detachF  r  zRun._detachrd   r  aliasesc              	   C  s   t j|\}}}|du rg }| jr| jjsdS | r%| s%| |}| jj	r+t
|  d}t|r:|}|j}| jj| ||||||}|jdurQt d |jdd}	|	du ra|  dS |	jj}
|
jrpt |
j dS dS )a  Link the given artifact to a portfolio (a promoted collection of artifacts).

        The linked artifact will be visible in the UI for the specified portfolio.

        Args:
            artifact: the (public or local) artifact which will be linked
            target_path: `str` - takes the following forms: `{portfolio}`, `{project}/{portfolio}`,
                or `{entity}/{project}/{portfolio}`
            aliases: `List[str]` - optional alias(es) that will only be applied on this linked artifact
                                   inside the portfolio.
            The alias "latest" will always be applied to the latest version of an artifact that is linked.

        Returns:
            None

        Nr   zQArtifact TTL will be disabled for source artifacts that are linked to portfolios.r  r   )rs   r  _parse_entity_project_itemr5  r   is_draft_is_draft_save_startedr!  r  r   NotImplementedErrorr   r4   _source_entitydeliver_link_artifact_ttl_duration_secondsr   r   r   link_artifact_responseerror_messager#  )r   rd   r  r  	portfolior  r  organizationr   r   r   ra   ra   rb   link_artifactI  sD   

	zRun.link_artifactartifact_or_namestr | Artifactr|  c           	      C  s  | j jrtdtj| j j| j jdd}|| j j t	|t
r| jr+| ||}n|}|  }|j||d}|durL||jkrLtd||j|j|pO||_|rx|| j v rf| j| |jkrftdd|v snd	|v rrtd
|j| j|< |j|j| j j| j j|p|d nn|}|du rg }nt	|t
r|g}t	|tr| r|durtd | j||ddd |  |p|j|_n7t	|tr| s| jr|j| j v rtd|j d |p|j|_|j|j|p|jp|jd ntd| jr| jjr| jj | |S )a  Declare an artifact as an input to a run.

        Call `download` or `file` on the returned object to get the contents locally.

        Args:
            artifact_or_name: (str or Artifact) An artifact name.
                May be prefixed with project/ or entity/project/.
                If no entity is specified in the name, the Run or API setting's entity is used.
                Valid names can be in the following forms:
                    - name:version
                    - name:alias
                You can also pass an Artifact object created by calling `wandb.Artifact`
            type: (str, optional) The type of artifact to use.
            aliases: (list, optional) Aliases to apply to this artifact
            use_as: (string, optional) Optional string indicating what purpose the artifact was used with.
                                       Will be shown in UI.

        Returns:
            An `Artifact` object.
        z)Cannot use artifact when in offline mode.)r  r  )default_settings)r|  r   Nz6Supplied type {} does not match type {} of artifact {}zECannot call use_artifact with the same use_as argument more than oncer  r  z3use_as cannot contain special characters ':' or '/')entity_namer  rt  z>Indicating use_as is not supported when using a draft artifactT)r  is_user_createduse_after_commitzKSwapping artifacts is not supported when using a non-draft artifact. Using r  rs  zYou must pass an artifact name (e.g. "pedestrian-dataset:v1"), an instance of `wandb.Artifact`, or `wandb.Api().artifact()` to `use_artifact`)!r  r   	TypeErrorr   r   r  r  set_current_run_idra  rW  rU   r  r  rv  r{  r|  r  r   r   _use_asr~  r  r  ry  r"   r  rs   r   r!  r   r5  r   publish_use_artifact)	r   r  r|  r  rt  apir   r}  rd   ra   ra   rb   ry    s   



zRun.use_artifactartifact_or_pathArtifact | StrPathc                 C  s   | j |||||dS )aE  Declare an artifact as an output of a run.

        Args:
            artifact_or_path: (str or Artifact) A path to the contents of this artifact,
                can be in the following forms:
                    - `/local/directory`
                    - `/local/directory/file.txt`
                    - `s3://bucket/path`
                You can also pass an Artifact object created by calling
                `wandb.Artifact`.
            name: (str, optional) An artifact name. Valid names can be in the following forms:
                    - name:version
                    - name:alias
                    - digest
                This will default to the basename of the path prepended with the current
                run id  if not specified.
            type: (str) The type of artifact to log, examples include `dataset`, `model`
            aliases: (list, optional) Aliases to apply to this artifact,
                defaults to `["latest"]`
            tags: (list, optional) Tags to apply to this artifact, if any.

        Returns:
            An `Artifact` object.
        )r   r|  r  r\  r!  )r   r  r   r|  r  r\  ra   ra   rb   r.    s   "zRun.log_artifactArtifact | strdistributed_idc                 C  F   | j jdu r|du rtd|du r| j jpd}| j|||||ddS )a  Declare (or append to) a non-finalized artifact as output of a run.

        Note that you must call run.finish_artifact() to finalize the artifact.
        This is useful when distributed jobs need to all contribute to the same artifact.

        Args:
            artifact_or_path: (str or Artifact) A path to the contents of this artifact,
                can be in the following forms:
                    - `/local/directory`
                    - `/local/directory/file.txt`
                    - `s3://bucket/path`
                You can also pass an Artifact object created by calling
                `wandb.Artifact`.
            name: (str, optional) An artifact name. May be prefixed with entity/project.
                Valid names can be in the following forms:
                    - name:version
                    - name:alias
                    - digest
                This will default to the basename of the path prepended with the current
                run id  if not specified.
            type: (str) The type of artifact to log, examples include `dataset`, `model`
            aliases: (list, optional) Aliases to apply to this artifact,
                defaults to `["latest"]`
            distributed_id: (string, optional) Unique string that all distributed jobs share. If None,
                defaults to the run's group name.

        Returns:
            An `Artifact` object.
        NzMCannot upsert artifact unless run is in a group or distributed_id is providedr   F)r   r|  r  r  finalizer  r  r  r!  r   r  r   r|  r  r  ra   ra   rb   upsert_artifact)  s   'zRun.upsert_artifactc                 C  r   )a,  Finishes a non-finalized artifact as output of a run.

        Subsequent "upserts" with the same distributed ID will result in a new version.

        Args:
            artifact_or_path: (str or Artifact) A path to the contents of this artifact,
                can be in the following forms:
                    - `/local/directory`
                    - `/local/directory/file.txt`
                    - `s3://bucket/path`
                You can also pass an Artifact object created by calling
                `wandb.Artifact`.
            name: (str, optional) An artifact name. May be prefixed with entity/project.
                Valid names can be in the following forms:
                    - name:version
                    - name:alias
                    - digest
                This will default to the basename of the path prepended with the current
                run id  if not specified.
            type: (str) The type of artifact to log, examples include `dataset`, `model`
            aliases: (list, optional) Aliases to apply to this artifact,
                defaults to `["latest"]`
            distributed_id: (string, optional) Unique string that all distributed jobs share. If None,
                defaults to the run's group name.

        Returns:
            An `Artifact` object.
        NzMCannot finish artifact unless run is in a group or distributed_id is providedr   T)r  r!  r"  r#  ra   ra   rb   finish_artifact_  s   &zRun.finish_artifactr!  r  r  c
              
   C  s  t  }
|
 ddkrtd |s|d u rtd|d ur$t|}|d ur,t|}| 	||||\}}||_
| | | jrt| jjrt| jjsd| jjj| |||| j|||	d}|||  j |S | jjj| ||||||	d |S | jr| jj| ||||||	d |S )N	anonymoustruezGArtifacts logged anonymously cannot be claimed and expire after 7 days.z7Must provide distributed_id if artifact is not finalize)r!  r  r  )r   r   r$  r  rs   r   r  r5   r6   _prepare_artifactr  _assert_can_log_artifactr5  r   r  r   communicate_artifactrb  _set_save_futurerv  rx  publish_artifactr6  )r   r  r   r|  r  r\  r  r!  r  r  r  rd   futurera   ra   rb   r!    sf   

	zRun._log_artifactr  dict[str, str] | None	PublicApic                 C  s>   d| j ji}| j js| j jpd|d< | j jpd|d< t|S )Nr   r   r  r  )r  ra  r   r  r  r   r   )r   r  ra   ra   rb   rv    s
   
zRun._public_apic                 C  s   | j jrd S z|  }|jd }|jd }t|||j|j}W n tj	j
y,   Y d S w |d urF|j|krFtd|j d| d|j d|r`|jr`||jkr`td|j d|j d| d|rz|jr|||jkr~td|j d	|j d| dd S d S d S )
Nr  r  z	Artifact z already exists with type 'z$'; cannot create another with type ''z is owned by entity 'z'; it can't be moved to 'z exists in project ')r  r   rv  r$  r"   _expected_typer   rx  requests
exceptionsRequestExceptionr|  r  r  _source_project)r   rd   r}  r  r  expected_typera   ra   rb   r)    sF   



zRun._assert_can_log_artifacttuple[Artifact, list[str]]c                 C  s   t |ttjfrN|pd| jj dtj| }t	||pd}tj
|r.|t| n"tj|r<|t| ndt|v rJ|t| ntd|}t |tj	sZtd|  |t|fS )Nzrun-r  unspecifiedz://zIpath must be a file, directory or externalreference like s3://bucket/pathzPYou must pass an instance of wandb.Artifact or a valid file path to log_artifact)rW  rU   r   PathLiker  ra  r  basenamers   r"   isfiler  isdiradd_diradd_referencer  r!  r-   )r   r  r   r|  r  rd   ra   ra   rb   r(     s*   zRun._prepare_artifactr  r(   c                 C  s   | j ||d|d dS )a  Logs a model artifact containing the contents inside the 'path' to a run and marks it as an output to this run.

        Args:
            path: (str) A path to the contents of this model,
                can be in the following forms:
                    - `/local/directory`
                    - `/local/directory/file.txt`
                    - `s3://bucket/path`
            name: (str, optional) A name to assign to the model artifact that the file contents will be added to.
                The string must contain only the following alphanumeric characters: dashes, underscores, and dots.
                This will default to the basename of the path prepended with the current
                run id  if not specified.
            aliases: (list, optional) Aliases to apply to the created model artifact,
                    defaults to `["latest"]`

        Examples:
            ```python
            run.log_model(
                path="/local/directory",
                name="my_model_artifact",
                aliases=["production"],
            )
            ```

            Invalid usage
            ```python
            run.log_model(
                path="/local/directory",
                name="my_entity/my_project/my_model_artifact",
                aliases=["production"],
            )
            ```

        Raises:
            ValueError: if name has invalid special characters

        Returns:
            None
        model)r  r   r|  r  Nr  )r   r  r   r  ra   ra   rb   r4  #  s   /
zRun.log_modelr&   c                 C  s^   | j |d}dt|j v sJ d| }t|}t|dkr-ttj	
||d S |S )a  Download the files logged in a model artifact 'name'.

        Args:
            name: (str) A model artifact name. 'name' must match the name of an existing logged
                model artifact.
                May be prefixed with entity/project/. Valid names
                can be in the following forms:
                    - model_artifact_name:version
                    - model_artifact_name:alias

        Examples:
            ```python
            run.use_model(
                name="my_model_artifact:latest",
            )

            run.use_model(
                name="my_project/my_model_artifact:v0",
            )

            run.use_model(
                name="my_entity/my_project/my_model_artifact:<digest>",
            )
            ```

            Invalid usage
            ```python
            run.use_model(
                name="my_entity/my_project/my_model_artifact",
            )
            ```

        Raises:
            AssertionError: if model artifact 'name' is of a type that does not contain the substring 'model'.

        Returns:
            path: (str) path to downloaded model artifact file(s).
        )r  r?  You can only use this method for 'model' artifacts. For an artifact to be a 'model' artifact, its type property must contain the substring 'model'.r0   r   )ry  rU   r|  r  downloadr   listdirr  r&   r  r   )r   r   rd   r  dir_listra   ra   rb   r5  V  s   )
zRun.use_modelregistered_model_namec           
   	   C  s   | d}t|dksJ dd}| jd | d | }|  }z!|j| dd}	dt|	j v s7J d| j|||	jd	}	W n t	t
fyT   | j||dd	}	Y nw | j|	||d
 dS )a  Log a model artifact version and link it to a registered model in the model registry.

        The linked model version will be visible in the UI for the specified registered model.

        Steps:
            - Check if 'name' model artifact has been logged. If so, use the artifact version that matches the files
            located at 'path' or log a new version. Otherwise log files under 'path' as a new model artifact, 'name'
            of type 'model'.
            - Check if registered model with name 'registered_model_name' exists in the 'model-registry' project.
            If not, create a new registered model with name 'registered_model_name'.
            - Link version of model artifact 'name' to registered model, 'registered_model_name'.
            - Attach aliases from 'aliases' list to the newly linked model artifact version.

        Args:
            path: (str) A path to the contents of this model,
                can be in the following forms:
                    - `/local/directory`
                    - `/local/directory/file.txt`
                    - `s3://bucket/path`
            registered_model_name: (str) - the name of the registered model that the model is to be linked to.
                A registered model is a collection of model versions linked to the model registry, typically representing a
                team's specific ML Task. The entity that this registered model belongs to will be derived from the run
            name: (str, optional) - the name of the model artifact that files in 'path' will be logged to. This will
                default to the basename of the path prepended with the current run id  if not specified.
            aliases: (List[str], optional) - alias(es) that will only be applied on this linked artifact
                inside the registered model.
                The alias "latest" will always be applied to the latest version of an artifact that is linked.

        Examples:
            ```python
            run.link_model(
                path="/local/directory",
                registered_model_name="my_reg_model",
                name="my_model_artifact",
                aliases=["production"],
            )
            ```

            Invalid usage
            ```python
            run.link_model(
                path="/local/directory",
                registered_model_name="my_entity/my_project/my_reg_model",
                name="my_model_artifact",
                aliases=["production"],
            )

            run.link_model(
                path="/local/directory",
                registered_model_name="my_reg_model",
                name="my_entity/my_project/my_model_artifact",
                aliases=["production"],
            )
            ```

        Raises:
            AssertionError: if registered_model_name is a path or
                if model artifact 'name' is of a type that does not contain the substring 'model'
            ValueError: if name has invalid special characters

        Returns:
            None
        r  r0   z_Please provide only the name of the registered model. Do not append the entity or project name.zmodel-registryz:latestr  r?  r@  )r  r   r|  )rd   r  r  N)r  r  r  rv  r{  rU   r|  r  r!  r  r   r  )
r   r  rD  r   r  
name_partsr  r  r}  rd   ra   ra   rb   r6    s*   
H

zRun.link_modeltitletextlevelstr | AlertLevel | Nonewait_durationint | float | timedelta | Nonec                 C  s   |pt j}t|t r|jn|}|dd t D vrtd|p"tdd}t|ts-t|tr3t|d}ntt	|dds?td	t|
 d
 }| jrZ| jjr\| jj|||| dS dS dS )a  Launch an alert with the given title and text.

        Args:
            title: (str) The title of the alert, must be less than 64 characters long.
            text: (str) The text body of the alert.
            level: (str or AlertLevel, optional) The alert level to use, either: `INFO`, `WARN`, or `ERROR`.
            wait_duration: (int, float, or timedelta, optional) The time to wait (in seconds) before sending another
                alert with this title.
        c                 S  s   h | ]}|j qS ra   )r  )r  levra   ra   rb   	<setcomp>  s    zRun.alert.<locals>.<setcomp>z/level must be one of 'INFO', 'WARN', or 'ERROR'r0   )minutes)r#  total_secondsNz:wait_duration must be an int, float, or datetime.timedeltar  )rM   INFOrW  r  r  r   r   r  callabler   rO  r5  r   publish_alert)r   rF  rG  rH  rJ  	level_strra   ra   rb   r0    s   
z	Run.alertc                 C  r  r   ra   r   ra   ra   rb   	__enter__  r  zRun.__enter__exc_typetype[BaseException]exc_valBaseExceptionexc_tbr
   c                 C  s8   |d u}|rt ||| |rdnd}| j|d | S )Nr0   r   r  )	tracebackprint_exceptionr  )r   rU  rW  rY  exception_raisedr  ra   ra   rb   __exit__  s   zRun.__exit__c                 C  s&   | j r| j jr| j j  dS dS dS )ztMark this run as preempting.

        Also tells the internal process to immediately report this to server.
        N)r5  r   publish_preemptingr   ra   ra   rb   r3    s   zRun.mark_preempting'dict[str, list[tuple[datetime, float]]]c              
   C  s   ddl m} ddd}| jr| jjsi S | jj }|jd	d
}|rJz|jj}|r.||W S W i S  tyI } zt	
d| W Y d}~i S d}~ww i S )znReturns a dictionary of system metrics.

        Returns:
            A dictionary of system metrics.
        r   )wandb_internal_pb2system_metrics_pb+wandb_internal_pb2.GetSystemMetricsResponser   r_  c                 S  sl   i }| j  D ],\}}g }|jD ]}tj|jjtjd}|j	|jj
d d}|||jf q|||< q|S )N)tzr  )microsecond)system_metricsr  recordr   r$  	timestampr#  r   utcr  r%  r  r  )ra  resr  recordsmeasurementsrf  dtra   ra   rb   
pb_to_dict1  s   


z'Run._system_metrics.<locals>.pb_to_dictr0   r   z Error getting system metrics: %sN)ra  rb  r   r_  )wandb.protor`  r5  r   deliver_get_system_metricsr   r   get_system_metrics_responser  rT  rZ  )r   r`  rm  r   r   r   r  ra   ra   rb   _system_metrics&  s&   	

zRun._system_metricsrC   c                 C  s.   t j| |d t j| |d t j| |d d S )Nrp  )r,  _header_wandb_version_info_header_sync_info_header_run_inforp  ra   ra   rb   rs  Y  s   zRun._headerc                 C  s&   | j s| jrd S |dtj  d S )Nz Tracking run with wandb version )r  r_  r^  rs   __version__rp  ra   ra   rb   rr  c  s   zRun._header_wandb_version_infoc              	   C  s   | j r |d|d dd|d d|d dg d S d	|| j g}|js9|d|d
 d | jsF| jsH|| d S d S d S )NzW&B syncing is set to z	`offline`z in this directory.  zRun z`wandb online`z or set zWANDB_MODE=onlinez to enable cloud syncing.zRun data is saved locally in z`wandb offline`z to turn off syncing.)	r   r^  r_  r)  sync_dirsupports_htmlr  r  r_  )r$  rC   rU  ra   ra   rb   rs  o  s   zRun._header_sync_infoc                 C  s  | j s| jrd S | j}| j}| j}| js| jrdnd}| j}|s"d S |jrpt	j
 sod||| d}d\}}	t	j
 s`|tdd}
||d}d	| d
|
 d}|r`d||| }	|| d| d| |	g n|r|| d||  | js||d d||  |r||d d||  ||d d||  |rt j ddkr|jddd d S d S d S )NzResuming runzSyncing runz<strong>z	</strong>)r   r   zdeveloper-guidedocszWeights & Biaseszto z ()zSweep page: rp  starz View project at broomz View sweep at rocketz View run at r&  r'  zJDo NOT share these links with anyone. They can be used to claim your runs.r  rH  )r   r_  r3  r.  r1  r  r  r  rw  rs   jupytermaybe_displaylinkr  r   r!  r^  r   emojir   r  r$  r  )r$  rC   r3  r.  r1  run_state_strr  run_lineproject_line
sweep_linedoc_htmlproject_htmlra   ra   rb   rt    s^   


zRun._header_run_infor`  ra  rb  r   c                C  sR   t j| |||d t j|||d t j||d t j||d t j|||d d S )N)historyrt  r$  rC   )rb  r$  rC   rp  )r   r$  rC   )r,  _footer_history_summary_info_footer_sync_info_footer_log_dir_info_footer_notify_wandb_core_footer_internal_messagesr_  ra   ra   rb   rj    s*   

zRun._footerc                C  s   |j rd S |jr|js|d|d|j g d S g }|jr;|jr;||	d d|
|j d||j  |jrO||	d d||j  | rr| jrrtd | j}|d	|j d
|j d|j d|j d	 || d S )Nz.You can sync this run to the cloud by running:zwandb sync r|  z
 View run z at: rz  z View project at: zlogging synced fileszSynced z W&B file(s), z media file(s), z artifact file(s) and z other file(s))r_  r   r  r^  r_  rv  r  r3  r  r  r   r  r.  file_countsrT  rU  wandb_countmedia_countartifact_countother_count)rb  r$  rC   rU  r  ra   ra   rb   r    s<   (

zRun._footer_sync_infoc                 C  sV   | j s| jrd S | jp| j}|r)tj|t d}|	d|
|  d S d S )Nr  zFind logs at: )r  r_  log_userlog_internalr   r  dirnamer  getcwdr^  r)  )r$  rC   log_dirra   ra   rb   r    s   zRun._footer_log_dir_infor  c                C  s  |j s|jrd S g }| rKtd dd | jD }g }t| D ]\}}tdd |D r/q!||}	|	r=|	||	g q!|rK|
|d}
|	|
 |ri }|jD ]}|jdsat|jdkrbqRt|j||j< qRtd	 g }t| D ];\}}t|tr|d d
 dt|d
k  }|	||g qyt|tjrt|trt|dn|}|	|t|g qyqy|r|
|d}|	| |r||| d S d S )Nzrendering historyc                 S  s2   i | ]}|j d s|j tj|jp|jdqS )r(  (   )r  r  rs   r  
downsamplevalues_float
values_int)r  r  ra   ra   rb   
<dictcomp>6  s    

z4Run._footer_history_summary_info.<locals>.<dictcomp>c                 s  s    | ]
}t |tj V  qd S r   )rW  numbersNumber)r  r  ra   ra   rb   r  @  s    z3Run._footer_history_summary_info.<locals>.<genexpr>zRun history:r(  r   zrendering summary   z...r   zRun summary:)r  r_  rT  rU  r  r  r  r  
sparklinesr  gridr  r  r  
nested_keyr  r  r  rW  rU   r  r  r  roundr^  panel)r  rt  r$  rC   r  r`  history_rowsr  values	sparklinehistory_gridra  r  summary_rowsr  summary_gridra   ra   rb   r  %  s^   






z Run._footer_history_summary_infoc                C  s8   |j s|jrd S | sd S | jjD ]	}|j|dd qd S )Nr  r}  )r  r_  r   r   r^  )r   r$  rC   r  ra   ra   rb   r  k  s   zRun._footer_internal_messagesc                 C  s.   | j s| jsdS |jdtd dd dS )z7Prints a message advertising the upcoming core release.NzThe legacy backend is deprecated. In future versions, `wandb-core` will become the sole backend service, and the `wandb.require('legacy-service')` flag will be removed. For more information, visit z
wandb-corer  r}  )r  x_require_legacy_servicer^  r   r!  rp  ra   ra   rb   r  {  s   
zRun._footer_notify_wandb_core)NNN)
r$  rN   rV  rR  rW  rR  rX  rR  r   r   )r  r   r   r   )r  r   r   r   r   )r  rm   r   r   )r  r-  r   r   )r  rU   r  r  r   r   )r  r  r   r,  )r   r   )r  r   r   r   )r   r  )r   rN   )r   rU   )r   r  )r   r  )r   rp   )r   rU   r   r   )r  rU   r   r   )r   r  )r\  r   r   r   )r   r  )r   r   )r   r  )
r  rp   r   rp   r  r  r  r  r   r  )r_  rp   r5  rp   r6  rp   r   r   )
r_  rp   r5  rp   r6  rp   r   rU   r   r   )rA  rX   r   r   )rR  r   r   r   )r[  F)r\  r   r]  r  r   r  )r\  r   r]  r  r   rU   NN)rh  ri  rj  ri  r   rk  )r  rm  rn  ri  rX  ro  r   r   )r  rU   rn  rr  r   r"   )r  rU   rn  r   r   r   )r  r<   r   r   )r   rL   r   r   )r   rm   )r  r   r   r   )r*  rU   r   r   )rX  rm   r   rm   )rX  rm   rb  r?  rW   r  r   r   )r   rU   rX  rU   r   r   )Tr   )r  rU   r  r  r  rU   r   r   )r  rO   r   r   )r  r  r   r   )r   r  r   r   )r  r3  r   r   )r  r!   r   r   )r  rU   r  rU   r  r  r   r   )
rX  rm   rb  r?  rW   r  r  r  r   r   )NNr  )r  r  r  r  r  r;   r   r  )r  r  r  r  r  r;   r   rX   NFN
r   rU   r  rp   r  r  r  rp   r   r  r  r?  r  r  r   r   r   )r  r?  r   r   )r   r'  )r)  rU   r*  rU   r+  r  r   r   )r9  r?  r:  r?  r;  rp   r   r   )r   r  )
r   rU   r  ri   r  rX   r  r  r   r"   )rn   rm   ro   rm   r  rX   r  rp   r[   r  r   r  )r  rU   r[   r  r   r"   )r  rK   r   r   )r  r  r  rL   r   r   )ra  rU   r   r   )NNNNNN)r   rU   r  r  r  r  r]  r  rt  rp   r  rp   r  r  r   r  )Nr  r  NF)r  r  r  r  r  r  r  r   r  r?  r  r  r   r   )r  r  r   r   )r  rU   rt  rp   r   rU   )rd   r"   r  rU   r  r  r   r   )
r  r  r|  rp   r  r  rt  rp   r   r"   )NNNN)r  r  r   rp   r|  rp   r  r  r\  r  r   r"   )r  r  r   rp   r|  rp   r  r  r  rp   r   r"   )NNNNNTFF)r  r  r   rp   r|  rp   r  r  r\  r  r  rp   r!  r  r  r  r  r  r   r"   )r  r.  r   r/  )
r  r  r   rp   r|  rp   r  r  r   r7  )r  r(   r   rp   r  r  r   r   )r   rU   r   r&   )
r  r(   rD  rU   r   rp   r  r  r   r   )
rF  rU   rG  rU   rH  rI  rJ  rK  r   r   )r   r,  )rU  rV  rW  rX  rY  r
   r   r  )r   r_  )r$  rN   rC   rT  r   r   )r`  rB  ra  rD  rb  rG  r   rI  r$  rN   rC   rT  r   r   )rb  rG  r$  rN   rC   rT  r   r   )
r  rB  rt  rD  r$  rN   rC   rT  r   r   )r   rI  r$  rN   rC   rT  r   r   )r]   r^   r_   r   r`   r   rY  r  r  r  r  r  r  r  r  r  r  r  propertyr  r   r  r$  r  rV  r  r   setterr  r  r\  r  r  r  r  r  r  r  rb  r  r  r  r  r
  r  r  r,   r?   exclude_wandb_fnr+  r/  r2  r4  r!  r  r<  r@  rI  rQ  rZ  r^  rc  rl  rn  rp  r  rv  r  rs  r  rz  r  r  r  r  r  r  r  r  r  r  r  r  r  r%  r  r  r  r  r  r  r   r(  r-  r8  rK  r^  r  rm  ri  ro  rz  r|  r  ry  r  r  r  r  r  r  r  re  r   r  r/  r  r1  r2  r  r  r  ry  r.  r$  r%  r!  rv  r)  r(  r4  r5  r6  r0  rT  r]  r3  rq  rs  rr  rs  rt  rj  r  r  r  r  r  __classcell__ra   ra   r  rb   r,    s  
 = 

U

	
$
= &  hO!0	n	,	E@N$"Bp(47D"#13\!0	G %Er,  r   rU   r  rp   r  r  r  r   r  c           
      C  s   t jduot jj}|rdnt j}|du r |dur|j}ntd|du r+|dur+|j}t }||}|du r<t	 }tj
|| }tj|rQ|du rQt|S |rUdS || g}	t|	dkrcdS |	d jdkrwtd|  d|pr| d|	d j|d	d
S )ac  Download the specified file from cloud storage.

    File is placed into the current directory or run directory.
    By default, will only download the file if it doesn't already exist.

    Args:
        name: the name of the file
        run_path: optional path to a run to pull files from, i.e. `username/project_name/run_id`
            if wandb.init has not been called, this is required.
        replace: whether to download the file even if it already exists locally
        root: the directory to download the file to.  Defaults to the current
            directory or the run directory if wandb.init was called.

    Returns:
        None if it can't find the file, otherwise a file object open for reading

    Raises:
        wandb.CommError: if we can't connect to the wandb backend
        ValueError: if the file is not found or can't find run_path
    Nz>run_path required when calling wandb.restore before wandb.initFr   0zFile z not found in r  T)r  r  )rs   r   r  r  r  r  r   r   r   r  r   r  r  r)  r  md5rA  )
r   r  r  r  is_disabledr   r  api_runr  r)  ra   ra   rb   r    s4   
r  r  r?  r  r  r   c                 C  s   t jrt jj| |d dS dS )a  Finish a run and upload any remaining data.

    Marks the completion of a W&B run and ensures all data is synced to the server.
    The run's final state is determined by its exit conditions and sync status.

    Run States:
    - Running: Active run that is logging data and/or sending heartbeats.
    - Crashed: Run that stopped sending heartbeats unexpectedly.
    - Finished: Run completed successfully (`exit_code=0`) with all data synced.
    - Failed: Run completed with errors (`exit_code!=0`).

    Args:
        exit_code: Integer indicating the run's exit status. Use 0 for success,
            any other value marks the run as failed.
        quiet: Deprecated. Configure logging verbosity using `wandb.Settings(quiet=...)`.
    r  r  N)rs   r   r  r  ra   ra   rb   r    s   r  r  r  r  r  )
__future__r   _threadr   rk  r
  r  r  loggingr  r   r  rerK  r   r   rZ  r  collections.abcr   dataclassesr   r   r   r   r   enumr	   typesr
   typingr   r   r   r   r   r   r   r2  rs   	wandb.envrv  r   wandb._globalsr   
wandb.apisr   r   wandb.apis.internalr   wandb.apis.publicr/  wandb.errorsr   r   r   wandb.errors.linksr   wandb.integration.torchr   
wandb.plotr   r   wandb.proto.wandb_internal_pb2r   r   r    r!   wandb.sdk.artifacts.artifactr"   wandb.sdk.internalr#   wandb.sdk.lib.import_hooksr$   r%   wandb.sdk.lib.pathsr&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r   r1   r2   r3   artifacts._validatorsr4   r5   r6   data_types._dtypesr7   interface.interfacer8   r9   r:   r;   interface.summary_recordr<   libr=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   lib.exit_hooksrH   lib.mailboxrI   rJ   rK   rL   wandb_alertsrM   wandb_settingsrN   wandb_setuprO   rP   torchwandb.sdk.backend.backend#wandb.sdk.interface.interface_queuerQ   rR   rS   rT   rc   rf   ri   	getLoggerrT  EXIT_TIMEOUTcompiler7  ru   ry   r|   r   r'  r,  r  r   r~  r  ra   ra   ra   rb   <module>   s    $$
4
	
 O`                           g9