o
    -wi<                    @  sn  U 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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  d dl!Z!d d	l"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(m+Z+ d dl,m-Z-m.Z. d dl/m0Z1 d dl2m3Z3m4Z4 d dl5m6Z6 d dl7m8Z8 d dl9m:Z:m;Z; d dl<m=Z= d dl>m?Z?m@Z@mAZAmBZB d dlCmDZD d dlEmFZF d dlGmHZH d dlImJZJ d dlKmLZLmMZM d dlNmOZOmPZP d dlQmRZRmSZS d dl*mTZTmUZUmVZVmWZWmXZXmYZYmZZZ ddl[m\Z\m]Z]m^Z^ ddl_m`Z`maZambZbmcZc ddldmeZe ddlfmgZgmhZhmiZimjZj dd lkmlZl dd!lmmnZnmoZompZpmqZqmrZrmsZsmtZtmuZumvZvmwZwmxZxmyZy dd"lzm{Z{ dd#l|m}Z}m~Z~mZmZ dd$lmZ dd%lmZ dd&lmZ erd d'lmZ d dlZd dl/Z(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/d0 d0ed1d2Zed3Zd4Ze
d5ZG d6d7 d7eZG d8d9 d9e&ZG d:d; d;Ze'd<Ze d=Zd^dAdBZdCadDedE< d^dFdGZd^dHdIZeG dJdK dKZG dLdM dMZ		1	d_d`dUdVZzejej_W n
 ey,   Y nw 		dadbd\d]ZdS )c    )annotationsN)Mapping)	dataclassfield)datetime	timedeltatimezone)IntEnum)TracebackType)TYPE_CHECKINGCallableSequenceTextIOTypeVar)AnyConcatenateLiteral
NamedTuple	ParamSpec)trigger)internalpublic)Api)	CommError
UsageError)url_registry)wandb_torch)CustomChart	Visualize)
Deprecated)MetricRecordPollExitResponseResult	RunRecord)InternalArtifact)is_artifact_registry_project)Artifact)job_builder)asyncio_compat
wb_logging)register_post_import_hookunregister_post_import_hook)FilePathStr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)MAX_ARTIFACT_METADATA_KEYSArtifactPathvalidate_aliasesvalidate_tags)TypeRegistry)	FilesDictGlobStrInterfaceBase
PolicyName)SummaryRecord)config_util	deprecate	filenames
filesystem	interruptipythonmoduleprinterprogress
proto_utilredirect	telemetry)	ExitHooks)HandleAbandonedErrorMailboxClosedErrorMailboxHandlewait_with_progress)
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__ rh   rh   P/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/wandb/sdk/wandb_run.pyr[   p   s
   
 r[   c                   @  s&   e Zd ZU ded< ded< ded< dS )ArtifactSourceDictr\   artifactr_   r`   ra   rb   Nrc   rh   rh   rh   ri   rj   v   s   
 rj   c                   @     e Zd ZU ded< ded< dS )ImageSourceDictr\   imagera   rb   Nrc   rh   rh   rh   ri   rm   {      
 rm   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 )JobSourceDictr\   _versionsource_typez4GitSourceDict | ArtifactSourceDict | ImageSourceDictsourcedict[str, Any]input_typesoutput_types
str | NoneruntimeNrc   rh   rh   rh   ri   rp      s   
 rp   F)totalwandb<   z[a-zA-Z0-9_-]+$c                   @  s   e Zd ZdZdZdS )TeardownStager5      N)rd   re   rf   EARLYLATErh   rh   rh   ri   r|      s    r|   c                   @  rl   )TeardownHookzCallable[[], None]callr|   stageNrc   rh   rh   rh   ri   r      ro   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	< 	
		d3d4ddZd5ddZed6dd Zd7d&d'Z	d5d(d)Z
d5d*d+Zd5d,d-Zd5d.d/Zd5d0d1Zd2S )8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[Result] | None_stop_status_handle_network_status_lock_network_status_handle_internal_messages_lock_internal_messages_handle      
   run_idr\   	interfacer@   settingsrU   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)_run_id
_interface_stop_polling_interval_retry_polling_interval#_internal_messages_polling_interval	_settings	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   r   r   rh   rh   ri   __init__   s8   	



zRunStatusChecker.__init__c                 C  s"   | j   | j  | j  d S N)r   startr   r   r   rh   rh   ri   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   rh   rh   ri   _abandon_status_check   s   
"z&RunStatusChecker._abandon_status_check
set_handler   timeoutrequestprocessc                C  s2  d }d}|st  }|sz| }W n
 ty   Y d S w |s J | | j r1	 W d    d S || W d    n1 s?w   Y  z|j|d}	W n tyV   Y d S  ty`   d }	Y nw | |d  W d    n1 srw   Y  |	r||	 d }t  | }
t||
 d}| jj	|d}|rd S d S )NFr   r   )
time	monotonicrQ   r   is_setwait_orrP   TimeoutErrormaxwait)r   r   r   r   r   r   local_handlejoin_requested
time_proberesulttime_elapsed	wait_timerh   rh   ri   _loop_check_status   sD   	



z#RunStatusChecker._loop_check_statusc              	        d
dd}t  j7 z j j fdd j jj|d	 W n ty1    	 j j
 Y n	w W d    d S W d    d S 1 sEw   Y  d S )Nr   r"   r   r   c                 S  sZ   | j j}|jD ]#}|jdks|jdkrt|j  qt|j d|j  d qd S )N   r   z encountered (z), retrying request)responsenetwork_status_responsenetwork_responseshttp_status_coderz   termloghttp_response_textrstrip)r   network_statushrrh   rh   ri   _process_network_status  s   
zFRunStatusChecker.check_network_status.<locals>._process_network_statusc                      t  d| S )Nr   setattrxr   rh   ri   <lambda>      z7RunStatusChecker.check_network_status.<locals>.<lambda>r   r   r   r   r   r   r"   r   r   )r)   
log_to_runr   r   r   r   r   deliver_network_statusBrokenPipeErrorr   r   )r   r   rh   r   ri   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_stoprz   agentspyagent
is_runningrG   interrupt_main)r   stop_statusrh   rh   ri   _process_stop_status(  s   z@RunStatusChecker.check_stop_status.<locals>._process_stop_statusc                   r   )Nr   r   r   r   rh   ri   r   5  r   z4RunStatusChecker.check_stop_status.<locals>.<lambda>r   r   )r)   r   r   r   r   r   r   deliver_stop_statusr   r   r   )r   r   rh   r   ri   r   '  s(   
	


"z"RunStatusChecker.check_stop_statusc              	     s   d
 fdd}t  j7 z j j fdd j jj|d	 W n ty3    	 j j
 Y n	w W d    d S W d    d S 1 sGw   Y  d S )Nr   r"   r   r   c                   sD    j jr j js j jrd S | jj}|jjD ]	}tj	|dd qd S )NFrepeat)
r   show_warningsquietsilentr   internal_messages_responsemessageswarningrz   termwarn)r   internal_messagesmsgr   rh   ri   _process_internal_messagesA  s   zLRunStatusChecker.check_internal_messages.<locals>._process_internal_messagesc                   r   )Nr   r   r   r   rh   ri   r   P  r   z:RunStatusChecker.check_internal_messages.<locals>.<lambda>r   r   )r)   r   r   r   r   r   r   deliver_internal_messagesr   r   r   )r   r   rh   r   ri   r   @  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   rh   rh   ri   stop[  s   
zRunStatusChecker.stopc                 C  s*   |    | j  | j  | j  d S r   )r   r   joinr   r   r   rh   rh   ri   r   j  s   

