o
    xi?                    @  s:  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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  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, d dl-m.Z.m/Z/ d dl0m1Z1 d dl2m3Z3 d dl4m5Z5m6Z6 d dl7m8Z8m9Z9m:Z:m;Z; d dl<m=Z= d dl>m?Z? d dl@mAZAmBZBmCZCmDZDmEZEmFZFmGZG d dlHmIZImJZJ d dlKmLZLmMZM d dl)mNZNmOZOmPZPmQZQmRZRmSZSmTZT ddlUmVZVmWZWmXZX ddlYmZZZ ddl[m\Z\ ddl]m^Z^ ddl_m`Z`maZambZbmcZcmdZdmeZemfZfmgZgmhZhmiZimjZjmkZk ddllmmZm ddlnmoZompZpmqZqmrZr ddlsmtZt dd lumvZv erd d!lmwZw d dlxZxd d"lymzZ{ d d#l7m|Z|m}Z}m~Z~ dd$lmZ dd%lmZ dd&lmZ dd'lmZ G d(d) d)ewZG d*d+ d+ewZG d,d- d-ewZG d.d/ d/ewd0d1Zed2Zd3Ze
d4ZG d5d6 d6eZG d7d8 d8e%ZG d9d: d:Ze&d;Ze d<Zd]d@dAZdBadCedD< d]dEdFZd]dGdHZeG dIdJ dJZG dKdL dLZ		0	d^d_dTdUZzejej_W n
 ey   Y nw 		d`dad[d\ZdS )b    )annotationsN)MappingSequence)	dataclassfield)datetime	timedeltatimezone)IntEnum)TracebackType)TYPE_CHECKINGCallableTextIOTypeVar)AnyConcatenateLiteral
NamedTuple	ParamSpec)trigger)
get_sentry)	CommError
UsageError)url_registry)wandb_torch)CustomChart	Visualize)MetricRecordPollExitResponseResult	RunRecord)
Deprecated)
wb_logging)	FilesDictGlobStr	LinkStats
PolicyNamelink_or_copy_with_policyunlink_pathvalidate_glob_path)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)TypeRegistry)InterfaceBase)SummaryRecord)config_utildeprecation	filenames
filesystem	interruptipythonmoduleprinterprogress
proto_utilredirect	telemetry)	ExitHooks)HandleAbandonedErrorMailboxClosedErrorMailboxHandlewait_with_progress)
AlertLevel)_WandbSetup)	TypedDict)Api)GetSummaryResponseInternalMessagesResponseSampledHistoryResponseArtifact)Backend)InterfaceQueue)Settingsc                   @  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__ rf   rf   G/home/ubuntu/.local/lib/python3.10/site-packages/wandb/sdk/wandb_run.pyrY   o   s
   
 rY   c                   @  s&   e Zd ZU ded< ded< ded< dS )ArtifactSourceDictrZ   artifactr]   r^   r_   r`   Nra   rf   rf   rf   rg   rh   u   s   
 rh   c                   @     e Zd ZU ded< ded< dS )ImageSourceDictrZ   imager_   r`   Nra   rf   rf   rf   rg   rk   z      
 rk   c                   @  sF   e Zd ZU ded< ded< ded< ded< ded< d	ed
< ded< dS )JobSourceDictrZ   _versionsource_typez4GitSourceDict | ArtifactSourceDict | ImageSourceDictsourcedict[str, Any]input_typesoutput_types
str | Noneruntimedict[str, str]servicesNra   rf   rf   rf   rg   rn   ~   s   
 rn   F)totalwandb<   z[a-zA-Z0-9_-]+$c                   @  s   e Zd ZdZdZdS )TeardownStager5      N)rb   rc   rd   EARLYLATErf   rf   rf   rg   r|      s    r|   c                   @  rj   )TeardownHookzCallable[[], None]callr|   stageNra   rf   rf   rf   rg   r      rm   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_idrZ   	interfacer:   settingsrX   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   rf   rf   rg   __init__   s8   	



zRunStatusChecker.__init__c                 C  s"   | j   | j  | j  d S N)r   startr   r   r   rf   rf   rg   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   )cancel)r   r   rf   rf   rg   _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	monotonicrJ   r   is_setwait_orrI   TimeoutErrormaxwait)r   r   r   r   r   r   local_handlejoin_requested
time_proberesulttime_elapsed	wait_timerf   rf   rg   _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hrrf   rf   rg   _process_network_status  s   
zFRunStatusChecker.check_network_status.<locals>._process_network_statusc                      t  d| S )Nr   setattrxr   rf   rg   <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   rf   r   rg   r     s(   



"z%RunStatusChecker.check_network_statusc              	     r   )Nr   r   r   r   c                 S  s6   ddl m} | jj}|jr| st  d S d S d S )Nr   )pyagent)wandb.agentsr   r   stop_status_responserun_should_stop
is_runningr@   interrupt_main)r   r   stop_statusrf   rf   rg   _process_stop_status(  s   z@RunStatusChecker.check_stop_status.<locals>._process_stop_statusc                   r   )Nr   r   r   r   rf   rg   r   6  r   z4RunStatusChecker.check_stop_status.<locals>.<lambda>r   r   )r"   r   r   r   r   r   r   deliver_stop_statusr   r   r   )r   r   rf   r   rg   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   rf   rg   _process_internal_messagesB  s   zLRunStatusChecker.check_internal_messages.<locals>._process_internal_messagesc                   r   )Nr   r   r   r   rf   rg   r   Q  r   z:RunStatusChecker.check_internal_messages.<locals>.<lambda>r   r   )r"   r   r   r   r   r   r   deliver_internal_messagesr   r   r   )r   r   rf   r   rg   r   A  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   rf   rf   rg   stop\  s   
zRunStatusChecker.stopc                 C  s*   |    | j  | j  | j  d S r   )r   r   joinr   r   r   rf   rf   rg   r   k  s   

zRunStatusChecker.joinN)r   r   r   )r   rZ   r   r:   r   rX   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   )rb   rc   rd   __doc__re   r   r   staticmethodr   r   r   r   r   r   r   rf   rf   rf   rg   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`   _P.argskwargs	_P.kwargsr   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   r`   r  r   r  rf   rg   wrapper  s   

$z_log_to_run.<locals>.wrapperNr   r  r`   r  r  r  r   r   	functoolswrapsr  r  rf   r
  rg   _log_to_runv  s   r   rZ   _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  r  r  r   r   c                   s   | j d u}t| dd }|r5|t kr5tr$td j d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  RuntimeErrorrb   rz   _attach)r   r`   r  is_using_service
attach_pidr
  rf   rg   r    s   
	
z_attach.<locals>.wrapperNr  r  r  rf   r
  rg   r    s   	r  c                   r  )zBDecorate a Run method to raise an error after the run is finished.r   r  r`   r  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  idrb   r   )r   r`   r  messager
  rf   rg   
wrapper_fn  s   
z&_raise_if_finished.<locals>.wrapper_fnNr  r  )r  r"  rf   r
  rg   _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)rb   rc   rd   r   r&  re   r'  r(  rf   rf   rf   rg   r$    s   
 r$  c                      sL  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d ddZ"eeedddZ#eeed ddZ$eeedddZ%eeeddd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djdkZiejd.dmdnZkeee	>	>	>	>	>	>d/d0dudvZl	>	>	>	>	>	>d/d0dwdxZmee	>	y	z	>	Őd1d2ddZnee	>dd3ddZoeee	>dd4ddZpeee	>	>	>dd5ddZqeee	>	>	>	>d6d7ddZreee	>	>	>	>d6d8ddZseee	>	>	>	>d6d8ddZt	>	>	>	>	>			Őd9d:ddZudd;ddZvdddZw	>	>	>dd<ddZxeee	>	>d
d=ddZyeeed>ddZzeee	>	>d
d?ddZ{eee	>	>d
d@ddZ|dAddZ}dBdǐdȄZ~eeeddɐdʄZeeeedCd̐d̈́ZddΐdτZddАdфZddҐdӄZddԐdՄZej	>	>	>	>d6dDdېd܄Zej	>ddEdݐdބZejdFdߐdZej	>	>d
dGddZejdHddZejdIddZej	>ddJddZ  ZS (K  r  a  A unit of computation logged by W&B. Typically, this is an ML experiment.

    Call [`wandb.init()`](https://docs.wandb.ai/ref/python/init/) to create a
    new run. `wandb.init()` starts a new run and returns a `wandb.Run` object.
    Each run is associated with a unique ID (run ID). W&B recommends using
    a context (`with` statement) manager to automatically finish the run.

    For distributed training experiments, you can either track each process
    separately using one run per process or track all processes to a single run.
    See [Log distributed training experiments](https://docs.wandb.ai/guides/track/log/distributed-training)
    for more information.

    You can log data to a run with `wandb.Run.log()`. Anything you log using
    `wandb.Run.log()` is sent to that run. See
    [Create an experiment](https://docs.wandb.ai/guides/track/create-an-experiment/) or
    [`wandb.init`](https://docs.wandb.ai/ref/python/init/) API reference page
    or more information.

    There is a another `Run` object in the
    [`wandb.apis.public`](https://docs.wandb.ai/ref/python/public-api/api/)
    namespace. Use this object is to interact with runs that have already been
    created.

    Attributes:
        summary: (Summary) A summary of the run, which is a dictionary-like
            object. For more information, see
            [Log summary metrics](https://docs.wandb.ai/guides/track/log/log-summary/).

    Examples:
    Create a run with `wandb.init()`:

    ```python
    import wandb

    # Start a new run and log some data
    # Use context manager (`with` statement) to automatically finish the run
    with wandb.init(entity="entity", project="project") as run:
        run.log({"accuracy": acc, "loss": loss})
    ```

    <!-- lazydoc-ignore-init: internal -->
    telemetry.TelemetryRecord_telemetry_objbool_telemetry_obj_active_telemetry_obj_dirtybytes_telemetry_obj_flushedlist[TeardownHook]_teardown_hookszBackend | None_backendz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  ru   r	  _is_attachedr  rX   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   rS  rT  rU  )r  r  rK  r	  _noopr   _init)r   r   rS  rT  rU  rf   rf   rg   r   9  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 | _d | _g | _d | _ d | _!d | _"d | _#d | _$d | _%d | _&i | _'d | _(d | _)d | _*d | _+d | _,d | _-t./ | _0d| _1d| _2d| _3d| _4t5 j6t
| j dd i | _7i | _8|pt
 }| jj	|ddd |r| jj9|d	dd
 |r| jj9|ddd
 t:j;< }|r|| j| d< t:j;= }|r|| j| d< t:j;> }|r|| j| d< d | _?d| _@d| _AtBC | _Dd| _E| j jF| _?d S )N_wandbr   F    user)tagsprocess_contextTallow_val_changeignore_lockedsweep)rZ  _allow_val_changelaunchlaunch_queue_namelaunch_queue_entitylaunch_trace_id)Gr   r6   Config_config_set_callback_config_callback_set_artifact_callback_config_artifact_callback_set_settings_updatedictr8   Summary%_summary_get_current_summary_callbackrR  _set_update_callback_summary_update_callback_step_starting_step_start_runtimer   _start_timerC   new_printerrQ  _torch_historyr2  r3  r4  _cached_public_apir;  r1  r9  r5  r6  rH  rI  r=  _exit_result_used_artifact_slotsr>  r@  rB  rE  rG  rC  rG   TelemetryRecordr*  r,  r/  r-  r:  r   configure_scope_launch_artifact_mapping&_unique_launch_artifact_sequence_namesmerge_lockedrz   envget_launch_queue_nameget_launch_queue_entityget_launch_trace_idr	  rL  r  r  r  r  rM  r   )	r   r   rS  rT  rU  	wandb_keyrc  rd  re  rf   rf   rg   rW  P  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   rb  r  environgetjsonloads
ValueErrorSyntaxErrorrz   r    _initialize_launch_artifact_mapslaunch_config_pathpathexistssaveopenread)r   r  fprU  rf   rf   rg   !_handle_launch_artifact_overrides  s0   z%Run._handle_launch_artifact_overridesr  rr   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_namerf   rf   rg   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  rf   rf   rg   _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-  r2  r   r*  SerializeToStringr/  _publish_telemetry)r   
serializedrf   rf   rg   r    s   



zRun._telemetry_flushc                 C  s
   d| _ d S )NT)_frozenr   rf   rf   rg   _freeze      
zRun._freezeattrrZ   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__rf   rg   r    s   zRun.__setattr__memodict[int, Any]c                 C     | S r   rf   )r   r  rf   rf   rg   __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	  rK  r  )r   r	  rn  rK  r  )r   r	  rf   rf   rg   __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	  rK  z5attach in the same process is not supported currently)r  r  r  r  __dict__update)r   r  r	  rf   rf   rg   __setstate__  s   
zRun.__setstate__wandb_torch.TorchHistoryc                 C  s   | j d u r
t | _ | j S r   )rx  r   TorchHistoryr   rf   rf   rg   _torch)  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   rf   rf   rg   r   /  s   zRun.settingsc                 C     | j jS )z<The directory where files associated with the run are saved.)r   	files_dirr   rf   rf   rg   dir6     zRun.dirwandb_config.Configc                 C     | j S )z'Config object associated with this run.)rg  r   rf   rf   rg   rS  =     z
Run.configwandb_config.ConfigStaticc                 C  s   t | jS )z.Static config object associated with this run.)r6   ConfigStaticrg  r   rf   rf   rg   config_staticD     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   rf   rf   rg   r   K     	zRun.namer   c                 C  sd   t j| d}d|j_W d    n1 sw   Y  || j_| jr.| jjr0| jj|  d S d S d S Nr  T)	rG   contextfeatureset_run_namer   r  r2  r   publish_run)r   r   telrf   rf   rg   r   V  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   rf   rf   rg   notes`  r  z	Run.notesr  c                 C  s0   || j _| jr| jjr| jj|  d S d S d S r   )r   r  r2  r   r  )r   r  rf   rf   rg   r  k  s   tuple | Nonec                 C     | j jpdS )z/Tags associated with the run, if there are any.rf   )r   run_tagsr   rf   rf   rg   r[  s  r  zRun.tagsr[  r   c              
   C  s   t j| d}d|j_W d    n1 sw   Y  zt|| j_W n0 tyR } z$t|}d|v r>|	dd 	dd }t
d| d	 W Y d }~d S d }~ww | jrc| jjre| jj|  d S d S d S )
Nr  TzValue error,zValue error, r5   z [type=r   zInvalid tag detected: z Tags not updated.)rG   r  r  set_run_tagstupler   r  r  rZ   r  rz   r   r2  r   r  )r   r[  r  e	error_msgrf   rf   rg   r[  z  s    

c                 C     | j jdusJ | j jS )zIdentifier for this run.N)r   r   r   rf   rf   rg   r        zRun.idc                 C  r  )zBIdentifier for the sweep associated with the run, if there is one.)r   sweep_idr   rf   rf   rg   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   rf   ).0r  rf   rf   rg   	<genexpr>  s    z Run._get_path.<locals>.<genexpr>)r   r   entityprojectr   r   rf   rf   rg   	_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   rf   rf   rg   r    r  zRun.pathfloatc                 C  r  )z4Unix timestamp (in seconds) of when the run started.)rv  r   rf   rf   rg   
start_time  r  zRun.start_timec                 C  r  )zNThe first step of the run.

        <!-- lazydoc-ignore: internal -->
        )rt  r   rf   rf   rg   starting_step  s   zRun.starting_stepc                 C  r  )z-True if the run was resumed, False otherwise.)r   resumedr   rf   rf   rg   r    r  zRun.resumedc                 C  r  )zCurrent value of the step.

        This counter is incremented by `wandb.Run.log()`.

        <!-- lazydoc-ignore: internal -->
        )rs  r   rf   rf   rg   step  s   