zRunStatusChecker.joinN)r   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   r   r   r   r   r   r   r   r   r   )rd   re   rf   __doc__rg   r   r   staticmethodr   r   r   r   r   r   r   rh   rh   rh   ri   r      s*   
 
*

-


r   _P_Tfunc"Callable[Concatenate[Run, _P], _T]r   c                      t  d fdd}|S )	a	  Decorate a Run method to set the run ID in the logging context.

    Any logs during the execution of the method go to the run's log file
    and not to other runs' log files.

    This is meant for use on all public methods and some callbacks. Private
    methods can be assumed to be called from some public method somewhere.
    The general rule is to use it on methods that can be called from a
    context that isn't specific to this run (such as all user code or
    internal methods that aren't run-specific).
    r   Runr   r   c                   s^   t | dr
| jj}n| j}t|  | g|R i |W  d    S 1 s(w   Y  d S )Nr   )hasattrr   r   
_attach_idr)   r   )r   rb   kwargsr   r  rh   ri   wrapper  s   

$z_log_to_run.<locals>.wrapperNr   r  r   r   	functoolswrapsr  r	  rh   r  ri   _log_to_runu  s   r   r\   _is_attachingc                   r  )	zDecorate a Run method to auto-attach when in a new process.

    When in a forked process or using a pickled Run instance, this automatically
    connects to the service process to "attach" to the existing run.
    r   r  r   r   c                   sz   | j d u}t| dd }|r2|t kr2tr!td j dt d jaz
tj| d W dandaw  | g|R i |S )N_attach_pidzTrying to attach `z$` while in the middle of attaching ``runr  )	r  getattrosgetpidr  RuntimeErrorrd   rz   _attach)r   rb   r  is_using_service
attach_pidr  rh   ri   r	    s   
	
z_attach.<locals>.wrapperNr
  r  r  rh   r  ri   r    s   	r  c                   r  )	zBDecorate a Run method to raise an error after the run is finished.r   r  r   r   c                   s@   t | dds | g|R i |S d| j d j d}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.)r  idrd   r   )r   rb   r  messager  rh   ri   
wrapper_fn  s   
z&_raise_if_finished.<locals>.wrapper_fnNr
  r  )r  r   rh   r  ri   _raise_if_finished  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)rd   re   rf   r   r$  rg   r%  r&  rh   rh   rh   ri   r"    s   
 r"  c                      s4  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< d1ed2< ded3< ded4< d5ed6< ded7< d8ed9< d:ed;< d<ed=< 	>	>	>dddEdFZ	>	>	>dddGdHZddIdJZddMdNZddPdQZ	ddRdSZ
ddTdUZd fdZd[Zdd^d_ZddadbZddddeZeddgdhZeeeddidjZeeeddkdlZeeeddndoZeeeddqdrZeeeddsdtZejeeddvdtZeeeddwdxZejeeddzdxZeeedd|d}Zejeeddd}ZeeedddZeeedddZdddZeeedddZ eeedddZ!eeedddZ"eeedddZ#eeedddZ$eeedddZ%eeedddZ&eeedddZ'eeedddZ(dddZ)eeedddZ*edddZ+eeedddZ,eeedd>e-e.j/fd ddZ0edddZ1eedddZ2edddZ3eeedddZ4eeedddZ5	>	>	>ddddZ6	>	>	>ddddZ7dddZ8dddZ9dddÄZ:eeddddɄZ;eedddd˄Z<	>dd	ddфZ=ee	>	>	>dd
dd؄Z>eddd܄Z?dddބZ@eedddZAedddZBedddZCedddZD	>ddddZEdddZFe	>	>ddddZGedddZHeedddZIe	dddd ZJdddZKdddZLdddZMdddZNdddZOdddZPdddZQ	>	>ddddZReee	>	>ddddZSeee	>	ddd&d'ZTd d*d+ZUee	>		>d!d"d/d0ZVee	>	>dd#d3d4ZWe	>dd$d5d6ZXeeed%d8d9ZYd&d>d?ZZ	>dd'dCdDZ[ddEdFZ\dd$dGdHZ]ddIdJZ^ddKdLZ_ddMdNZ`ddOdPZaddQdRZbddSdTZcddUdVZdd(dXdYZe	>dd)d_d`Zf	>	>dd*dfdgZg	>dd+dhdiZhd,dldmZiddndoZjekd-dqdrZleee	>	>	>	>	>	>d.d/dydzZm	>	>	>	>	>	>d.d/d{d|Znee	>	}	~	>	Őd0d1ddZoee	>dd2ddZpeee	>dd3ddZqeee	>	>	>dd4ddZreee	>	>	>	>d5d6ddZseee	>	>	>	>d5d7ddZteee	>	>	>	>d5d7ddZu	>	>	>	>	>			Őd8d9ddZvdd:ddZwdddZx	>	>	>dd;ddZyeee	>	>dd<ddZzeeed=ddZ{eee	>	>dd>ddZ|eee	>	>dd?ddZ}d@dÐdĄZ~dAdːd̄Zeeedd͐d΄ZeeeedBdАdфZddҐdӄZddԐdՄZdd֐dׄZddؐdلZek	>	>	>	>d5dCdߐdZek	>ddDddZekdEddZek	>	>ddFddZek	>ddGddZ  ZS (H  r  aF  A unit of computation logged by wandb. Typically, this is an ML experiment.

    Create a run with `wandb.init()`:
    ```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`:
    ```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:
    ```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_objbool_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_fdr_   _artifact_slotsr   	_init_pidr  rw   r  _is_attachedr  rU   r   _forkeddict[str, Any] | None_launch_artifactsprinter.Printer_printerzwandb_summary.SummarysummaryNr   configsweep_configlaunch_configr   r   c                 C  s6   t  | _d | _|jr|| _d S | j||||d d S )N)r   rQ  rR  rS  )r  r  rI  r  _noopr   _init)r   r   rQ  rR  rS  rh   rh   ri   r   G  s   

zRun.__init__c           	      C  s  || _ t | _| j| j | j| j | j| j  d}| j	|t
 i t| j| _| j| j d| _d| _d| _t | _t|| _d | _d | _d | _d | _d | _g | _d | _d | _ d | _!d | _"d | _#d | _$d | _%i | _&d | _'d | _(d | _)d | _*d | _+d | _,t-. | _/d| _0d| _1d| _2d| _3t4j5j6t
| j dd i | _7i | _8|pt
 }| jj	|ddd |r| jj9|d	dd
 |r| jj9|ddd
 t4j:; }|r|| j| d< t4j:< }|r|| j| d< t4j:= }|r|| j| d< d | _>d| _?d| _@tAB | _Cd| _D| j jE| _>d S )N_wandbr   F    user)tagsprocess_contextTallow_val_changeignore_lockedsweep)rX  _allow_val_changelaunchlaunch_queue_namelaunch_queue_entitylaunch_trace_id)Fr   r6   Config_config_set_callback_config_callback_set_artifact_callback_config_artifact_callback_set_settings_updatedictr8   Summary%_summary_get_current_summary_callbackrP  _set_update_callback_summary_update_callback_step_starting_step_start_runtimer   _start_timerJ   new_printerrO  _torch_historyr0  r1  r2  r9  r/  r7  r3  r4  rF  rG  r;  _exit_result_used_artifact_slotsr<  r>  r@  rC  rE  rA  rN   TelemetryRecordr(  r*  r-  r+  r8  rz   _sentryconfigure_scope_launch_artifact_mapping&_unique_launch_artifact_sequence_namesmerge_lockedenvget_launch_queue_nameget_launch_queue_entityget_launch_trace_idr  rJ  r  r  r  r  rK  r   )	r   r   rQ  rR  rS  	wandb_keyra  rb  rc  rh   rh   ri   rU  ^  s   







z	Run._initc              	   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   r`  r  environgetjsonloads
ValueErrorSyntaxErrorrz   r    _initialize_launch_artifact_mapslaunch_config_pathpathexistssaveopenread)r   r  fprS  rh   rh   ri   !_handle_launch_artifact_overrides  s0   z%Run._handle_launch_artifact_overridesr  rt   c                 C  sl   |  D ]/\}}|| j|< |d}t|dkr3|d dd }| j|r.| j| q|| j|< qd S )N:r}   r   /)itemsr|  splitlenr}  r  pop)r   r  keyitemartifact_sequence_tuple_or_slotsequence_namerh   rh   ri   r    s   


z$Run._initialize_launch_artifact_maps	telem_objc                 C  s2   t | dr| jr
d S | j| d| _|   d S )Nr(  T)r  r  r(  	MergeFromr+  _telemetry_flush)r   r  rh   rh   ri   _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*  r+  r0  r   r(  SerializeToStringr-  _publish_telemetry)r   
serializedrh   rh   ri   r    s   



zRun._telemetry_flushc                 C  s
   d| _ d S )NT)_frozenr   rh   rh   ri   _freeze     
zRun._freezeattrr\   value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  	Exceptionsuper__setattr__)r   r  r  	__class__rh   ri   r    s   zRun.__setattr__memodict[int, Any]c                 C     | S r   rh   )r   r  rh   rh   ri   __deepcopy__     zRun.__deepcopy__r   c                 C  s*   | j sdS | j}|sdS t|| j| jdS )z$Return run state as a custom pickle.N)r  rI  r  )r   r  rl  rI  r  )r   r  rh   rh   ri   __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  rI  z5attach in the same process is not supported currently)r  r  r  r  __dict__update)r   r  r  rh   rh   ri   __setstate__(  s   
zRun.__setstate__wandb_torch.TorchHistoryc                 C  s   | j d u r
t | _ | j S r   )rv  r   TorchHistoryr   rh   rh   ri   _torch6  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   rh   rh   ri   r   <  s   zRun.settingsc                 C     | j jS )z<The directory where files associated with the run are saved.)r   	files_dirr   rh   rh   ri   dirC     zRun.dirwandb_config.Configc                 C     | j S )z'Config object associated with this run.)re  r   rh   rh   ri   rQ  J     z
Run.configwandb_config.ConfigStaticc                 C  s   t | jS r   )r6   ConfigStaticre  r   rh   rh   ri   config_staticQ     zRun.config_staticc                 C  r  )zDisplay name of the run.

        Display names are not guaranteed to be unique and may be descriptive.
        By default, they are randomly generated.
        )r   run_namer   rh   rh   ri   r   W     	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)	rN   contextfeatureset_run_namer   r  r0  r   publish_run)r   r   telrh   rh   ri   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   rh   rh   ri   notesl  r  z	Run.notesr  c                 C  s0   || j _| jr| jjr| jj|  d S d S d S r   )r   r  r0  r   r  )r   r  rh   rh   ri   r  w  s   tuple | Nonec                 C     | j jpdS )z/Tags associated with the run, if there are any.rh   )r   run_tagsr   rh   rh   ri   rY    s   zRun.tagsrY  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  )
rN   r  r  set_run_tagstupler   r  r0  r   r  )r   rY  r  rh   rh   ri   rY    s   
c                 C     | j jdusJ | j jS )zIdentifier for this run.N)r   r   r   rh   rh   ri   r       zRun.idc                 C  r  )zBIdentifier for the sweep associated with the run, if there is one.)r   sweep_idr   rh   rh   ri   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   rh   ).0erh   rh   ri   	<genexpr>  s    z Run._get_path.<locals>.<genexpr>)r   r   entityprojectr   r   rh   rh   ri   	_get_path  s   
zRun._get_pathc                 C  s   |   S )zPath to the run.

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

        This counter is incremented by `wandb.log`.
        )rq  r   rh   rh   ri   step  s   zRun.stepc                 C  r  r   )r   _offliner   rh   rh   ri   offline     zRun.offlinec                 C  r  r   )r   rT  r   rh   rh   ri   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   rh   rh   ri   group  s   z	Run.groupc                 C  r  )Nr  )r   run_job_typer   rh   rh   ri   job_type  r  zRun.job_typec                 C     t j tjdd | jS )zName of the W&B project associated with the run.

        Note: this method is deprecated and will be removed in a future release.
        Please use `run.project` instead.
        zpThe project_name method is deprecated and will be removed in a future release. Please use `run.project` instead.
field_namewarning_message)rD   r   run__project_namer  r   rh   rh   ri   project_name  s
   zRun.project_namec                 C  r  )z0Name of the W&B project associated with the run.N)r   r  r   rh   rh   ri   r    r  zRun.projectc                 C  r  )zURL of the W&B project associated with the run, if there is one.

        Offline runs do not have a project URL.

        Note: this method is deprecated and will be removed in a future release.
        Please use `run.project_url` instead.
        zwThe get_project_url method is deprecated and will be removed in a future release. Please use `run.project_url` instead.r  )rD   r   run__get_project_urlproject_urlr   rh   rh   ri   get_project_url  
   	zRun.get_project_urlc                 C     | j jrtd dS | j jS )zzURL of the W&B project associated with the run, if there is one.

        Offline runs do not have a project URL.
         URL not available in offline runN)r   r  rz   r   r  r   rh   rh   ri   r       
zRun.project_url.root
include_fn2Callable[[str, str], bool] | Callable[[str], bool]
exclude_fnArtifact | Nonec                 C  sp  |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rptj|}t|||D ]}	d}tj|	|}
|j|	|
d q]t| jjD ]#\}}}|D ]}tj||}	tj|	| jj}
d}|j|	|
d q~qw|st	d	 dS | |}| jjd
d|jiidd |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-codeFTr   z_No relevant files were detected in the specified directory. No code will be logged to your run.rV  	code_path)r\  )r   _jupyternotebook_namex_jupyter_path
startswithx_jupyter_namer   r  program_relpathrz   utilmake_artifact_name_safer$   r  r  abspathrE   filtered_dirrelpathadd_filewalk_tmp_code_dirr   r   _log_artifactre  r  r   )r   r   r   r  r  r
  name_stringartfiles_added	file_path	save_namedirpath_filesfnamerk   rh   rh   ri   log_code+  sN   1



zRun.log_codec                 C  r  )zThe URL of the sweep associated with the run, if there is one.

        Offline runs do not have a sweep URL.

        Note: this method is deprecated and will be removed in a future release.
        Please use `run.sweep_url` instead.
        zsThe get_sweep_url method is deprecated and will be removed in a future release. Please use `run.sweep_url` instead.r  )rD   r   run__get_sweep_url	sweep_urlr   rh   rh   ri   get_sweep_url  r  zRun.get_sweep_urlc                 C  r  )zrURL of the sweep associated with the run, if there is one.

        Offline runs do not have a sweep URL.
        r  N)r   r  rz   r   r#  r   rh   rh   ri   r#    s   
zRun.sweep_urlc                 C  r  )zURL of the W&B run, if there is one.

        Offline runs do not have a URL.

        Note: this method is deprecated and will be removed in a future release.
        Please use `run.url` instead.
        zgThe get_url method is deprecated and will be removed in a future release. Please use `run.url` instead.r  )rD   r   run__get_urlurlr   rh   rh   ri   get_url  r  zRun.get_urlc                 C  r  )z]The url for the W&B run, if there is one.

        Offline runs will not have a url.
        r  N)r   r  rz   r   run_urlr   rh   rh   ri   r&    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   rh   rh   ri   r    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  )rN   r  RE_LABELmatchlabelcode_stringrepo_stringr*  )r   r  r)  r*  r  rh   rh   ri   _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  r)  r*  zLabel added for 'z' with invalid identifier 'z' (ignored).Fr   z Label added for unsupported key z (ignored).)r  r)  r*  )r   label_disabler+  r,  rz   r   r0  r  )r   r  r)  r*  r  kvrh   rh   ri   _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  cr)  rversionr3  r*  rh   )rN   _parse_label_linesr  r0  )r   r5  parsed
label_dictr  r)  code_verrh   rh   ri   _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  
splitlinesr=  )r   mdocdoclinesrh   rh   ri   _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   rs   zUnable to probe notebook: )	loggerinfoprobe_ipynbr  
isinstancer\   r  r  r=  )r   rF  r5  datacell0r  rh   rh   ri   _label_probe_notebook  s"   


zRun._label_probe_notebook  Fheighthiddenc                 C  sd   | j jrdS t sdS zddlm} W n ty#   td Y dS w ||	| 
|| dS )zDisplay this run in jupyter.Fr   )displayz-.display() only works in jupyter environmentsT)r   r   rH   
in_jupyterIPythonrR  ImportErrorrz   r   HTMLto_html)r   rP  rQ  rR  rh   rh   ri   rR  '  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   r(  rH   toggle_button)r   rP  rQ  r&  styleprefixrh   rh   ri   rW  :  s   zRun.to_htmlinclude
Any | Noneexcludedict[str, str]c                 C  s   d| j ddiS )Nz	text/htmlT)rQ  )rW  )r   r[  r]  rh   rh   ri   _repr_mimebundle_F  s   zRun._repr_mimebundle_r  tuple[str, ...] | str | NonevalrL  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  ra  rL  )rH  rI  r0  r   publish_config)r   r  ra  rL  rh   rh   ri   rg  K  s   zRun._config_callbackstr | Artifact | dictr&   c           	      C  s   t |r!t|tsJ |  }t|d |j}|sJ | |S t|r`t|t	s,J t
|\}}}i }|d urCd|i}t|}n|  }|rQt||j}n|j|d}|s[J | |S t|ri| |S tdt| )Nr  base_urlr  z.Cannot call _config_artifact_callback on type )r0   rK  rl  _public_apir&   _from_idclientuse_artifactr/   r\   r4   r   r   _client	_artifactr.   r  type)	r   r  ra  
public_apirk   artifact_stringrf  is_idr  rh   rh   ri   ri  W  s0   