zRun.stepc                 C  r  )z,True if the run is offline, False otherwise.)r   _offliner   rf   rf   rg   offline  r  zRun.offlinec                 C  r  )z-True if the run is disabled, False otherwise.)r   rV  r   rf   rf   rg   disabled  r  zRun.disabledc                 C  r  )a+  Returns the name of the group associated with this run.

        Grouping runs together allows related experiments to be organized and
        visualized collectively in the W&B UI. This is especially useful for
        scenarios such as distributed training or cross-validation, where
        multiple runs should be viewed and managed as a unified experiment.

        In shared mode, where all processes share the same run object,
        setting a group is usually unnecessary, since there is only one
        run and no grouping is required.
        r  )r   	run_groupr   rf   rf   rg   group  s   z	Run.groupc                 C  r  )a  Name of the job type associated with the run.

        View a run's job type in the run's Overview page in the W&B App.

        You can use this to categorize runs by their job type, such as
        "training", "evaluation", or "inference". This is useful for organizing
        and filtering runs in the W&B UI, especially when you have multiple
        runs with different job types in the same project. For more
        information, see [Organize runs](https://docs.wandb.ai/guides/runs/#organize-runs).
        r  )r   run_job_typer   rf   rf   rg   job_type  s   zRun.job_typec                 C     t jtdddd | jS )zThis method is deprecated and will be removed in a future release. Use `run.project` instead.

        Name of the W&B project associated with the run.

        <!-- lazydoc-ignore: internal -->
        T)run__project_namezpThe project_name method is deprecated and will be removed in a future release. Please use `run.project` instead.r  r!  )r=   warn_and_record_deprecationr!   r  r   rf   rf   rg   project_name  s
   zRun.project_namec                 C  r  )z0Name of the W&B project associated with the run.N)r   r  r   rf   rf   rg   r    r  zRun.projectc                 C  r  )a  This method is deprecated and will be removed in a future release. Use `run.project_url` instead.

        URL of the W&B project associated with the run, if there is one.
        Offline runs do not have a project URL.

        <!-- lazydoc-ignore: internal -->
        T)run__get_project_urlzwThe get_project_url method is deprecated and will be removed in a future release. Please use `run.project_url` instead.r  )r=   r  r!   project_urlr   rf   rf   rg   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   rf   rf   rg   r  2     
zRun.project_url.root
include_fn2Callable[[str, str], bool] | Callable[[str], bool]
exclude_fnArtifact | Nonec                 C  s|  ddl m} |du rK| jjr7d}| 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| }||d}d}	|durvtj|}t|||D ]}
d	}	tj|
|}|j|
|d
 qct| jjD ]#\}}}|D ]}tj||}
tj|
| jj}d	}	|j|
|d
 qq}|	std dS | |}| jjdd|jiid	d |S )a  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
        import wandb

        with wandb.init() as run:
            run.log_code()
        ```

        Advanced usage

        ```python
        import wandb

        with wandb.init() as run:
            run.log_code(
                root="../",
                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
        r   InternalArtifactNzfileId=-zsource-codeFTr   z_No relevant files were detected in the specified directory. No code will be logged to your run.rX  	code_path)r^  )&wandb.sdk.artifacts._internal_artifactr  r   _jupyternotebook_namex_jupyter_path
startswithx_jupyter_namer   r  program_relpathrz   utilmake_artifact_name_safer  r  abspathr>   filtered_dirrelpathadd_filewalk_tmp_code_dirr   r   _log_artifactrg  r  r   )r   r  r   r  r  r  r  name_stringartfiles_added	file_path	save_namedirpath_filesfnameri   rf   rf   rg   log_code?  sP   9



zRun.log_codec                 C  r  )a	  This method is deprecated and will be removed in a future release. Use `run.sweep_url` instead.

        The URL of the sweep associated with the run, if there is one.
        Offline runs do not have a sweep URL.

        <!-- lazydoc-ignore: internal -->
        T)run__get_sweep_urlzsThe get_sweep_url method is deprecated and will be removed in a future release. Please use `run.sweep_url` instead.r  )r=   r  r!   	sweep_urlr   rf   rf   rg   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   rf   rf   rg   r'    s   
zRun.sweep_urlc                 C  r  )zThis method is deprecated and will be removed in a future release. Use `run.url` instead.

        URL of the W&B run, if there is one. Offline runs do not have a URL.

        <!-- lazydoc-ignore: internal -->
        T)run__get_urlzgThe get_url method is deprecated and will be removed in a future release. Please use `run.url` instead.r  )r=   r  r!   urlr   rf   rf   rg   get_url  s
   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   rf   rf   rg   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   rf   rf   rg   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  )rG   r  RE_LABELmatchlabelcode_stringrepo_stringr.  )r   r	  r-  r.  r  rf   rf   rg   _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/  r0  rz   r   r4  r  )r   r	  r-  r.  r  kvrf   rf   rg   _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versionr7  r.  rf   )rG   _parse_label_linesr  r4  )r   r9  parsed
label_dictr	  r-  code_verrf   rf   rg   _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  
splitlinesrA  )r   mdocdoclinesrf   rf   rg   _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   rq   zUnable to probe notebook: )	loggerinfoprobe_ipynbr  
isinstancerZ   r  r  rA  )r   rJ  r9  datacell0r  rf   rf   rg   _label_probe_notebook4  s"   


zRun._label_probe_notebook  Fheighthiddenc                 C  sl   | j jrdS t rt r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   rA   
in_jupyterin_vscode_notebookIPythonrV  ImportErrorrz   r   HTMLto_html)r   rT  rU  rV  rf   rf   rg   rV  D  s   
zRun.displayc                 C  sd   t  rddl}|t| S | jjd }d| d}d}|r'|d7 }t  }|d|d	|d
 S )zGenerate HTML containing an iframe displaying the current run.

        If the run is being displayed in a VSCode notebook,
        the string representation of the run is returned instead.

        <!-- lazydoc-ignore: internal -->
        r   Nz?jupyter=truezborder:none;width:100%;height:zpx;r  zdisplay:none;z<iframe src=z style=z
></iframe>)rA   rX  htmlescaperZ   r   r,  toggle_button)r   rT  rU  r]  r*  styleprefixrf   rf   rg   r\  W  s   
zRun.to_htmlinclude
Any | Noneexcluderw   c                 C  s   d| j ddiS )Nz	text/htmlT)rU  )r\  )r   rb  rd  rf   rf   rg   _repr_mimebundle_n  s   zRun._repr_mimebundle_r  tuple[str, ...] | str | NonevalrP  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  rg  rP  )rL  rM  r2  r   publish_config)r   r  rg  rP  rf   rf   rg   ri  s  s   zRun._config_callbackstr | Artifact | dictrU   c                 C  s   ddl m} ddlm} t|r-t|tsJ |  }||d |j	}|s(J | 
|S t|rlt|ts8J t|\}}}	i }
|d urOd|i}
||
}n|  }|	r]|||j}n|j|d}|sgJ | 
|S t|ru| 
|S tdt| )Nr   publicrT   r   base_urlr
  z.Cannot call _config_artifact_callback on type )
wandb.apisrm  wandb.sdk.artifacts.artifactrU   r0   rO  rn  _public_api_from_idclientuse_artifactr/   rZ   r4   rP   _client	_artifactr.   r  type)r   r  rg  rm  rU   
public_apiri   artifact_stringrn  is_idr  rf   rf   rg   rk    s4   