zRun._config_artifact_callbackc                 C  s   | j d|f|d d S )NrV  )r  ra  rg  )r   r  ra  rh   rh   ri   _set_config_wandb  s   zRun._set_config_wandbsummary_recordrB   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  )rN   r  r  set_summaryr0  r   publish_summary)r   rs  r  rh   rh   ri   rp    s   
zRun._summary_update_callbackc                 C  sr   | j r
td i S | jr| jjsi S | jj }z
|j| jjd}W n t	y.   i  Y S w |j
j}t|jS )Nz*Summary data not available in finished runr   )r  rz   r   r0  r   deliver_get_summaryr   r   summary_timeoutr   r   get_summary_responserL   dict_from_proto_listr  )r   r   r   rx  rh   rh   ri   rn    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   )r0  r   _publish_metric)r   rz  rh   rh   ri   _metric_callback  s   zRun._metric_callbackr   c                 C  s8   | j r| j js	dS tt|dfgd}| j j| dS )a   Mark a run file to be uploaded with the run.

        This is a W&B-internal function: it can be used by other internal
        wandb code.

        Args:
            fname: The path to the file in the run's files directory, relative
                to the run's files directory.
        Nnow)r  )r0  r   rl  r?   publish_files)r   r   r  rh   rh   ri   _publish_file  s   zRun._publish_file
key_prefixc           	      C  s   t  }i }| D ]=\}}|r| d| n|}t|tr'|| |||< q	t|tr6|| |||< q	t|trF| ||}|| q	|D ]}|	| qI|S )zPops all charts from a dictionary including nested charts.

        This function will return a mapping of the charts and a dot-separated
        key for each chart. Indicating the path to the chart in the data dictionary.
        r  )
r   r  rK  r   addr   rl  _pop_all_chartsr  r  )	r   rL  r  keys_to_removechartsr2  r3  r  nested_chartsrh   rh   ri   r    s"   








zRun._pop_all_chartsc                 C  sv   |s|S |  |}| D ]+\}}|| | j|jj|jjd t|tr.|j	||jj
< qt|tr8|j	||< q|S )a8  Process and replace chart objects with their underlying table values.

        This processes the chart objects passed to `run.log()`, replacing their entries
        in the given dictionary (which is saved to the run's history) and adding them
        to the run's config.

        Args:
            data: Dictionary containing data that may include plot objects
                Plot objects can be nested in dictionaries, which will be processed recursively.

        Returns:
            The processed dictionary with custom charts transformed into tables.
        ra  r  )r  r  set_keyrg  specconfig_value
config_keyrK  r   table	table_keyr   )r   rL  r  r2  r3  rh   rh   ri   _serialize_custom_charts  s   




zRun._serialize_custom_chartsr  r^   bool | Nonec                 C  sV   | j r| j js	d S | }| |}ttjd dk}| j jj| || j|||d d S )Ntensorboardr   )	user_stepr  flushpublish_step)	r0  r   copyr  r  rz   patchedpublish_partial_historyrq  )r   rL  r  r^   not_using_tensorboardrh   rh   ri   _partial_history_callback  s   

zRun._partial_history_callbackc                 C  s*   | j r| j jr| j j|| d S d S d S r   )r0  r   publish_output)r   r   rL  rh   rh   ri   _console_callback
  s   zRun._console_callbackc                 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  r0  r   publish_output_raw)r   r   rL  console_pidrh   rh   ri   _console_raw_callback  s   	zRun._console_raw_callbackTr  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)rH  rI  r0  r   publish_tbdata)r   r  r  r  rh   rh   ri   _tensorboard_callback   s   zRun._tensorboard_callbacklibraryrV   c                 C  
   || _ d S r   )r2  )r   r  rh   rh   ri   _set_library(  r  zRun._set_librarybackend!wandb.sdk.backend.backend.Backendc                 C  r  r   )r0  )r   r  rh   rh   ri   _set_backend+  r  zRun._set_backendr   2wandb.sdk.interface.interface_queue.InterfaceQueuec                 C  r  r   )r1  )r   r   rh   rh   ri   _set_internal_run_interface.  s   