zRun._config_artifact_callbackc                 C  s   | j d|f|d d S )NrX  )r  rg  ri  )r   r  rg  rf   rf   rg   _set_config_wandb  s   zRun._set_config_wandbsummary_recordr;   c                 C  s^   t j| d}d|j_W d    n1 sw   Y  | jr+| jjr-| jj| | d S d S d S r  )rG   r  r  set_summaryr2  r   publish_summary)r   r}  r  rf   rf   rg   rr    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   r2  r   deliver_get_summaryr   r   summary_timeoutr   r   get_summary_responserE   dict_from_proto_listr  )r   r   r   r  rf   rf   rg   rp    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   )r2  r   _publish_metric)r   r  rf   rf   rg   _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#  )r2  r   rn  r$   publish_files)r   r$  r#  rf   rf   rg   _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  rO  r   addr   rn  _pop_all_chartsr  r  )	r   rP  r  keys_to_removechartsr6  r7  r  nested_chartsrf   rf   rg   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 )a>  Process and replace chart objects with their underlying table values.

        This processes the chart objects passed to `wandb.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.
        rg  r  )r  r  set_keyri  specconfig_value
config_keyrO  r   table	table_keyr   )r   rP  r  r6  r7  rf   rf   rg   _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)	r2  r   copyr  r  rz   patchedpublish_partial_historyrs  )r   rP  r  r\   not_using_tensorboardrf   rf   rg   _partial_history_callback  s   

zRun._partial_history_callbackc                 C  s.   | j r| j jr| j jj||dd d S d S d S )NTnowait)r2  r   publish_output)r   r   rP  rf   rf   rg   _console_callback5  s   zRun._console_callbackc                 C  sJ   t | dd}|t krd S | jr!| jjr#| jjj||dd d S d S d S )Nr  r   Tr  )r  r  r  r2  r   publish_output_raw)r   r   rP  console_pidrf   rf   rg   _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)rL  rM  r2  r   publish_tbdata)r   r  r  r  rf   rf   rg   _tensorboard_callbackJ  s   zRun._tensorboard_callbacklibraryrN   c                 C  
   || _ d S r   )r4  )r   r  rf   rf   rg   _set_libraryR  r  zRun._set_librarybackendrV   c                 C  r  r   )r2  )r   r  rf   rf   rg   _set_backendU  r  zRun._set_backendr   rW   c                 C  r  r   )r3  )r   r   rf   rf   rg   _set_internal_run_interfaceX  r  zRun._set_internal_run_interfacehooksc                 C  r  r   )r1  )r   r  rf   rf   rg   _set_teardown_hooks[  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,dt-| jd d S )Ng    .ATr]  rZ  )r\  r[  ).r  rt  rs  r  ToMicrosecondsrv  rv   ru  rS  r<   dict_no_value_from_proto_listr  rg  rm  rR  r  r  
value_jsonr  r   r   r  r  r  r  r  display_namer  r  r  r[  r  r  r  hostr  git
remote_urlgit_remote_urlr\   
git_commitforkedrM  r   r}  rn  )r   r  c_dictsummary_dictorigrf   rf   rg   _set_run_obj^  sb   










zRun._set_run_objc                 C  sh   ddl m} z|| jj| jj| jj| jjdd}|j| j_|j| j_W d S  t	y3   t
d Y d S w )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-  rf   rf   rg   _populate_git_info  s   
zRun._populate_git_info	data_typedict[int | str, str]c                 C  s~   |||d}|| j d vri | j d |< || j d | v r'| j d | | }nd}||kr=|| j d | |< | j   dS dS )a  Store a singleton item to wandb config.

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

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

        Add singleton can be called many times in one run, and it will only be
        updated when the value changes. The last value logged will be the one
        persisted to the server.
        )rw  r  r  rX  N)rg  persist)r   r  r  r  value_extra	old_valuerf   rf   rg   _add_singleton  s   zRun._add_singletonc                 C  s   t |ts	tdtdd |D rtd| ||| |d urJt | jks+| jr2t	j
ddd tt	jd d	krBt	j
d
dd || jkrJ|| _|d u rR|d u sT|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   )rO  rZ   )r  r  rf   rf   rg   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   )rO  r   	TypeErroranyr  r  r  rK  rL  rz   r   r  r  rs  )r   rP  r  r\   rf   rf   rg   _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 [Log objects and media](https://docs.wandb.ai/guides/track/log) for
        code snippets, best practices, and more.

        Basic usage:

        ```python
        import wandb

        with wandb.init() as run:
            run.log({"train-loss": 0.5, "accuracy": 0.9})
        ```

        The previous code snippet saves the loss and accuracy to the run's
        history and updates the summary values for these metrics.

        Visualize logged data in a 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, such as in a
        Jupyter notebook, with the [Public API](https://docs.wandb.ai/guides/track/public-api-guide).

        Logged values don't have to be scalars. You can log any
        [W&B supported Data Type](https://docs.wandb.ai/ref/python/data-types/)
        such as images, audio, video, and more. For example, you can use
        `wandb.Table` to log structured data. See
        [Log tables, visualize and query data](https://docs.wandb.ai/guides/models/tables/tables-walkthrough)
        tutorial for more details.

        W&B 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":

        ```python
        with wandb.init() as run:
            # Log metrics in the "train" section.
            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".

        `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.

        By default, each call to `log` creates a new "step".
        The step must always increase, and it is not possible to log
        to a previous step. You can use any metric as the X axis in charts.
        See [Custom log axes](https://docs.wandb.ai/guides/track/log/customize-logging-axes/)
        for more details.

        In many cases, it is better to treat the W&B step like
        you'd treat a timestamp rather than a training step.

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

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

        ```python
        with wandb.init() as run:
            # 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, commit=True)
        ```

        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

        with wandb.init() as run:
            run.log({"train-loss": 0.5, "accuracy": 0.9
        ```

        Incremental logging

        ```python
        import wandb

        with wandb.init() as run:
            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)
        with wandb.init() as run:
            run.log({"gradients": wandb.Histogram(gradients)})
        ```

        Image from NumPy

        ```python
        import numpy as np
        import wandb

        with wandb.init() as run:
            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

        with wandb.init() as run:
            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

        with wandb.init() as run:
            # 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

        with wandb.init() as run:
            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

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

        3D Object

        ```python
        import wandb

        with wandb.init() as run:
            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   )rP  r  r\   )rG   r  r  set_step_logr   _sharedrz   r   r   r*  r  )r   rP  r  r\   r  rf   rf   rg   log  s    }
zRun.logliveglob_strstr | os.PathLike	base_pathstr | os.PathLike | Nonepolicyr&   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.

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

        Files are automatically deduplicated: calling `save()` multiple times
        on the same file without modifications will not re-upload it.

        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.

        ```python
        import wandb

        run = wandb.init()

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

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

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

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

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

        # Explicitly finish the run since a context manager is not used.
        run.finish()
        ```
        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.)rO  r.  decoderZ   r  rz   r   pathlibPurePathr  r  r  Pathis_absoluter   parentr  _save)r   r  r  r  	glob_pathresolved_glob_pathresolved_base_pathrf   rf   rg   r    s4   
A

zRun.saver  pathlib.PurePathc              	     s
  t || ||}tt|}tj| d}d|j_W d   n1 s%w   Y  t	| j
j t |}dd tttt|| D }t }	g }
t }|D ]o}tj	|jt|jd  } | }|| tt' | r||r|
tt| |f 	 W d   qTW d   n1 sw   Y  |jjddd t| t| j
||||	}|
tt| |f qTt|D ]}||vr|
tt| |f q|	  d|
i}| jr| jjr| jj |  fdd	|
D }d
d t|D S )a  Materialize matched files into the run's files/ dir for syncing.

        Strategy:
        1) If settings.symlink is True, try symlink.
        2) Else (or if symlink fails), try hardlink (same-volume files).
        3) Else copy and, if requested policy == "live", downgrade those files to "now".

        Args:
            glob_path: Absolute path glob pattern for files to save.
            base_path: Base path to determine relative directory structure.
            policy: Upload policy - "live", "now", or "end".

        Returns:
            List of absolute paths to files in the wandb run directory.

        Raises:
            ValueError: If glob_path is invalid relative to base_path.
        r  TNc                 S  s   g | ]	}t | qS rf   )r  r  absoluter  prf   rf   rg   
<listcomp>  s    zRun._save.<locals>.<listcomp>)parentsexist_okr#  c                   s   h | ]\}} t | qS rf   )r  r  )r  g_pol
files_rootrf   rg   	<setcomp>  s    zRun._save.<locals>.<setcomp>c                 S  s   g | ]}t |qS rf   )rZ   r  rf   rf   rg   r        )!r)   relative_tor$   rZ   rG   r  r  r  r  r  r   r  r   globsortedr%   partsr  r  
contextlibsuppressOSErrorr  samefileappendr  mkdirr(   r'   emit_warningsr2  r   r  )r   r  r  r  relative_globrelative_glob_strr  preexisting	src_pathsstatspublish_entriescreated_targetssrcreldsteffective_policyr  
files_dictabs_targetsrf   r  rg   r  a  s^   



 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  rf   rf   rg   r    s   	

zRun.restore	exit_coder   c                 C  s(   |durt jtddd| d | |S )aY  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`).
        - Killed: Run was forcibly stopped before it could finish.

        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=...)`.
        NT)run__finish_quietzpThe `quiet` argument to `wandb.run.finish()` is deprecated, use `wandb.Settings(quiet=...)` to set this instead.r  r!  r  )r=   r  r!   _finish)r   r  r   rf   rf   rg   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   d S tj| u rt  t   w )Nzfinishing run r  Tr  )r   )r  r4  rL  rM  r  rG   r  r  r  r1  r   r|   r~   r   remove_active_run_atexit_cleanupr   r   r   assert_serviceinform_finishrz   r  rB   unset_globalsr   end_session)r   r  r  hookservicerf   rf   rg   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(  )r2  r   r$  deliver_request_run_statusr   r   run_status_responser(  secondsr   fromtimestampnanosr&  r'  )r   handle_run_statusr   	sync_datar(  rf   rf   rg   status	  s   z
Run.statusvisualize_key
panel_typepanel_configrn  c                 C  s"   ||d}| j |dd|fd d S )N)r)  r*  rX  	visualizer  r{  )r   r(  r)  r*  rS  rf   rf   rg   
_add_panel1	  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>   rF   wrap_emuwbrF   zRedirecting console.stdoutc                        d| S Nr4  r  rP  r   rf   rg   r   Z	  r   zRun._redirect.<locals>.<lambda>online)r  cbsflush_periodicallystderrc                   r5  Nr<  r7  r8  r   rf   rg   r   b	  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.r0  )r/  )r5  	uninstallr6  rz   r   	_redirect)r   r   rf   rg   wrap_fallbacki	  s   


z$Run._redirect.<locals>.wrap_fallback
tensorflowr2  zWrapping output streams.c                   r5  r6  r7  r8  r   rf   rg   r   |	  r   c                   r5  r=  r7  r8  r   rf   rg   r   	  r   c                   r5  r6  r  r8  r   rf   rg   r   	  r   )r  r:  c                   r5  r=  rC  r8  r   rf   rg   r   	  r   offzunhandled consolezRedirects installed.zFailed to redirect: zFailed to redirect.r   )r   r/  rL  rM  r  r  r   r  r>   OUTPUT_FNAMEr9  r?   CRDedupedFiler  rF   Redirectwritemoder   r3   StreamWrapperStreamRawWrapperr  installr5  r6  r  rz   r   	exception)	r   r-  r.  r/  output_log_path	out_redir	err_redirrA  r  rf   r   rg   r@  :	  s   















zRun._redirectc                 C  s8   t d | jr| j  | jr| j  t d d S )Nr  zrestore done)rL  rM  r5  r?  r6  r   rf   rf   rg   _restore	  s   


zRun._restorec                 C  s   | j d u rtd d S | jrd S d| _|p| jr| jjpd}|| _td|  |dkr=tj	
| jjr=t| jj z|   W n' tyU   tj sTtd   t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   rC   )r2  rL  r   r:  r;  r  r=  rM  r  r  r  r   resume_fnameremove
_on_finishKeyboardInterruptrz   wandb_agent_is_running	termerrorr  _console_stoprM  r  _footerr@  rB  rE  rG  rQ  )r   r  rf   rf   rg   r  	  s>   






zRun._atexit_cleanupc                 C  s&   t d t | _| | j| j d S )Nz
atexit reg)rL  rM  rH   r;  r@  rH  rI  r   rf   rf   rg   _console_start	  s   
zRun._console_startc                 C  s&   |    | jr| j  d | _d S d S r   )rQ  r9  closer   rf   rf   rg   r]  	  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_requirementsr2  r   
wandb.utilrb  rL  debugpublish_python_packagesr  r   r   r>  r   r_  	_on_ready)r   rb  rf   rf   rg   	_on_start	  s0   
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)rG   r  r  attachrL  rj  )r   r  rf   rf   rg   
_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  rB   r   r   r   c              	   S  sz   t j| d-}zt|dd }|d urt|j|d W n ty*   Y W d    d S w W d    d S 1 s6w   Y  d S )Nr  rb   T)rG   r  r  r   imports_finishAttributeError)r  rB   r  r   rf   rf   rg   _telemetry_import_hook
  s   "zDRun._register_telemetry_import_hooks.<locals>._telemetry_import_hook)r  r  rB   r   r   r   )rG   list_telemetry_importsr  partialr   r   r*   )r   rp  import_telemetry_setimport_hook_fnmodule_namerf   rf   rg    _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)r4  add_active_runrv  r,  r  _detect_and_apply_job_inputsr  rL  rM  r  r   resumer  r  r  rV  rW  r   rf   rf   rg   rj  '
  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.internalrz  apply)r   rz  rf   rf   rg   rx  =
  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   ra  c                 s  s"    | ]}|j  d |j V  qdS )z==N)r  r<  )r  drf   rf   rg   r  F
  s     z,Run._make_job_source_reqs.<locals>.<genexpr>)
rg  rb  r  r9   type_ofrS  as_dictto_jsonrR  _as_dict)r   rb  installed_packages_listrs   rt   rf   rf   rg   _make_job_source_reqsC
  s
   
zRun._make_job_source_reqssource_dictrn   r  
patch_pathos.PathLike | Nonec           	      C  s   ddl m} ddlm} |||j}|r"tj|r"|t	|d |
d}|d| W d    n1 s:w   Y  |
d}|t| W d    |S 1 sXw   Y  |S )Nr   r  )job_builderz
diff.patchzrequirements.frozen.txt
zwandb-job.json)r  r  wandb.sdk.internalr  JOB_ARTIFACT_TYPEr  r  r  r  r,   new_filerH  r   r  dumps)	r   r   r  r  r  r  r  job_artifactfrf   rf   rg   _construct_job_artifactL
  s   
zRun._construct_job_artifactrs   rt   docker_image_namer`   list[str] | Nonec           
      C  sj   |pt d}|sd S tjd| }|d ur|n| jj}dd||d||| jjd}| |||}	|	S )NWANDB_DOCKERzjob-v0rl   )rl   r`   )ro   rp   rq   rs   rt   rv   )	r  getenvrz   r  r  r   _args_pythonr  )
r   rs   rt   r  r  r`   r   s_argssource_infor  rf   rf   rg   _create_image_job`
  s    zRun._create_image_jobc                 C  sL   |   \}}}| j|||||d}|sJ | |}|s$td| |S )N)r`   r  zJob Artifact log unsuccessful: )r  r  log_artifactrz   Error)r   r  r`   packagesin_types	out_typesr  ri   rf   rf   rg   _log_job_artifact_with_image}
  s   
z Run._log_job_artifact_with_imagec              	   C  sr  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 ttj|| jjd W d    n1 sQw   Y  | jj }|jd d}|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_text)r   display_progressr   )%r   r   r>  r   r]  r2  r   r   x_update_finish_statedeliver_exitr=  deliver_finish_without_exitrD   progress_printerrQ  rL   r  rr  loop_printing_operation_statsdeliver_poll_exitr   r   rU  rE  r   r   rG  r  deliver_request_sampled_historysampled_history_responser@  r  rB  cleanupr   r   "_unregister_telemetry_import_hooks)r   exit_handler  poll_exit_handler   internal_messages_handlefinal_summary_handlesampled_history_handlerf   rf   rg   rX  
  sV   