zRun._set_internal_run_interfacehooksc                 C  r  r   )r/  )r   r  rh   rh   ri   _set_teardown_hooks4  r  zRun._set_teardown_hooksrun_objr#   c                 C  s  |j r|j | _|j | _|jr|j d | _|jr|j| _|jr0t	
|jj}| 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rt|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    .ATr[  rX  )rZ  rY  )/r  rr  rq  r  ToMicrosecondsrt  rx   rs  rQ  rC   dict_no_value_from_proto_listr  re  rk  rP  r  r  
value_jsonr  r   r   r  r  r  r  r  display_namer  r  r  rY  r  r  r  hostr  git
remote_urlgit_remote_urlr^   
git_commitforkedrK  rz   rz  r{  rl  )r   r  c_dictsummary_dictorigrh   rh   ri   _set_run_obj7  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 )Nr5   )GitRepoF)r   r]   r  r^   lazyz:Cannot find valid git repo associated with this directory.)
lib.gitlibr  r   git_root
git_remoter  r  r  last_commitr  rz   r   )r   r  r)  rh   rh   ri   _populate_git_infot  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.
        )rm  r  r  rV  N)re  persist)r   r  r  r  value_extra	old_valuerh   rh   ri   _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   )rK  r\   )r  r  rh   rh   ri   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.r5   )rK  r   	TypeErroranykeysr  r  r  rI  rJ  rz   r   r  r  rq  )r   rL  r  r^   rh   rh   ri   _log  s*   
	
zRun._logc                 C  s|   |durt j| d}d|j_W d   n1 sw   Y  | jjr4|dur4t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/models/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`.

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

            ### Basic usage
            ```python
            import wandb

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

            ### Incremental logging
            ```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
            ```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
            ```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
            ```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
            ```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
            ```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  TztIn 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   )rL  r  r^   )rN   r  r  set_step_logr   _sharedrz   r   r   r&  r  )r   rL  r  r^   r  rh   rh   ri   log  s    q
zRun.logliveglob_strstr | os.PathLike	base_pathstr | os.PathLike | NonepolicyrA   bool | list[str]c                 C  s   t |tr
|d}t |tr|drt| d g S t|}tt	j
|}|dur6t|}n| s@td}ntjddd |jj}|d	vrSt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.
        zutf-8)zgs://zs3://z0 is a cloud storage url, can't save file to W&B.Nr  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.)rK  r,  decoder\   r  rz   r   pathlibPurePathr  r  r  Pathis_absoluter   parentr  _save)r   r  r  r  	glob_pathresolved_glob_pathresolved_base_pathrh   rh   ri   r    s4   
8

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 filer5   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 rh   )r?   r\   relative_tor   r  r  fr  r   rh   ri   
<listcomp>g  s    zRun._save.<locals>.<listcomp>c                 S  s   g | ]}t |qS rh   )r\   r  rh   rh   ri   r  r      )r\   r  r  r  partsr?   rN   r  r  r  r   r  r  r   r  globr  absoluter  resolver  mkdirunlink
symlink_torz   r   r0  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_dictrh   r  ri   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   rh   rh   ri   r  t  s   	

zRun.restore	exit_coder   c                 C  s$   |durt j t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  )rD   r   run__finish_quiet_finish)r   r  r   rh   rh   ri   finish  s   
z
Run.finishc                 C  s$  | j rd S | js
J td|    tj| d}d|j_W d    n1 s)w   Y  | j	D ]}|j
tjkr=|  q1d| _ | j|  z;| j|d | j	D ]}|j
tjkr]|  qQg | _	| jjrr| j }|j| jjd W tj| u r|t  tj  d S tj| u rt  tj  w )Nzfinishing run r  Tr  )r   )r  r2  rH  rI  r  rN   r  r  r  r/  r   r|   r~   r   remove_active_run_atexit_cleanupr   r   r   assert_serviceinform_finishrz   r  rI   unset_globalsrz  end_session)r   r  r  hookservicerh   rh   ri   r    s<   






zRun._finishr"  c                 C  sl   | j r| j js
t S | j j }|jdd}|jj}d}|jjr-t	
|jj|jjd  }t|j|j|dS )zMGet sync info from the internal backend, about the current run's sync status.Nr   g    eA)r$  r%  r&  )r0  r   r"  deliver_request_run_statusr   r   run_status_responser&  secondsr   fromtimestampnanosr$  r%  )r   handle_run_statusr   	sync_datar&  rh   rh   ri   status  s   z
Run.statusvisualize_key
panel_typepanel_configrl  c                 C  s"   ||d}| j |dd|fd d S )N)r  r  rV  	visualizer  rq  )r   r  r  r  rQ  rh   rh   ri   
_add_panel  s   zRun._add_panelstdout_slave_fdstderr_slave_fdconsolec           	   
     s  |d u r j j}|dkrd}td| |dv r.tj j jtj	} j
s.tt|d _
|dkrqtd tjd fd	d
 j
jg j jdkd}tjd fdd
 j
jg j jdkd}tjdkrpd! fdd}td| n^|dkrtd tjd fdd
 j
jg j jdkd}tjd fdd
 j
jg j jdk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d|  td  W Y d }~d S d }~ww )"Nwrapwrap_rawzredirect: %s>   rM   wrap_emuwbrM   zRedirecting console.stdoutc                        d| S Nr#  r  rL  r   rh   ri   r   	  r   zRun._redirect.<locals>.<lambda>online)srccbsflush_periodicallystderrc                   r$  Nr,  r&  r'  r   rh   ri   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  )r3  	uninstallr4  rz   r   	_redirect)r   r   rh   ri   wrap_fallback&	  s   


z$Run._redirect.<locals>.wrap_fallback
tensorflowr!  zWrapping output streams.c                   r$  r%  r&  r'  r   rh   ri   r   9	  r   c                   r$  r-  r&  r'  r   rh   ri   r   A	  r   c                   r$  r%  r  r'  r   rh   ri   r   K	  r   )r)  r*  c                   r$  r-  r3  r'  r   rh   ri   r   Q	  r   offzunhandled consolezRedirects installed.zFailed to redirect: zFailed to redirect.r   )r   r  rH  rI  r  r  r   r  rE   OUTPUT_FNAMEr7  rF   CRDedupedFiler  rM   Redirectwritemoder   r3   StreamWrapperStreamRawWrapperr  installr3  r4  r  rz   r   	exception)	r   r  r  r  output_log_path	out_redir	err_redirr1  r  rh   r   ri   r0    s   















zRun._redirectc                 C  s8   t d | jr| j  | jr| j  t d d S )Nr  zrestore done)rH  rI  r3  r/  r4  r   rh   rh   ri   _restored	  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yj   |   td td  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 runsampled_historyfinal_summarypoll_exit_responser   r   rJ   )r0  rH  r   r8  r9  r  r;  rI  r  r  r  r   resume_fnameremove
_on_finishKeyboardInterruptrz   wandb_agent_is_running	termerrorr  _console_stopr=  r  _footerr>  r@  rC  rE  rO  )r   r  rh   rh   ri   r  m	  s@   






zRun._atexit_cleanupc                 C  s&   t d t | _| | j| j d S )Nz
atexit reg)rH  rI  rO   r9  r0  rF  rG  r   rh   rh   ri   _console_start	  s   
zRun._console_startc                 C  s&   |    | jr| j  d | _d S d S r   )rA  r7  closer   rh   rh   ri   rM  	  s
   