zRun._on_finishr   c                 C  s    t  }|D ]}t||  qd S r   )rG   rq  r+   )r   rs  ru  rf   rf   rg   r  
  s   z&Run._unregister_telemetry_import_hooksstep_metric str | wandb_metric.Metric | None	step_syncgoal	overwritewandb_metric.Metricc              	   C  sb   |rd|v rt jtddd| d |rd|v s|dur&t jtddd	| d | |||||||S )
an  Customize metrics logged with `wandb.Run.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
                `wandb.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",
                "first", "best", "copy" and "none". "none" prevents a summary
                from being generated. "best" is used together with the goal
                parameter, "best" is deprecated and should not be used, use
                "min" or "max" instead. "copy" is deprecated and should not be
                used.
            goal: Specify how to interpret the "best" summary type.
                Supported options are "minimize" and "maximize". "goal" is
                deprecated and should not be used, use "min" or "max" instead.
            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  T)run__define_metric_copyz@define_metric(summary='copy') is deprecated and will be removed.r  bestN)run__define_metric_best_goalzdefine_metric(summary='best', goal=...) is deprecated and will be removed. Use define_metric(summary='min') or define_metric(summary='max') instead.)r=   r  r!   _define_metric)r   r   r  r  rU  rR  r  r  rf   rf   rg   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  rU  rR  r  r  zUnhandled define_metric() arg: z type: *r  z:Unhandled define_metric() arg: name (glob suffixes only): c                 S  s   g | ]}|  qS rf   )lower)r  srf   rf   rg   r  :  r  z&Run._define_metric.<locals>.<listcomp>,>   r   minr  r  lastmeannonefirstz+Unhandled define_metric() arg: summary op: r  T   r  r   z%Unhandled define_metric() arg: goal: )r   r  r  rR  rU  r  r  )rz   r  rO  r7   Metricr   rZ   r+  rw  rb   endswithr  r  rG   r  r  metric_summaryr  metric_goalmetric_hiddenmetric_step_syncmetricrh  r  _commit)r   r   r  r  rU  rR  r  r  arg_namearg_valexp_typearg_typestrippedsummary_opssummary_itemsvalidir  goal_cleaned
valid_goalrF  rf   rf   rg   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  Hook into given PyTorch model to monitor gradients and the model's computational graph.

        This function can track parameters, gradients, or both during training.

        Args:
            models: A single model or a sequence of models to be monitored.
            criterion: The loss function being optimized (optional).
            log: Specifies whether to log "gradients", "parameters", or "all".
                Set to None to disable logging. (default="gradients").
            log_freq: Frequency (in batches) to log gradients and parameters. (default=1000)
            idx: Index used when tracking multiple models with `wandb.watch`. (default=None)
            log_graph: 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  rf   rf   rg   watchd  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: Optional list of pytorch models that have had watch called on them.
        )r  N)rz   r  _unwatch)r   r  rf   rf   rg   unwatch  s   
zRun.unwatchri   target_pathaliasesc                 C  sf   ddl m} | r| s| |}| jjrt||}|	 s+|j
| j| jd}|| |S )u  Link the artifact to a collection.

        The term “link” refers to pointers that connect where W&B stores the
        artifact and where the artifact is accessible in the registry. W&B
        does not duplicate artifacts when you link an artifact to a collection.

        View linked artifacts in the Registry UI for the specified collection.

        Args:
            artifact: The artifact object to link to the collection.
            target_path: The path of the collection. Path consists of the prefix
                "wandb-registry-" along with the registry name and the
                collection name `wandb-registry-{REGISTRY_NAME}/{COLLECTION_NAME}`.
            aliases: Add one or more aliases to the linked artifact. The
                "latest" alias is automatically applied to the most recent artifact
                you link.

        Returns:
            The linked artifact.

        r5   )ArtifactPath)ra  r  )artifacts._validatorsr  is_draft_is_draft_save_startedr  r   r  NotImplementedErrorfrom_stris_registry_pathwith_defaultsr  r  linkto_str)r   ri   r  r  r  r   rf   rf   rg   link_artifact  s   

zRun.link_artifactartifact_or_namestr | Artifactrw  use_asc                 C  s  ddl m} ddlm} | jjrtd|j| jj| jj	dd}|
| jj |dur6tjtdd	d
d t|trr|}|  }	|	j||d}
|dur`||
jkr`td| d|
j d|
j |j|
j| jj| jj	|
j|
j	d nJ|}
|du r{g }nt|tr|g}t||r|
 r|durtd | j|
|ddd |
  nt|
|r|
 s|j|
j|
j|
j	d ntd| jr| jjr| jj|
 |
S )a(  Declare an artifact as an input to a run.

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

        Args:
            artifact_or_name: The name of the artifact to use. May be prefixed
                with the name of the project the artifact was logged to
                ("entity" 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
            type: The type of artifact to use.
            aliases: Aliases to apply to this artifact
            use_as: This argument is deprecated and does nothing.

        Returns:
            An `Artifact` object.

        Examples:
        ```python
        import wandb

        run = wandb.init(project="<example>")

        # Use an artifact by name and alias
        artifact_a = run.use_artifact(artifact_or_name="<name>:<alias>")

        # Use an artifact by name and version
        artifact_b = run.use_artifact(artifact_or_name="<name>:v<version>")

        # Use an artifact by entity/project/name:alias
        artifact_c = run.use_artifact(
            artifact_or_name="<entity>/<project>/<name>:<alias>"
        )

        # Use an artifact by entity/project/name:version
        artifact_d = run.use_artifact(
            artifact_or_name="<entity>/<project>/<name>:v<version>"
        )

        # Explicitly finish the run since a context manager is not used.
        run.finish()
        ```

        r   )internalrT   z)Cannot use artifact when in offline mode.)r  r  )default_settingsNT)run__use_artifact_use_aszW`use_as` argument is deprecated and does not affect the behaviour of `run.use_artifact`r  )rw  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 artifact)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`) ro  r  rp  rU   r   r  r  rP   r  r  set_current_run_idr   r=   r  r!   rO  rZ   rq  rv  rw  r  r   rt  r   r  rz   r   r  r   r2  r   publish_use_artifact)r   r  rw  r  r  r  rU   apir   rx  ri   rf   rf   rg   rt    sv   8


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   rw  r  r[  r  )r   r  r   rw  r  r[  rf   rf   rg   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: A path to the contents of this artifact,
                can be in the following forms:
            - `/local/directory`
            - `/local/directory/file.txt`
            - `s3://bucket/path`
            name: An artifact name. May be prefixed with "entity/project". Defaults
                to the basename of the path prepended with the current run ID
                if not specified. Valid names can be in the following forms:
            - name:version
            - name:alias
            - digest
            type: The type of artifact to log. Common examples include `dataset`, `model`.
            aliases: Aliases to apply to this artifact, defaults to `["latest"]`.
            distributed_id: 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   rw  r  r
  finalizer   r  r  r  r   r  r   rw  r  r
  rf   rf   rg   upsert_artifactk  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: 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: 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: The type of artifact to log, examples include `dataset`, `model`
            aliases: Aliases to apply to this artifact,
                defaults to `["latest"]`
            distributed_id: 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  rf   rf   rg   finish_artifact  s   'zRun.finish_artifactr  r  r  c
              
   C  s  ddl m}
m} |s|d u rtd|d ur|
|}|d ur"||}| ||||\}}i |j|_||_| | | jrp| jj	rp| j
js`| jj	j| |||| j|||	d}|||  j |S | jj	j| ||||||	d |S | jr| jj| ||||||	d |S )Nr5   )validate_aliasesvalidate_tagsz7Must provide distributed_id if artifact is not finalize)r  r  r  )r  r  r  r  _prepare_artifactmetadatar
  _assert_can_log_artifactr2  r   r   r  deliver_artifactr  _set_save_handlerq  rs  publish_artifactr3  )r   r  r   rw  r  r[  r
  r  r  r  r  r  ri   r   rf   rf   rg   r    s`   

	zRun._log_artifactr  dict[str, str] | None	PublicApic                 C  sv   | j d ur| j S ddlm} d| jji}| jjs.| jjpd|d< | jjp%d|d< | jj|d< |j	|| jj
d| _ | j S )	Nr   rl  r  r  r  r  rn  )api_key)ry  ro  rm  r   r   r  r  r  rn  rP   r  )r   r  rm  rf   rf   rg   rq    s   
zRun._public_apic                 C  s  dd l }ddlm} | jjrd S z|  }|jd }|jd }||||j|j	}W n |j
jy6   Y d S w |d urP|j|krPtd|j d| d|j d|rj|jrj||jkrjtd|j d	|j d
| d|r|jr||jkrtd|j d|j d
| dd S d S d S )Nr   rT   r  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 ')requestsrp  rU   r   r  rq  r   _expected_typer   rs  
exceptionsRequestExceptionrw  r  _source_entity_source_project)r   ri   r  rU   rx  r  r  expected_typerf   rf   rg   r  )  sJ   



zRun._assert_can_log_artifacttuple[Artifact, list[str]]c                 C  s   ddl m} t|ttjfrS|pd| jj dtj	| }|||p#d}tj
|r3|t| n"tj|rA|t| ndt|v rO|t| ntd|}t||s^td|  |t|fS )	Nr   rT   z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)rp  rU   rO  rZ   r  PathLiker   r   r  basenameisfiler  isdiradd_diradd_referencer  r  r  r2   )r   r  r   rw  r  rU   ri   rf   rf   rg   r  L  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.

        The name of model artifact can only contain alphanumeric characters,
        underscores, and hyphens.

        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: A name to assign to the model artifact that
                the file contents will be added to. This will default to the
                basename of the path prepended with the current run id if
                not specified.
            aliases: Aliases to apply to the created model artifact,
                    defaults to `["latest"]`

        Raises:
            ValueError: If name has invalid special characters.

        Returns:
            None
        model)r  r   rw  r  Nr  )r   r  r   r  rf   rf   rg   	log_modelq  s   !
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: 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

        Returns:
            path (str): Path to downloaded model artifact file(s).

        Raises:
            AssertionError: If model artifact 'name' is of a type that does
                not contain the substring 'model'.
        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  rt  rZ   rw  r  AssertionErrordownloadr  listdirr  r,   r  r   )r   r   ri   r  dir_listrf   rf   rg   	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.

        Linked model versions are visible in the UI for the specified registered model.

        This method will:
        - 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: 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: 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: Aliases 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.

        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   rw  )ri   r  r  )r  r  r/  r  rq  rv  rZ   rw  r  r  r  r   r  )
r   r  r4  r   r  
name_partsr  r  rx  ri   rf   rf   rg   
link_model  s2   
2

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tfr0t|d}ntt	|dds<t
d	t| d
 }| jrW| jjrY| jj|||| dS dS dS )a  Create an alert with the given title and text.

        Args:
            title: The title of the alert, must be less than 64 characters long.
            text: The text body of the alert.
            level: The alert level to use, either: `INFO`, `WARN`, or `ERROR`.
            wait_duration: The time to wait (in seconds) before sending another
                alert with this title.
        c                 S  s   h | ]}|j qS rf   )r  )r  levrf   rf   rg   r  $  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  )rM   INFOrO  r  r  r   r   r  callabler  r  r?  r2  r   publish_alert)r   r7  r8  r9  r;  	level_strrf   rf   rg   alert  s   
z	Run.alertc                 C  r  r   rf   r   rf   rf   rg   	__enter__3  r  zRun.__enter__exc_typetype[BaseException] | Noneexc_valBaseException | Noneexc_tbTracebackType | Nonec                 C  s8   |d u}|rt ||| |rdnd}| j|d | S )Nr5   r   r  )	tracebackprint_exceptionr  )r   rF  rH  rJ  exception_raisedr  rf   rf   rg   __exit__6  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)r2  r   publish_preemptingr   rf   rf   rg   mark_preemptingC  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   rR  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  )rT  resr  recordsmeasurementsrY  dtrf   rf   rg   
pb_to_dictZ  s   


z'Run._system_metrics.<locals>.pb_to_dictr5   r   zError getting system metrics.N)rT  rU  r   rR  )wandb.protorS  r2  r   deliver_get_system_metricsr   r   r   get_system_metrics_responser  rL  rM  )r   rS  r`  r   r   r   rf   rf   rg   _system_metricsN  s"   


zRun._system_metricsc                 C  s   |    |   |   d S r   )_header_wandb_version_info_header_sync_info_header_run_infor   rf   rf   rg   rc    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   rQ  rV  rz   __version__r   rf   rf   rg   re    s   zRun._header_wandb_version_infoc                 C  s   d| j | jj }| jjr1d| j d d| j d d| j d d}| j ||g d S |g}| j jsGd	| j d
 d}|| | jj	sW| jj
sY| j | d S d S d S )NzRun data is saved locally in z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 z`wandb offline`z to turn off syncing.)rQ  r#  r   sync_dirr  r	  rV  supports_htmlr  r   r   )r   sync_location_msgoffline_warningr   disable_sync_msgrf   rf   rg   rf    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||  d S )NzResuming runzSyncing runr   z<strong>z	</strong>)r  r  zdeveloper-guidedocszWeights & Biaseszto z ()zSweep page: ri  starz View project at broomz View sweep at rocketz View run at )r   rQ  r  r   r,  r  r'  r  resume_fromr  rj  wandb.jupyterjupyterdisplay_if_magic_is_usedr  r   r   r*  rV  r   emoji)r   r   rC   r,  r  r'  run_state_strr  rz   run_lineproject_line
sweep_linedoc_htmlproject_htmlrf   rf   rg   rg    sV   zRun._header_run_inforS  rT  rU  r   rC   c                C  sD   t j| |||d t j|||d t j||d t j|||d d S )N)historyrR  r   rC   )rU  r   rC   )r   rC   )r   r   rC   )r  _footer_history_summary_info_footer_sync_info_footer_log_dir_info_footer_internal_messagesrR  rf   rf   rg   r^    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 rr  z
 View run z at: rp  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   rV  r	  ri  r  r,  r  rw  r   r  r  file_countsrL  rM  wandb_countmedia_countartifact_countother_count)rU  r   rC   rM  r  rf   rf   rg   r    s<   (

zRun._footer_sync_infoc                 C  sV   | j s| jrd S | jp| j}|r)tj|t d}|	d|
|  d S d S )Nr   zFind logs at: )r   r   log_userlog_internalr  r  dirnamer  getcwdrV  r#  )r   rC   log_dirrf   rf   rg   r  $  s   zRun._footer_log_dir_infor~  c                C  sp   |j s|jrd S g }| rt| || }r|| |r*t||| }r*|| |r6||| d S d S r   )r   r   r  _footer_historyr  _footer_summaryrV  panel)r~  rR  r   rC   r  history_gridsummary_gridrf   rf   rg   r  4  s   

z Run._footer_history_summary_inforS   c           	      C  s   t dd | jD dd d}g }|D ]%}t||jkr ntj|jp%|jd}|	| }r7|
|j|g q|s<dS t|t|k rWt|t| }|
d|d	d
g ||dS )z>Returns the run history formatted for printing to the console.c                 s  s     | ]}|j d s|V  qdS r"  N)r  r  r  r  rf   rf   rg   r  V  s    z&Run._footer_history.<locals>.<genexpr>c                 S  r  r   r  r  rf   rf   rg   r   W      z%Run._footer_history.<locals>.<lambda>r  (   N+,d...zRun history:)r  r  r  max_end_of_run_history_metricsrz   r  
downsamplevalues_float
values_int
sparklinesr  r  grid)	r~  rC   r   sorted_history_itemshistory_rowsr  values	sparkline	remainingrf   rf   rg   r  N  s*   
zRun._footer_historyrQ   c           	   	   C  sN  t dd | jD dd d}g }d}|D ]i}t||jkr n_zt|j}W n tjy?   t	d|j
d |d	7 }Y qw t|tr\|d
d dt|dk  }||j
|g qt|tjryt|trlt|dn|}||j
t|g q|d	7 }q|sd
S t|t|| k rt|t| | }|d|ddg ||dS )z>Returns the run summary formatted for printing to the console.c                 s  s&    | ]}|j d s|js|V  qdS r  )r  r  
nested_keyr  rf   rf   rg   r  x  s    