zRun._console_stopc                 C  s   |    | jjr| jjd ur| | jj | jjr3| jr3| jjr3ddlm	} t
d | jj|  | jrV| jjrV| jjsV| jjsDJ t| jj| jj| jd| _| j  |   |   d S )Nr   working_setzBSaving list of pip packages installed into the current environment)r   r   )_headerr   	save_codecode_dirr!  x_save_requirementsr0  r   
wandb.utilrR  rH  debugpublish_python_packagesr  r   r   r<  r   rO  	_on_ready)r   rR  rh   rh   ri   	_on_start	  s(   
zRun._on_startc                 C  sF   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)rN   r  r  attachrJ  rZ  )r   r  rh   rh   ri   
_on_attach	  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  rI   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  rd   T)rN   r  r  r   imports_finishAttributeError)r  rI   r  r   rh   rh   ri   _telemetry_import_hook	  s   "zDRun._register_telemetry_import_hooks.<locals>._telemetry_import_hook)r  r  rI   r   r   r   )rN   list_telemetry_importsr  partialr   r   r*   )r   r`  import_telemetry_setimport_hook_fnmodule_namerh   rh   ri    _register_telemetry_import_hooks	  s   
z$Run._register_telemetry_import_hooksc                 C  s   | j sJ | j |  |   d| _|   z|   W n ty*   td Y n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 inputsN)r2  add_active_runrf  r*  r  _detect_and_apply_job_inputsr  rH  r=  r  r   resumer  r  r  rF  rG  r   rh   rh   ri   rZ  	  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.internalrj  apply)r   rj  rh   rh   ri   rh  	  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  r8  )r  drh   rh   ri   r  
  s     z,Run._make_job_source_reqs.<locals>.<genexpr>)
rW  rR  sortedr=   type_ofrQ  as_dictto_jsonrP  _as_dict)r   rR  installed_packages_listru   rv   rh   rh   ri   _make_job_source_reqs	  s
   
zRun._make_job_source_reqssource_dictrp   rt  
patch_pathos.PathLike | Nonec                 C  s   t |tj}|rtj|r|tt|d |	d}|
d| W d    n1 s0w   Y  |	d}|
t| W d    |S 1 sNw   Y  |S )Nz
diff.patchzrequirements.frozen.txt
zwandb-job.json)r$   r'   JOB_ARTIFACT_TYPEr  r  r  r  r,   r\   new_filer8  r   r  dumps)r   r   rv  rt  rw  job_artifactr  rh   rh   ri   _construct_job_artifact
  s   
zRun._construct_job_artifactru   rv   docker_image_namerb   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-v0rn   )rn   rb   )rq   rr   rs   ru   rv   rx   )	r  getenvrz   r  r  r   _args_pythonr~  )
r   ru   rv   rt  r  rb   r   s_argssource_infor}  rh   rh   ri   _create_image_job
  s    zRun._create_image_jobc                 C  sL   |   \}}}| j|||||d}|sJ | |}|s$td| |S )N)rb   r  zJob Artifact log unsuccessful: )ru  r  log_artifactrz   Error)r   r  rb   packagesin_types	out_typesr}  rk   rh   rh   ri   _log_job_artifact_with_image6
  s   
z Run._log_job_artifact_with_imageprogress_printerprogress.ProgressPrinterc              	     s   d  d fdd}d fdd}t  4 I d H }||  ||  W d   I d H  d S 1 I d H s9w   Y  d S )Nr   r   c                     s*   	  r  jjg tdI d H  q)NTg?)r  r   rE  asynciosleeprh   )last_resultr  rh   ri   loop_update_printerP
  s   z6Run._display_finish_stats.<locals>.loop_update_printerc                    sf   j rj js
J 	 j j } t }| jd dI d H  t | }|dk r2td| I d H  q)NTr   r5   )r0  r   deliver_poll_exitr   r   
wait_asyncr  r  )r   
time_startr   )r  r   rh   ri   loop_poll_exitX
  s   z1Run._display_finish_stats.<locals>.loop_poll_exitr   )r(   open_task_group
start_soon)r   r  r  r  
task_grouprh   )r  r  r   ri   _display_finish_statsJ
  s   .zRun._display_finish_statsc              	   C  s  t d | jd ur| j  |   | jr| jjsJ | jjr)| jj	| j
}n| jj }tj| jdd}t|d dt| j|d W d    n1 sOw   Y  | jj }|jd d}t| j|jj |jj| _| jj }|jd d}|jj| _| jj }| jj }|jd d}|jj| _|jd d}|jj | _!| jr| j"  | jr| j#  | jj$r| %| jj$ d S d S )Non_finishedzFinishing up...)default_textr5   )r   progress_afterdisplay_progressr   )&r   r   r<  r   rM  r0  r   r   x_update_finish_statedeliver_exitr;  deliver_finish_without_exitrK   r  rO  rS   r  rb  r  r  r   print_sync_dedupe_statsr   rE  rC  r   r   rE  rv  deliver_request_sampled_historysampled_history_responser>  rx  r@  cleanupr   r   "_unregister_telemetry_import_hooks)r   exit_handler  poll_exit_handler   internal_messages_handlefinal_summary_handlesampled_history_handlerh   rh   ri   rH  k
  s^   









zRun._on_finishr   c                 C  s    t  }|D ]}t||  qd S r   )rN   ra  r+   )r   rc  re  rh   rh   ri   r  
  s   z&Run._unregister_telemetry_import_hooksstep_metric str | wandb_metric.Metric | None	step_syncgoal	overwritewandb_metric.Metricc              	   C  sV   |rd|v rt  tjd|  |rd|v s|dur t  t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.)rD   r   run__define_metric_copyrun__define_metric_best_goal_define_metric)r   r   r  r  rQ  rP  r  r  rh   rh   ri   define_metric
  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  rQ  rP  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 rh   )lower)r  r  rh   rh   ri   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  rP  rQ  r  r  )rz   r  rK  r7   Metricr   r\   r)  rm  rd   endswithr  appendrN   r  r  metric_summaryr  metric_goalmetric_hiddenmetric_step_syncmetricrf  r|  _commit)r   r   r  r  rQ  rP  r  r  arg_namearg_valexp_typearg_typestrippedsummary_opssummary_itemsvalidir  goal_cleaned
valid_goalrB  rh   rh   ri   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)rz   sdk_watch)r   r  r  r  r  r  r  rh   rh   ri   watch@  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)rz   r  _unwatch)r   r  rh   rh   ri   unwatchf  s   zRun.unwatchrk   r  aliasesc                 C  sb   |  r| s| |}| jjrtt|}|jr t	|js)|j
| j| j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:
            The linked artifact if linking was successful, otherwise None.

        )rZ  r  )is_draft_is_draft_save_startedr  r   r  NotImplementedErrorr:   from_strr  r%   with_defaultsr  linkto_str)r   rk   r  r  r   rh   rh   ri   link_artifacts  s   

zRun.link_artifactartifact_or_namestr | Artifactrm  use_asc           	      C  s|  | j jrtdtj| j j| j jdd}|| j j |dur(t	j	t
jdd t|trd|}|  }|j||d}|durR||jkrRtd| d	|j d
|j |j|j| j j| j j|j|jd nJ|}|du rmg }nt|tru|g}t|tr| r|durtd | j||ddd |  nt|tr| s|j|j|j|jd ntd| jr| jjr| jj| |S )aQ  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: This argument is deprecated and does nothing.

        Returns:
            An `Artifact` object.
        z)Cannot use artifact when in offline mode.)r  r  )default_settingsNzW`use_as` argument is deprecated and does not affect the behaviour of `run.use_artifact`r  )rm  r   zSupplied type z does not match type z of artifact )entity_namer  artifact_entity_nameartifact_project_namez>Indicating use_as is not supported when using a draft artifactT)r  is_user_createduse_after_commit)r  r  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  r  r   r   r  r  set_current_run_idr   rD   r   run__use_artifact_use_asrK  r\   rg  rl  rm  r  r   rj  r  r&   r  rz   r   r  r   r0  r   publish_use_artifact)	r   r  rm  r  r  apir   rn  rk   rh   rh   ri   rj    sr   


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   rm  r  rY  r  )r   r  r   rm  r  rY  rh   rh   ri   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   rm  r  r  finalizer   r  r  r  r   r  r   rm  r  r  rh   rh   ri   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  rh   rh   ri   finish_artifacta  s   'zRun.finish_artifactr   r  r  c
              
   C  s  | j jdv rtd |s|d u rtd|d urt|}|d ur%t|}| ||||\}
}t|
j	t
kr>tdt
 d||
_| |
 | jr|| jjr|| j jsl| jjj| |
||| j|||	d}|
||  j |
S | jjj| |
|||||	d |
S | jr| jj| |
|||||	d |
S )NallowmustzGArtifacts logged anonymously cannot be claimed and expire after 7 days.z7Must provide distributed_id if artifact is not finalizez!Artifact must not have more than z metadata keys.)r   r  r  )r   	anonymousrz   r   r  r;   r<   _prepare_artifactr  metadatar9   r  r  _assert_can_log_artifactr0  r   r  deliver_artifactr  _set_save_handlerg  ri  publish_artifactr1  )r   r  r   rm  r  rY  r  r   r  r  rk   r   rh   rh   ri   r    sl   


	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   r   r  r  r  r   r   )r   r  rh   rh   ri   rg    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  rg  r   r&   _expected_typer   ri  requests
exceptionsRequestExceptionrm  r  _source_entity_source_project)r   rk   rn  r  r  expected_typerh   rh   ri   r    sF   



zRun._assert_can_log_artifacttuple[Artifact, list[str]]c                 C  s   t |ttjfrM|pd| jj dtj| }t||pd}tj	|r-|
t| n"tj|r;|t| ndt|v rI|t| ntd|}t |tsXt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)rK  r\   r  PathLiker   r   r  basenamer&   isfiler  isdiradd_diradd_referencer  r  r   r2   )r   r  r   rm  r  rk   rh   rh   ri   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   rm  r  Nr  )r   r  r   r  rh   rh   ri   	log_model+  s   0
zRun.log_modelr,   c                 C  sn   | j jrtd| j|d}dt|j vrtd| }t	
|}t|dkr5t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).
        z*`use_model` not supported in offline mode.)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'.r5   r   )r   r  r  rj  r\   rm  r  AssertionErrordownloadr  listdirr  r,   r  r   )r   r   rk   r  dir_listrh   rh   ri   	use_model_  s   *
zRun.use_modelregistered_model_namec           
   	   C  s   | d}t|dkrtdd}| jd | d | }|  }z!|j| dd}	dt|	j vr7td| j	|||	jd	}	W n t
tfyT   | j	||dd	}	Y nw | j|	||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:
            The linked artifact if linking was successful, otherwise None.
        r  r5   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   rm  )rk   r  r  )r  r  r$  r  rg  rl  r\   rm  r  r  r  r   r  )
r   r  r)  r   r  
name_partsr  r  rn  rk   rh   rh   ri   
link_model  s2   
I

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 rh   )r  )r  levrh   rh   ri   	<setcomp>  s    zRun.alert.<locals>.<setcomp>z/level must be one of 'INFO', 'WARN', or 'ERROR'r5   )minutes)r  total_secondsNz:wait_duration must be an int, float, or datetime.timedeltar  )rT   INFOrK  r  r  r   r   r  callabler  r  r5  r0  r   publish_alert)r   r,  r-  r.  r0  	level_strrh   rh   ri   alert  s   
z	Run.alertc                 C  r  r   rh   r   rh   rh   ri   	__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 )Nr5   r   r  )	tracebackprint_exceptionr  )r   r<  r>  r@  exception_raisedr  rh   rh   ri   __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)r0  r   publish_preemptingr   rh   rh   ri   mark_preempting9  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 }z|jd	d
}W n ty-   i  Y S w z|jj}|r:||W S i W S  t	yL   t
d i  Y S w )znReturns a dictionary of system metrics.

        Returns:
            A dictionary of system metrics.
        r   )wandb_internal_pb2system_metrics_pb+wandb_internal_pb2.GetSystemMetricsResponser   rG  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  )rI  resr  recordsmeasurementsrN  dtrh   rh   ri   
pb_to_dictP  s   


z'Run._system_metrics.<locals>.pb_to_dictr5   r   zError getting system metrics.N)rI  rJ  r   rG  )wandb.protorH  r0  r   deliver_get_system_metricsr   r   r   get_system_metrics_responser  rH  r=  )r   rH  rU  r   r   r   rh   rh   ri   _system_metricsD  s"   


zRun._system_metricsc                 C  s   |    |   |   d S r   )_header_wandb_version_info_header_sync_info_header_run_infor   rh   rh   ri   rS  x  s   zRun._headerc                 C  s,   | j js| j jr
d S | jdtj  d S )Nz Tracking run with wandb version )r   r   r   rO  rR  rz   __version__r   rh   rh   ri   rZ  }  s   zRun._header_wandb_version_infoc              
   C  s   | j jr#| jd| jd d| jd d| jd dg d S | j j}d| j| g}| jjsB|d	| jd
 d | j j	sR| j j
sT| j| d S d S d S )NzW&B syncing is set to z	`offline`z in this directory. Run z`wandb online`z or set zWANDB_MODE=onlinez to enable cloud syncing.zRun data is saved locally in zRun z`wandb offline`z to turn off syncing.)r   r  rO  rR  r  sync_dirr  supports_htmlr  r   r   )r   r^  rI  rh   rh   ri   r[    s$   

	zRun._header_sync_infoc                 C  s  | j | j}}|js|jrd S |j}|j}|j}|js|jr dnd}|j	}|s)d S |j
rzdd l}|j| syd||| d}	d\}
}|jsj|tdd}||d	}d
| d| d}
|rjd||| }|| d|	 d|
 |g n|r|| d||  |js||d d||  |r||d d||  ||d d||  |r|jdv r|jddd d S d S d S )NzResuming runzSyncing runr   z<strong>z	</strong>)r  r  zdeveloper-guidedocszWeights & Biaseszto z ()zSweep page: rc  starz View project at broomz View sweep at rocketz View run at r  zJDo NOT share these links with anyone. They can be used to claim your runs.warnr.  )r   rO  r  r   r(  r  r#  r  resume_fromr  r_  wandb.jupyterjupyterdisplay_if_magic_is_usedr  r   r   r&  rR  r   emojir  )r   r   rJ   r(  r  r#  run_state_strr  rz   run_lineproject_line
sweep_linedoc_htmlproject_htmlrh   rh   ri   r\    sb   
zRun._header_run_inforC  rD  rE  r   rJ   c                C  sD   t j| |||d t j|||d t j||d t j|||d d S )N)historyrP  r   rJ   )rE  r   rJ   )r   rJ   )r   r   rJ   )r  _footer_history_summary_info_footer_sync_info_footer_log_dir_info_footer_internal_messagesrB  rh   rh   ri   rN    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 rd  z
 View run z at: rb  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   rR  r  r^  r  r(  r  rk  r   r  r  file_countsrH  rI  wandb_countmedia_countartifact_countother_count)rE  r   rJ   rI  rw  rh   rh   ri   rt    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  getcwdrR  r  )r   rJ   log_dirrh   rh   ri   ru     s   zRun._footer_log_dir_inforr  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  rz   r  
downsamplevalues_float
values_int)r  r  rh   rh   ri   
<dictcomp>A  s    

z4Run._footer_history_summary_info.<locals>.<dictcomp>c                 s  s    | ]
}t |tj V  qd S r   )rK  numbersNumber)r  r  rh   rh   ri   r  K  s    z3Run._footer_history_summary_info.<locals>.<genexpr>zRun history:r  r   zrendering summary   z...r   zRun summary:)r   r   rH  rI  r  ro  r  r  
sparklinesr  gridr  r  r  
nested_keyr  r  r  rK  r\   r  r  r  roundrR  panel)rr  rP  r   rJ   r  rC  history_rowsr  values	sparklinehistory_gridrD  r  summary_rowsr  summary_gridrh   rh   ri   rs  0  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 )Nre  rf  )r   r   r   r   rR  )r   r   rJ   r  rh   rh   ri   rv  v  s   zRun._footer_internal_messages)NNN)
r   rU   rQ  rL  rR  rL  rS  rL  r   r   r   )r  rt   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   rU   )r   r\   )r   r  )r   r  )r   rw   )r   r\   r   r   )r  r\   r   r   )r   r  )rY  r   r   r   )r   r  )r   r   )r   r)  )
r   rw   r   rw   r  r  r  r  r   r  )r  rw   r)  rw   r*  rw   r   r   )
r  rw   r)  rw   r*  rw   r  r\   r   r   )r5  r_   r   r   )rF  r   r   r   )rO  F)rP  r   rQ  r)  r   r)  )rP  r   rQ  r)  r   r\   NN)r[  r\  r]  r\  r   r^  )r  r`  ra  r\  rL  rb  r   r   )r  r\   ra  re  r   r&   )r  r\   ra  r   r   r   )rs  rB   r   r   )r   rt   )rz  r    r   r   )r   r\   r   r   r   )rL  rt   r  rw   r   rt   )rL  rt   r   rt   )rL  rt   r  r:  r^   r  r   r   )r   r\   rL  r\   r   r   )Tr  )r  r\   r  r)  r  r\   r   r   )r  rV   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   )Nr  )r  r  r  r  r  rA   r   r  )r  r  r  r  r  rA   r   r_   NFN
r   r\   r  rw   r  r)  r   rw   r   r   r  r:  r   r  r   r   )r  r:  r   r   )r   r"  )r  r\   r  r\   r  rl  r   r   )r  r:  r  r:  r  rw   r   r   )r   rm  )
r   r\   rv  rp   rt  r_   rw  rx  r   r&   )ru   rt   rv   rt   rt  r_   r  rw   rb   r  r   r  )r  r\   rb   r  r   r&   )r  r  r   r   )r   r\   r   r   )NNNNNN)r   r\   r  r  r  r  rQ  r  rP  rw   r  rw   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   )rk   r&   r  r\   r  r  r   r  )
r  r  rm  rw   r  r  r  rw   r   r&   )NNNN)r  r  r   rw   rm  rw   r  r  rY  r  r   r&   )r  r  r   rw   rm  rw   r  r  r  rw   r   r&   )NNNNNTFF)r  r  r   rw   rm  rw   r  r  rY  r  r  rw   r   r)  r  r)  r  r)  r   r&   )r  r  r   r  )
r  r  r   rw   rm  rw   r  r  r   r  )r  r-   r   rw   r  r  r   r   )r   r\   r   r,   )
r  r-   r)  r\   r   rw   r  r  r   r  )
r,  r\   r-  r\   r.  r/  r0  r1  r   r   )r   r  )r<  r=  r>  r?  r@  r
   r   r)  )r   rG  )rC  r=  rD  r?  rE  rB  r   rD  r   rU   rJ   rN  r   r   )rE  rB  r   rU   rJ   rN  r   r   )r   rU   rJ   rN  r   r   )
rr  r=  rP  r?  r   rU   rJ   rN  r   r   )r   rD  r   rU   rJ   rN  r   r   )rd   re   rf   r   rg   r   rU  r  r  r  r  r  r  r  r  r  propertyr  r  r  r   r  rQ  r  r   setterr!  r  rY  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r1   rE   exclude_wandb_fnr!  r$  r#  r'  r&  r  r0  r4  r=  rE  rN  rR  rW  r_  rg  ri  rr  rp  rn  r|  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r0  rA  r  rO  rM  r[  r]  rf  rZ  rh  ru  r~  r  r  r  rH  r   r  r  r  r  r  r  rj  r  r  r  r  rg  r  r	  r"  r(  r+  r:  r;  rD  rF  rY  rS  rZ  r[  r\  rN  rt  ru  rs  rv  __classcell__rh   rh   r  ri   r    sX  
 :u
\

	
'#= & {]O .m	,!A@N$)](47I"#1;e!0E%Er  r   r  rw   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  )rz   r  r  r  r  r  r   r   r  r  r   r  r  r  r  md5r%  )
r   r  r  r   is_disabledr  r  api_runr  r  rh   rh   ri   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)rz   r  r  r  rh   rh   ri   r    s   r  )r  r  r   r  r  r  r  r  )
__future__r   r  r  r  r  loggingr  r  r  rer?  r   r   rA  collections.abcr   dataclassesr   r   r   r   r   enumr	   typesr
   typingr   r   r   r   r   r  typing_extensionsr   r   r   r   r   rz   	wandb.envrW  r   
wandb.apisr   r   wandb.apis.publicr   r  wandb.errorsr   r   wandb.errors.linksr   wandb.integration.torchr   
wandb.plotr   r   wandb.proto.wandb_deprecatedr   wandb.proto.wandb_internal_pb2r    r!   r"   r#   &wandb.sdk.artifacts._internal_artifactr$   wandb.sdk.artifacts._validatorsr%   wandb.sdk.artifacts.artifactr&   wandb.sdk.internalr'   wandb.sdk.libr(   r)   wandb.sdk.lib.import_hooksr*   r+   wandb.sdk.lib.pathsr,   r-   r.   r/   r0   r1   r2   r3   r4   r  r6   r7   r8   artifacts._validatorsr9   r:   r;   r<   data_types._dtypesr=   interface.interfacer>   r?   r@   rA   interface.summary_recordrB   librC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   lib.exit_hooksrO   mailboxrP   rQ   rR   rS   wandb_alertsrT   wandb_settingsrU   wandb_setuprV   rW   torchwandb.sdk.backend.backend#wandb.sdk.interface.interface_queuerX   rY   rZ   r[   rj   rm   rp   	getLoggerrH  EXIT_TIMEOUTcompiler+  r|   r   r   r   r   r  r  rg   r  r!  r"  r  r  r   r_  r  rh   rh   rh   ri   <module>   s    $
8
	
 [


*                           I9