z&Run._footer_summary.<locals>.<genexpr>c                 S  r  r   r  r  rf   rf   rg   r   }  r  z%Run._footer_summary.<locals>.<lambda>r  r   zError decoding summary[]r5   N   r  r   r  r  zRun summary:)r  r  r  max_end_of_run_summary_metricsr  r  r  JSONDecodeErrorrL  rM  r  rO  rZ   r  numbersNumberr  roundr  )	rR  rC   r   sorted_summary_itemssummary_rowsskippedr  r  r  rf   rf   rg   r  p  s>   	

zRun._footer_summaryc                C  s8   |j s|jrd S | sd S | jjD ]	}|j|dd qd S )Nwarn)r9  )r   r   r   r   rV  )r   r   rC   r!  rf   rf   rg   r    s   zRun._footer_internal_messages)NNN)
r   rX   rS  rN  rT  rN  rU  rN  r   r   r   )r  rr   r   r   )r  r)  r   r   )r  rZ   r  r  r   r   )r  r  r   r  )r   r   )r  r   r   r   )r   r  )r   rX   )r   rZ   )r   r  )r   r  )r   ru   )r   rZ   r   r   )r  rZ   r   r   )r   r  )r[  r   r   r   )r   r  )r   r   )r   r+  )
r  ru   r   ru   r  r  r  r  r   r  )r	  ru   r-  ru   r.  ru   r   r   )
r	  ru   r-  ru   r.  ru   r  rZ   r   r   )r9  r]   r   r   )rJ  r   r   r   )rS  F)rT  r   rU  r+  r   r+  )rT  r   rU  r+  r   rZ   NN)rb  rc  rd  rc  r   rw   )r  rf  rg  rc  rP  rh  r   r   )r  rZ   rg  rk  r   rU   )r  rZ   rg  r   r   r   )r}  r;   r   r   )r   rr   )r  r   r   r   )r$  rZ   r   r   r   )rP  rr   r  ru   r   rr   )rP  rr   r   rr   )rP  rr   r  r<  r\   r  r   r   )r   rZ   rP  rZ   r   r   )Tr  )r  rZ   r  r+  r  rZ   r   r   )r  rN   r   r   )r  rV   r   r   )r   rW   r   r   )r  r0  r   r   )r  r    r   r   )r  rZ   r  rZ   r  r  r   r   )Nr  )r  r  r  r  r  r&   r   r  )r  r  r  r  r  r&   r   r]   NFN
r   rZ   r  ru   r  r+  r  ru   r   r  r  r<  r   r  r   r   )r  r<  r   r   )r   r$  )r(  rZ   r)  rZ   r*  rn  r   r   )r-  r<  r.  r<  r/  ru   r   r   )r   r}  )
r   rZ   r  rn   r  r]   r  r  r   rU   )rs   rr   rt   rr   r  r]   r  ru   r`   r  r   r  )r  rZ   r`   r  r   rU   )r   rZ   r   r   )NNNNNN)r   rZ   r  r  r  r  rU  r  rR  ru   r  ru   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   )ri   rU   r  rZ   r  r  r   rU   )
r  r  rw  ru   r  r  r  ru   r   rU   )NNNN)r  r  r   ru   rw  ru   r  r  r[  r  r   rU   )r  r	  r   ru   rw  ru   r  r  r
  ru   r   rU   )NNNNNTFF)r  r  r   ru   rw  ru   r  r  r[  r  r
  ru   r  r+  r  r+  r  r+  r   rU   )r  r  r   r  )
r  r  r   ru   rw  ru   r  r  r   r$  )r  r-   r   ru   r  r  r   r   )r   rZ   r   r,   )
r  r-   r4  rZ   r   ru   r  r  r   r  )
r7  rZ   r8  rZ   r9  r:  r;  r<  r   r   )r   r  )rF  rG  rH  rI  rJ  rK  r   r+  )r   rR  )rS  r?  rT  rA  rU  rD  r   rF  r   rX   rC   rP  r   r   )rU  rD  r   rX   rC   rP  r   r   )r   rX   rC   rP  r   r   )
r~  r?  rR  rA  r   rX   rC   rP  r   r   )r~  rS   rC   rP  r   rX   r   ru   )rR  rQ   rC   rP  r   rX   r   ru   )r   rF  r   rX   rC   rP  r   r   )rb   rc   rd   r   re   r   rW  r  r  r  r  r  r  r  r  r  propertyr  r  r  r   r  rS  r  r   setterr#  r  r[  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r1   r>   exclude_wandb_fnr%  r(  r'  r+  r*  r  r4  r8  rA  rI  rR  rV  r\  re  ri  rk  r|  rr  rp  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@  rQ  r  r_  r]  rk  rm  rv  rj  rx  r  r  r  r  rX  r   r  r  r  r  r  r  rt  r  r  r  r  rq  r  r  r-  r3  r6  rD  rE  rO  rQ  rd  rc  re  rf  rg  r^  r  r  r  r  r  r  __classcell__rf   rf   r  rg   r    s`  
 +v	
f

	
*#= &  fU!.m	+<CN
0{(07C&%"%N!0<%!.r  r   r  ru   r  r+  r  r  c                 C  s  ddl m} 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 r1|dur1|j}| }||}|du rBt	
 }t	j|| }	t	j|	rW|du rWt|	S |r[dS || g}
t|
dkridS |
d jdkr}td|  d|px| d	|
d j|d
dS )a`  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:
        CommError: If W&B can't connect to the W&B backend.
        ValueError: If the file is not found or can't find run_path.
    r   rl  Nz>run_path required when calling wandb.restore before wandb.initF0zFile z not found in r   T)r  r  )ro  rm  rz   r  r  r  r  r  rP   r  r  r   r  r  r#  r  md5r0  )r   r  r  r  rm  is_disabledr  r  api_runr  r#  rf   rf   rg   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  rf   rf   rg   r    s   r  )r  r  r   r  r  r  r  r  )
__future__r   r  r  r  r  loggingr  r  r  rerC  r   r   rL  collections.abcr   r   dataclassesr   r   r   r   r	   enumr
   typesr   typingr   r   r   r   typing_extensionsr   r   r   r   r   rz   	wandb.envrg  r   wandb.analyticsr   wandb.errorsr   r   wandb.errors.linksr   wandb.integration.torchr   
wandb.plotr   r   wandb.proto.wandb_internal_pb2r   r   r   r    wandb.proto.wandb_telemetry_pb2r!   wandb.sdk.libr"   wandb.sdk.lib.filesystemr#   r$   r%   r&   r'   r(   r)   wandb.sdk.lib.import_hooksr*   r+   wandb.sdk.lib.pathsr,   r-   r.   r/   r0   r1   r2   r3   r4   r  r6   r7   r8   data_types._dtypesr9   interface.interfacer:   interface.summary_recordr;   libr<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   lib.exit_hooksrH   mailboxrI   rJ   rK   rL   wandb_alertsrM   wandb_setuprN   rO   torchwandb.apis.publicrP   r  rQ   rR   rS   artifacts.artifactrU   backend.backendrV   interface.interface_queuerW   wandb_settingsrX   rY   rh   rk   rn   	getLoggerrL  EXIT_TIMEOUTcompiler/  r|   r   r   r   r   r  r  re   r  r#  r$  r  r  r   ro  r  rf   rf   rf   rg   <module>   s    $	$
8


 \


*                           q: