id
int64
1
6.07M
name
stringlengths
1
295
code
stringlengths
12
426k
language
stringclasses
1 value
source_file
stringlengths
5
202
start_line
int64
1
158k
end_line
int64
1
158k
repo
dict
2,801
_console_callback
def _console_callback(self, name: str, data: str) -> None: # logger.info("console callback: %s, %s", name, data) if self._backend and self._backend.interface: self._backend.interface.publish_output(name, data)
python
wandb/sdk/wandb_run.py
1,409
1,412
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,802
_console_raw_callback
def _console_raw_callback(self, name: str, data: str) -> None: # logger.info("console callback: %s, %s", name, data) # NOTE: console output is only allowed on the process which installed the callback # this will prevent potential corruption in the socket to the service. Other methods # are protected by the _attach run decorator, but this callback was installed on the # write function of stdout and stderr streams. console_pid = getattr(self, "_attach_pid", 0) if console_pid != os.getpid(): return if self._backend and self._backend.interface: self._backend.interface.publish_output_raw(name, data)
python
wandb/sdk/wandb_run.py
1,415
1,427
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,803
_tensorboard_callback
def _tensorboard_callback( self, logdir: str, save: bool = True, root_logdir: str = "" ) -> None: logger.info("tensorboard callback: %s, %s", logdir, save) if self._backend and self._backend.interface: self._backend.interface.publish_tbdata(logdir, save, root_logdir)
python
wandb/sdk/wandb_run.py
1,429
1,434
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,804
_set_library
def _set_library(self, library: _WandbSetup) -> None: self._wl = library
python
wandb/sdk/wandb_run.py
1,436
1,437
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,805
_set_backend
def _set_backend(self, backend: "wandb.sdk.backend.backend.Backend") -> None: self._backend = backend
python
wandb/sdk/wandb_run.py
1,439
1,440
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,806
_set_internal_run_interface
def _set_internal_run_interface( self, interface: Union[ "wandb.sdk.interface.interface_queue.InterfaceQueue", "wandb.sdk.interface.interface_grpc.InterfaceGrpc", ], ) -> None: self._internal_run_interface = interface
python
wandb/sdk/wandb_run.py
1,442
1,449
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,807
_set_reporter
def _set_reporter(self, reporter: Reporter) -> None: self._reporter = reporter
python
wandb/sdk/wandb_run.py
1,451
1,452
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,808
_set_teardown_hooks
def _set_teardown_hooks(self, hooks: List[TeardownHook]) -> None: self._teardown_hooks = hooks
python
wandb/sdk/wandb_run.py
1,454
1,455
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,809
_set_run_obj
def _set_run_obj(self, run_obj: RunRecord) -> None: self._run_obj = run_obj self._entity = run_obj.entity self._project = run_obj.project # Grab the config from resuming if run_obj.config: c_dict = config_util.dict_no_value_from_proto_list(run_obj.config.update) # TODO: Windows throws a wild error when this is set... if "_wandb" in c_dict: del c_dict["_wandb"] # We update the config object here without triggering the callback self._config._update(c_dict, allow_val_change=True, ignore_locked=True) # Update the summary, this will trigger an un-needed graphql request :( if run_obj.summary: summary_dict = {} for orig in run_obj.summary.update: summary_dict[orig.key] = json.loads(orig.value_json) self.summary.update(summary_dict) self._step = self._get_starting_step() # update settings from run_obj self._settings._apply_run_start(message_to_dict(self._run_obj)) self._update_settings(self._settings) wandb._sentry.configure_scope( process_context="user", settings=self._settings, )
python
wandb/sdk/wandb_run.py
1,457
1,485
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,810
_set_run_obj_offline
def _set_run_obj_offline(self, run_obj: RunRecord) -> None: self._run_obj_offline = run_obj
python
wandb/sdk/wandb_run.py
1,487
1,488
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,811
_add_singleton
def _add_singleton( self, data_type: str, key: str, value: Dict[Union[int, str], str] ) -> None: """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. """ value_extra = {"type": data_type, "key": key, "value": value} if data_type not in self._config["_wandb"]: self._config["_wandb"][data_type] = {} if data_type in self._config["_wandb"][data_type]: old_value = self._config["_wandb"][data_type][key] else: old_value = None if value_extra != old_value: self._config["_wandb"][data_type][key] = value_extra self._config.persist()
python
wandb/sdk/wandb_run.py
1,490
1,517
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,812
_log
def _log( self, data: Dict[str, Any], step: Optional[int] = None, commit: Optional[bool] = None, ) -> None: if not isinstance(data, Mapping): raise ValueError("wandb.log must be passed a dictionary") if any(not isinstance(key, str) for key in data.keys()): raise ValueError("Key values passed to `wandb.log` must be strings.") self._partial_history_callback(data, step, commit) if step is not None: if os.getpid() != self._init_pid or self._is_attached: wandb.termwarn( "Note that setting step in multiprocessing can result in data loss. " "Please log your step values as a metric such as 'global_step'", repeat=False, ) # if step is passed in when tensorboard_sync is used we honor the step passed # to make decisions about how to close out the history record, but will strip # this history later on in publish_history() if len(wandb.patched["tensorboard"]) > 0: wandb.termwarn( "Step cannot be set when using syncing with tensorboard. " "Please log your step values as a metric such as 'global_step'", repeat=False, ) if step > self._step: self._step = step if (step is None and commit is None) or commit: self._step += 1
python
wandb/sdk/wandb_run.py
1,519
1,553
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,813
log
def log( self, data: Dict[str, Any], step: Optional[int] = None, commit: Optional[bool] = None, sync: Optional[bool] = None, ) -> None: """Log a dictonary of data to the current run's history. Use `wandb.log` to log data from runs, such as scalars, images, video, histograms, plots, and tables. See our [guides to logging](https://docs.wandb.ai/guides/track/log) for live examples, code snippets, best practices, and more. The most basic usage is `wandb.log({"train-loss": 0.5, "accuracy": 0.9})`. This will save the loss and accuracy to the run's history and update the summary values for these metrics. Visualize logged data in the workspace at [wandb.ai](https://wandb.ai), or locally on a [self-hosted instance](https://docs.wandb.ai/guides/hosting) of the W&B app, or export data to visualize and explore locally, e.g. in Jupyter notebooks, with [our API](https://docs.wandb.ai/guides/track/public-api-guide). In the UI, summary values show up in the run table to compare single values across runs. Summary values can also be set directly with `wandb.run.summary["key"] = value`. Logged values don't have to be scalars. Logging any wandb object is supported. For example `wandb.log({"example": wandb.Image("myimage.jpg")})` will log an example image which will be displayed nicely in the W&B UI. See the [reference documentation](https://docs.wandb.com/ref/python/data-types) for all of the different supported types or check out our [guides to logging](https://docs.wandb.ai/guides/track/log) for examples, from 3D molecular structures and segmentation masks to PR curves and histograms. `wandb.Table`s can be used to logged structured data. See our [guide to logging tables](https://docs.wandb.ai/guides/data-vis/log-tables) for details. Logging nested metrics is encouraged and is supported in the W&B UI. If you log with a nested dictionary like `wandb.log({"train": {"acc": 0.9}, "val": {"acc": 0.8}})`, the metrics will be organized into `train` and `val` sections in the W&B UI. wandb keeps track of a global step, which by default increments with each call to `wandb.log`, so logging related metrics together is encouraged. If it's inconvenient to log related metrics together calling `wandb.log({"train-loss": 0.5}, commit=False)` and then `wandb.log({"accuracy": 0.9})` is equivalent to calling `wandb.log({"train-loss": 0.5, "accuracy": 0.9})`. `wandb.log` is not intended to be called more than a few times per second. If you want to log more frequently than that it's better to aggregate the data on the client side or you may get degraded performance. Arguments: data: (dict, optional) A dict of serializable python objects i.e `str`, `ints`, `floats`, `Tensors`, `dicts`, or any of the `wandb.data_types`. commit: (boolean, optional) Save the metrics dict to the wandb server and increment the step. If false `wandb.log` just updates the current metrics dict with the data argument and metrics won't be saved until `wandb.log` is called with `commit=True`. step: (integer, optional) The global step in processing. This persists any non-committed earlier steps but defaults to not committing the specified step. sync: (boolean, True) This argument is deprecated and currently doesn't change the behaviour of `wandb.log`. Examples: For more and more detailed examples, see [our guides to logging](https://docs.wandb.com/guides/track/log). ### Basic usage <!--yeadoc-test:init-and-log-basic--> ```python import wandb wandb.init() wandb.log({"accuracy": 0.9, "epoch": 5}) ``` ### Incremental logging <!--yeadoc-test:init-and-log-incremental--> ```python import wandb wandb.init() wandb.log({"loss": 0.2}, commit=False) # Somewhere else when I'm ready to report this step: wandb.log({"accuracy": 0.8}) ``` ### Histogram <!--yeadoc-test:init-and-log-histogram--> ```python import numpy as np import wandb # sample gradients at random from normal distribution gradients = np.random.randn(100, 100) wandb.init() wandb.log({"gradients": wandb.Histogram(gradients)}) ``` ### Image from numpy <!--yeadoc-test:init-and-log-image-numpy--> ```python import numpy as np import wandb wandb.init() examples = [] for i in range(3): pixels = np.random.randint(low=0, high=256, size=(100, 100, 3)) image = wandb.Image(pixels, caption=f"random field {i}") examples.append(image) wandb.log({"examples": examples}) ``` ### Image from PIL <!--yeadoc-test:init-and-log-image-pillow--> ```python import numpy as np from PIL import Image as PILImage import wandb wandb.init() examples = [] for i in range(3): pixels = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) pil_image = PILImage.fromarray(pixels, mode="RGB") image = wandb.Image(pil_image, caption=f"random field {i}") examples.append(image) wandb.log({"examples": examples}) ``` ### Video from numpy <!--yeadoc-test:init-and-log-video-numpy--> ```python import numpy as np import wandb wandb.init() # axes are (time, channel, height, width) frames = np.random.randint(low=0, high=256, size=(10, 3, 100, 100), dtype=np.uint8) wandb.log({"video": wandb.Video(frames, fps=4)}) ``` ### Matplotlib Plot <!--yeadoc-test:init-and-log-matplotlib--> ```python from matplotlib import pyplot as plt import numpy as np import wandb wandb.init() fig, ax = plt.subplots() x = np.linspace(0, 10) y = x * x ax.plot(x, y) # plot y = x^2 wandb.log({"chart": fig}) ``` ### PR Curve ```python wandb.log({"pr": wandb.plots.precision_recall(y_test, y_probas, labels)}) ``` ### 3D Object ```python wandb.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 """ if sync is not None: deprecate.deprecate( field_name=deprecate.Deprecated.run__log_sync, warning_message=( "`sync` argument is deprecated and does not affect the behaviour of `wandb.log`" ), ) self._log(data=data, step=step, commit=commit)
python
wandb/sdk/wandb_run.py
1,558
1,750
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,814
save
def save( self, glob_str: Optional[str] = None, base_path: Optional[str] = None, policy: "PolicyName" = "live", ) -> Union[bool, List[str]]: """Ensure all files matching `glob_str` are synced to wandb with the policy specified. Arguments: glob_str: (string) a relative or absolute path to a unix glob or regular path. If this isn't specified the method is a noop. base_path: (string) the base path to run the glob relative to policy: (string) on of `live`, `now`, or `end` - live: upload the file as it changes, overwriting the previous version - now: upload the file once now - end: only upload file when the run ends """ if glob_str is None: # noop for historical reasons, run.save() may be called in legacy code deprecate.deprecate( field_name=deprecate.Deprecated.run__save_no_args, warning_message=( "Calling wandb.run.save without any arguments is deprecated." "Changes to attributes are automatically persisted." ), ) return True return self._save(glob_str, base_path, policy)
python
wandb/sdk/wandb_run.py
1,754
1,782
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,815
_save
def _save( self, glob_str: Optional[str] = None, base_path: Optional[str] = None, policy: "PolicyName" = "live", ) -> Union[bool, List[str]]: if policy not in ("live", "end", "now"): raise ValueError( 'Only "live" "end" and "now" policies are currently supported.' ) if isinstance(glob_str, bytes): glob_str = glob_str.decode("utf-8") if not isinstance(glob_str, str): raise ValueError("Must call wandb.save(glob_str) with glob_str a str") if base_path is None: if os.path.isabs(glob_str): base_path = os.path.dirname(glob_str) wandb.termwarn( "Saving files without folders. If you want to preserve " "sub directories pass base_path to wandb.save, i.e. " 'wandb.save("/mnt/folder/file.h5", base_path="/mnt")', repeat=False, ) else: base_path = "." wandb_glob_str = GlobStr(os.path.relpath(glob_str, base_path)) if ".." + os.sep in wandb_glob_str: raise ValueError("globs can't walk above base_path") with telemetry.context(run=self) as tel: tel.feature.save = True if glob_str.startswith("gs://") or glob_str.startswith("s3://"): wandb.termlog( "%s is a cloud storage url, can't save file to wandb." % glob_str ) return [] files = glob.glob(os.path.join(self._settings.files_dir, wandb_glob_str)) warn = False if len(files) == 0 and "*" in wandb_glob_str: warn = True for path in glob.glob(glob_str): file_name = os.path.relpath(path, base_path) abs_path = os.path.abspath(path) wandb_path = os.path.join(self._settings.files_dir, file_name) filesystem.mkdir_exists_ok(os.path.dirname(wandb_path)) # We overwrite symlinks because namespaces can change in Tensorboard if os.path.islink(wandb_path) and abs_path != os.readlink(wandb_path): os.remove(wandb_path) os.symlink(abs_path, wandb_path) elif not os.path.exists(wandb_path): os.symlink(abs_path, wandb_path) files.append(wandb_path) if warn: file_str = "%i file" % len(files) if len(files) > 1: file_str += "s" wandb.termwarn( ( "Symlinked %s into the W&B run directory, " "call wandb.save again to sync new files." ) % file_str ) files_dict: "FilesDict" = dict(files=[(wandb_glob_str, policy)]) if self._backend and self._backend.interface: self._backend.interface.publish_files(files_dict) return files
python
wandb/sdk/wandb_run.py
1,784
1,852
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,816
restore
def restore( self, name: str, run_path: Optional[str] = None, replace: bool = False, root: Optional[str] = None, ) -> Union[None, TextIO]: return restore( name, run_path or self._get_path(), replace, root or self._settings.files_dir, )
python
wandb/sdk/wandb_run.py
1,855
1,867
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,817
finish
def finish( self, exit_code: Optional[int] = None, quiet: Optional[bool] = None ) -> None: """Mark a run as finished, and finish uploading all data. This is used when creating multiple runs in the same process. We automatically call this method when your script exits or if you use the run context manager. Arguments: exit_code: Set to something other than 0 to mark a run as failed quiet: Set to true to minimize log output """ return self._finish(exit_code, quiet)
python
wandb/sdk/wandb_run.py
1,871
1,883
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,818
_finish
def _finish( self, exit_code: Optional[int] = None, quiet: Optional[bool] = None ) -> None: if quiet is not None: self._quiet = quiet with telemetry.context(run=self) as tel: tel.feature.finish = True logger.info(f"finishing run {self._get_path()}") # detach jupyter hooks / others that needs to happen before backend shutdown for hook in self._teardown_hooks: if hook.stage == TeardownStage.EARLY: hook.call() self._atexit_cleanup(exit_code=exit_code) if self._wl and len(self._wl._global_run_stack) > 0: self._wl._global_run_stack.pop() # detach logger / others meant to be run after we've shutdown the backend for hook in self._teardown_hooks: if hook.stage == TeardownStage.LATE: hook.call() self._teardown_hooks = [] module.unset_globals() # inform manager this run is finished manager = self._wl and self._wl._get_manager() if manager: manager._inform_finish(run_id=self._run_id) self._is_finished = True # end sentry session wandb._sentry.end_session()
python
wandb/sdk/wandb_run.py
1,885
1,915
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,819
join
def join(self, exit_code: Optional[int] = None) -> None: """Deprecated alias for `finish()` - use finish instead.""" deprecate.deprecate( field_name=deprecate.Deprecated.run__join, warning_message=( "wandb.run.join() is deprecated, please use wandb.run.finish()." ), ) self._finish(exit_code=exit_code)
python
wandb/sdk/wandb_run.py
1,919
1,927
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,820
status
def status( self, ) -> RunStatus: """Get sync info from the internal backend, about the current run's sync status.""" if not self._backend or not self._backend.interface: return RunStatus() handle_run_status = self._backend.interface.deliver_request_run_status() result = handle_run_status.wait(timeout=-1) assert result sync_data = result.response.run_status_response sync_time = None if sync_data.sync_time.seconds: sync_time = datetime.fromtimestamp( sync_data.sync_time.seconds + sync_data.sync_time.nanos / 1e9 ) return RunStatus( sync_items_total=sync_data.sync_items_total, sync_items_pending=sync_data.sync_items_pending, sync_time=sync_time, )
python
wandb/sdk/wandb_run.py
1,931
1,952
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,821
plot_table
def plot_table( vega_spec_name: str, data_table: "wandb.Table", fields: Dict[str, Any], string_fields: Optional[Dict[str, Any]] = None, ) -> CustomChart: """Create a custom plot on a table. Arguments: vega_spec_name: the name of the spec for the plot data_table: a wandb.Table object containing the data to be used on the visualization fields: a dict mapping from table keys to fields that the custom visualization needs string_fields: a dict that provides values for any string constants the custom visualization needs """ return custom_chart(vega_spec_name, data_table, fields, string_fields or {})
python
wandb/sdk/wandb_run.py
1,955
1,972
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,822
_add_panel
def _add_panel( self, visualize_key: str, panel_type: str, panel_config: dict ) -> None: config = { "panel_type": panel_type, "panel_config": panel_config, } self._config_callback(val=config, key=("_wandb", "visualize", visualize_key))
python
wandb/sdk/wandb_run.py
1,974
1,981
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,823
_set_globals
def _set_globals(self) -> None: module.set_global( run=self, config=self.config, log=self.log, summary=self.summary, save=self.save, use_artifact=self.use_artifact, log_artifact=self.log_artifact, define_metric=self.define_metric, plot_table=self.plot_table, alert=self.alert, mark_preempting=self.mark_preempting, )
python
wandb/sdk/wandb_run.py
1,983
1,996
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,824
_redirect
def _redirect( self, stdout_slave_fd: Optional[int], stderr_slave_fd: Optional[int], console: Optional[SettingsConsole] = None, ) -> None: if console is None: console = self._settings._console # only use raw for service to minimize potential changes if console == SettingsConsole.WRAP: if not self._settings._disable_service: console = SettingsConsole.WRAP_RAW else: console = SettingsConsole.WRAP_EMU logger.info("redirect: %s", console) out_redir: redirect.RedirectBase err_redir: redirect.RedirectBase # raw output handles the output_log writing in the internal process if console in {SettingsConsole.REDIRECT, SettingsConsole.WRAP_EMU}: output_log_path = os.path.join( self._settings.files_dir, filenames.OUTPUT_FNAME ) # output writer might have been set up, see wrap_fallback case if not self._output_writer: self._output_writer = filesystem.CRDedupedFile( open(output_log_path, "wb") ) if console == SettingsConsole.REDIRECT: logger.info("Redirecting console.") out_redir = redirect.Redirect( src="stdout", cbs=[ lambda data: self._console_callback("stdout", data), self._output_writer.write, # type: ignore ], ) err_redir = redirect.Redirect( src="stderr", cbs=[ lambda data: self._console_callback("stderr", data), self._output_writer.write, # type: ignore ], ) if os.name == "nt": def wrap_fallback() -> None: if self._out_redir: self._out_redir.uninstall() if self._err_redir: self._err_redir.uninstall() msg = ( "Tensorflow detected. Stream redirection is not supported " "on Windows when tensorflow is imported. Falling back to " "wrapping stdout/err." ) wandb.termlog(msg) self._redirect(None, None, console=SettingsConsole.WRAP) add_import_hook("tensorflow", wrap_fallback) elif console == SettingsConsole.WRAP_EMU: logger.info("Wrapping output streams.") out_redir = redirect.StreamWrapper( src="stdout", cbs=[ lambda data: self._console_callback("stdout", data), self._output_writer.write, # type: ignore ], ) err_redir = redirect.StreamWrapper( src="stderr", cbs=[ lambda data: self._console_callback("stderr", data), self._output_writer.write, # type: ignore ], ) elif console == SettingsConsole.WRAP_RAW: logger.info("Wrapping output streams.") out_redir = redirect.StreamRawWrapper( src="stdout", cbs=[ lambda data: self._console_raw_callback("stdout", data), ], ) err_redir = redirect.StreamRawWrapper( src="stderr", cbs=[ lambda data: self._console_raw_callback("stderr", data), ], ) elif console == SettingsConsole.OFF: return else: raise ValueError("unhandled console") try: # save stdout and stderr before installing new write functions out_redir.save() err_redir.save() out_redir.install() err_redir.install() self._out_redir = out_redir self._err_redir = err_redir logger.info("Redirects installed.") except Exception as e: print(e) logger.error("Failed to redirect.", exc_info=e) return
python
wandb/sdk/wandb_run.py
1,998
2,106
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,825
wrap_fallback
def wrap_fallback() -> None: if self._out_redir: self._out_redir.uninstall() if self._err_redir: self._err_redir.uninstall() msg = ( "Tensorflow detected. Stream redirection is not supported " "on Windows when tensorflow is imported. Falling back to " "wrapping stdout/err." ) wandb.termlog(msg) self._redirect(None, None, console=SettingsConsole.WRAP)
python
wandb/sdk/wandb_run.py
2,046
2,057
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,826
_restore
def _restore(self) -> None: logger.info("restore") # TODO(jhr): drain and shutdown all threads if self._out_redir: self._out_redir.uninstall() if self._err_redir: self._err_redir.uninstall() logger.info("restore done")
python
wandb/sdk/wandb_run.py
2,108
2,115
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,827
_atexit_cleanup
def _atexit_cleanup(self, exit_code: Optional[int] = None) -> None: if self._backend is None: logger.warning("process exited without backend configured") return if self._atexit_cleanup_called: return self._atexit_cleanup_called = True exit_code = exit_code or self._hooks.exit_code if self._hooks else 0 logger.info(f"got exitcode: {exit_code}") if exit_code == 0: # Cleanup our resume file on a clean exit if os.path.exists(self._settings.resume_fname): os.remove(self._settings.resume_fname) self._exit_code = exit_code report_failure = False try: self._on_finish() except KeyboardInterrupt as ki: if wandb.wandb_agent._is_running(): raise ki wandb.termerror("Control-C detected -- Run data was not synced") if not self._settings._jupyter: os._exit(-1) except Exception as e: if not self._settings._jupyter: report_failure = True self._console_stop() self._backend.cleanup() logger.error("Problem finishing run", exc_info=e) wandb.termerror("Problem finishing run") traceback.print_exception(*sys.exc_info()) else: self._on_final() finally: if report_failure: os._exit(-1)
python
wandb/sdk/wandb_run.py
2,117
2,154
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,828
_console_start
def _console_start(self) -> None: logger.info("atexit reg") self._hooks = ExitHooks() manager = self._wl and self._wl._get_manager() if not manager: self._hooks.hook() # NB: manager will perform atexit hook like behavior for outstanding runs atexit.register(lambda: self._atexit_cleanup()) self._redirect(self._stdout_slave_fd, self._stderr_slave_fd)
python
wandb/sdk/wandb_run.py
2,156
2,166
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,829
_console_stop
def _console_stop(self) -> None: self._restore() if self._output_writer: self._output_writer.close() self._output_writer = None
python
wandb/sdk/wandb_run.py
2,168
2,172
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,830
_on_init
def _on_init(self) -> None: if self._backend and self._backend.interface: logger.info("communicating current version") version_handle = self._backend.interface.deliver_check_version( current_version=wandb.__version__ ) version_result = version_handle.wait(timeout=30) if not version_result: version_handle.abandon() return self._check_version = version_result.response.check_version_response logger.info(f"got version response {self._check_version}")
python
wandb/sdk/wandb_run.py
2,174
2,185
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,831
_on_start
def _on_start(self) -> None: # would like to move _set_global to _on_ready to unify _on_start and _on_attach # (we want to do the set globals after attach) # TODO(console) However _console_start calls Redirect that uses `wandb.run` hence breaks # TODO(jupyter) However _header calls _header_run_info that uses wandb.jupyter that uses # `wandb.run` and hence breaks self._set_globals() self._header( self._check_version, settings=self._settings, printer=self._printer ) if self._settings.save_code and self._settings.code_dir is not None: self.log_code(self._settings.code_dir) if self._backend and self._backend.interface and not self._settings._offline: self._run_status_checker = RunStatusChecker( interface=self._backend.interface, ) self._run_status_checker.start() self._console_start() self._on_ready()
python
wandb/sdk/wandb_run.py
2,187
2,208
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,832
_on_attach
def _on_attach(self) -> None: """Event triggered when run is attached to another run.""" with telemetry.context(run=self) as tel: tel.feature.attach = True self._set_globals() self._is_attached = True self._on_ready()
python
wandb/sdk/wandb_run.py
2,210
2,217
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,833
_register_telemetry_import_hooks
def _register_telemetry_import_hooks( self, ) -> None: def _telemetry_import_hook( run: "Run", module: Any, ) -> None: with telemetry.context(run=run) as tel: try: name = getattr(module, "__name__", None) if name is not None: setattr(tel.imports_finish, name, True) except AttributeError: return import_telemetry_set = telemetry.list_telemetry_imports() import_hook_fn = functools.partial(_telemetry_import_hook, self) for module_name in import_telemetry_set: register_post_import_hook( import_hook_fn, self._run_id, module_name, )
python
wandb/sdk/wandb_run.py
2,219
2,241
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,834
_telemetry_import_hook
def _telemetry_import_hook( run: "Run", module: Any, ) -> None: with telemetry.context(run=run) as tel: try: name = getattr(module, "__name__", None) if name is not None: setattr(tel.imports_finish, name, True) except AttributeError: return
python
wandb/sdk/wandb_run.py
2,222
2,232
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,835
_on_ready
def _on_ready(self) -> None: """Event triggered when run is ready for the user.""" self._register_telemetry_import_hooks() # start reporting any telemetry changes self._telemetry_obj_active = True self._telemetry_flush() # object is about to be returned to the user, don't let them modify it self._freeze() if not self._settings.resume: if os.path.exists(self._settings.resume_fname): os.remove(self._settings.resume_fname)
python
wandb/sdk/wandb_run.py
2,243
2,256
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,836
_make_job_source_reqs
def _make_job_source_reqs(self) -> Tuple[List[str], Dict[str, Any], Dict[str, Any]]: import pkg_resources installed_packages_list = sorted( f"{d.key}=={d.version}" for d in iter(pkg_resources.working_set) ) input_types = TypeRegistry.type_of(self.config.as_dict()).to_json() output_types = TypeRegistry.type_of(self.summary._as_dict()).to_json() return installed_packages_list, input_types, output_types
python
wandb/sdk/wandb_run.py
2,258
2,267
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,837
_construct_job_artifact
def _construct_job_artifact( self, name: str, source_dict: "JobSourceDict", installed_packages_list: List[str], patch_path: Optional[os.PathLike] = None, ) -> "Artifact": job_artifact = wandb.Artifact(name, type="job") if patch_path and os.path.exists(patch_path): job_artifact.add_file(patch_path, "diff.patch") with job_artifact.new_file("requirements.frozen.txt") as f: f.write("\n".join(installed_packages_list)) with job_artifact.new_file("wandb-job.json") as f: f.write(json.dumps(source_dict)) return job_artifact
python
wandb/sdk/wandb_run.py
2,269
2,284
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,838
_create_image_job
def _create_image_job( self, input_types: Dict[str, Any], output_types: Dict[str, Any], installed_packages_list: List[str], docker_image_name: Optional[str] = None, args: Optional[List[str]] = None, ) -> Optional["Artifact"]: docker_image_name = docker_image_name or os.getenv("WANDB_DOCKER") if not docker_image_name: return None name = wandb.util.make_artifact_name_safe(f"job-{docker_image_name}") s_args: Sequence[str] = args if args is not None else self._settings._args source_info: JobSourceDict = { "_version": "v0", "source_type": "image", "source": {"image": docker_image_name, "args": s_args}, "input_types": input_types, "output_types": output_types, "runtime": self._settings._python, } job_artifact = self._construct_job_artifact( name, source_info, installed_packages_list ) return job_artifact
python
wandb/sdk/wandb_run.py
2,286
2,313
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,839
_log_job_artifact_with_image
def _log_job_artifact_with_image( self, docker_image_name: str, args: Optional[List[str]] = None ) -> Artifact: packages, in_types, out_types = self._make_job_source_reqs() job_artifact = self._create_image_job( in_types, out_types, packages, args=args, docker_image_name=docker_image_name, ) artifact = self.log_artifact(job_artifact) if not artifact: raise wandb.Error(f"Job Artifact log unsuccessful: {artifact}") else: return artifact
python
wandb/sdk/wandb_run.py
2,315
2,332
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,840
_on_probe_exit
def _on_probe_exit(self, probe_handle: MailboxProbe) -> None: handle = probe_handle.get_mailbox_handle() if handle: result = handle.wait(timeout=0) if not result: return probe_handle.set_probe_result(result) assert self._backend and self._backend.interface handle = self._backend.interface.deliver_poll_exit() probe_handle.set_mailbox_handle(handle)
python
wandb/sdk/wandb_run.py
2,334
2,343
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,841
_on_progress_exit
def _on_progress_exit(self, progress_handle: MailboxProgress) -> None: probe_handles = progress_handle.get_probe_handles() assert probe_handles and len(probe_handles) == 1 result = probe_handles[0].get_probe_result() if not result: return self._footer_file_pusher_status_info( result.response.poll_exit_response, printer=self._printer )
python
wandb/sdk/wandb_run.py
2,345
2,354
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,842
_on_finish
def _on_finish(self) -> None: trigger.call("on_finished") if self._run_status_checker is not None: self._run_status_checker.stop() self._console_stop() # TODO: there's a race here with jupyter console logging assert self._backend and self._backend.interface exit_handle = self._backend.interface.deliver_exit(self._exit_code) exit_handle.add_probe(on_probe=self._on_probe_exit) self._footer_exit_status_info( self._exit_code, settings=self._settings, printer=self._printer ) _ = exit_handle.wait(timeout=-1, on_progress=self._on_progress_exit) # dispatch all our final requests poll_exit_handle = self._backend.interface.deliver_poll_exit() server_info_handle = self._backend.interface.deliver_request_server_info() final_summary_handle = self._backend.interface.deliver_get_summary() sampled_history_handle = ( self._backend.interface.deliver_request_sampled_history() ) # wait for them, it's ok to do this serially but this can be improved result = poll_exit_handle.wait(timeout=-1) assert result self._poll_exit_response = result.response.poll_exit_response result = server_info_handle.wait(timeout=-1) assert result self._server_info_response = result.response.server_info_response result = sampled_history_handle.wait(timeout=-1) assert result self._sampled_history = result.response.sampled_history_response result = final_summary_handle.wait(timeout=-1) assert result self._final_summary = result.response.get_summary_response if self._backend: self._backend.cleanup() if self._run_status_checker: self._run_status_checker.join() self._unregister_telemetry_import_hooks(self._run_id)
python
wandb/sdk/wandb_run.py
2,356
2,405
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,843
_unregister_telemetry_import_hooks
def _unregister_telemetry_import_hooks(run_id: str) -> None: import_telemetry_set = telemetry.list_telemetry_imports() for module_name in import_telemetry_set: unregister_post_import_hook(module_name, run_id)
python
wandb/sdk/wandb_run.py
2,408
2,411
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,844
_on_final
def _on_final(self) -> None: self._footer( self._sampled_history, self._final_summary, self._poll_exit_response, self._server_info_response, self._check_version, self._reporter, self._quiet, settings=self._settings, printer=self._printer, )
python
wandb/sdk/wandb_run.py
2,413
2,424
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,845
define_metric
def define_metric( self, name: str, step_metric: Union[str, wandb_metric.Metric, None] = None, step_sync: Optional[bool] = None, hidden: Optional[bool] = None, summary: Optional[str] = None, goal: Optional[str] = None, overwrite: Optional[bool] = None, **kwargs: Any, ) -> wandb_metric.Metric: """Define metric properties which will later be logged with `wandb.log()`. Arguments: name: Name of the metric. step_metric: Independent variable associated with the metric. step_sync: Automatically add `step_metric` to history if needed. Defaults to True if step_metric is specified. hidden: Hide this metric from automatic plots. summary: Specify aggregate metrics added to summary. Supported aggregations: "min,max,mean,best,last,none" Default aggregation is `copy` Aggregation `best` defaults to `goal`==`minimize` goal: Specify direction for optimizing the metric. Supported directions: "minimize,maximize" Returns: A metric object is returned that can be further specified. """ return self._define_metric( name, step_metric, step_sync, hidden, summary, goal, overwrite, **kwargs )
python
wandb/sdk/wandb_run.py
2,428
2,460
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,846
_define_metric
def _define_metric( self, name: str, step_metric: Union[str, wandb_metric.Metric, None] = None, step_sync: Optional[bool] = None, hidden: Optional[bool] = None, summary: Optional[str] = None, goal: Optional[str] = None, overwrite: Optional[bool] = None, **kwargs: Any, ) -> wandb_metric.Metric: if not name: raise wandb.Error("define_metric() requires non-empty name argument") for k in kwargs: wandb.termwarn(f"Unhandled define_metric() arg: {k}") if isinstance(step_metric, wandb_metric.Metric): step_metric = step_metric.name for arg_name, arg_val, exp_type in ( ("name", name, str), ("step_metric", step_metric, str), ("step_sync", step_sync, bool), ("hidden", hidden, bool), ("summary", summary, str), ("goal", goal, str), ("overwrite", overwrite, bool), ): # NOTE: type checking is broken for isinstance and str if arg_val is not None and not isinstance(arg_val, exp_type): arg_type = type(arg_val).__name__ raise wandb.Error( "Unhandled define_metric() arg: {} type: {}".format( arg_name, arg_type ) ) stripped = name[:-1] if name.endswith("*") else name if "*" in stripped: raise wandb.Error( "Unhandled define_metric() arg: name (glob suffixes only): {}".format( name ) ) summary_ops: Optional[Sequence[str]] = None if summary: summary_items = [s.lower() for s in summary.split(",")] summary_ops = [] valid = {"min", "max", "mean", "best", "last", "copy", "none"} for i in summary_items: if i not in valid: raise wandb.Error(f"Unhandled define_metric() arg: summary op: {i}") summary_ops.append(i) goal_cleaned: Optional[str] = None if goal is not None: goal_cleaned = goal[:3].lower() valid_goal = {"min", "max"} if goal_cleaned not in valid_goal: raise wandb.Error(f"Unhandled define_metric() arg: goal: {goal}") m = wandb_metric.Metric( name=name, step_metric=step_metric, step_sync=step_sync, summary=summary_ops, hidden=hidden, goal=goal_cleaned, overwrite=overwrite, ) m._set_callback(self._metric_callback) m._commit() with telemetry.context(run=self) as tel: tel.feature.metric = True return m
python
wandb/sdk/wandb_run.py
2,462
2,531
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,847
watch
def watch( # type: ignore self, models, criterion=None, log="gradients", log_freq=100, idx=None, log_graph=False, ) -> None: wandb.watch(models, criterion, log, log_freq, idx, log_graph)
python
wandb/sdk/wandb_run.py
2,535
2,544
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,848
unwatch
def unwatch(self, models=None) -> None: # type: ignore wandb.unwatch(models=models)
python
wandb/sdk/wandb_run.py
2,548
2,549
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,849
_swap_artifact_name
def _swap_artifact_name(self, artifact_name: str, use_as: Optional[str]) -> str: artifact_key_string = use_as or artifact_name replacement_artifact_info = self._launch_artifact_mapping.get( artifact_key_string ) if replacement_artifact_info is not None: new_name = replacement_artifact_info.get("name") entity = replacement_artifact_info.get("entity") project = replacement_artifact_info.get("project") if new_name is None or entity is None or project is None: raise ValueError( "Misconfigured artifact in launch config. Must include name, project and entity keys." ) return f"{entity}/{project}/{new_name}" elif replacement_artifact_info is None and use_as is None: sequence_name = artifact_name.split(":")[0].split("/")[-1] unique_artifact_replacement_info = ( self._unique_launch_artifact_sequence_names.get(sequence_name) ) if unique_artifact_replacement_info is not None: new_name = unique_artifact_replacement_info.get("name") entity = unique_artifact_replacement_info.get("entity") project = unique_artifact_replacement_info.get("project") if new_name is None or entity is None or project is None: raise ValueError( "Misconfigured artifact in launch config. Must include name, project and entity keys." ) return f"{entity}/{project}/{new_name}" else: return artifact_name return artifact_name
python
wandb/sdk/wandb_run.py
2,552
2,584
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,850
_detach
def _detach(self) -> None: pass
python
wandb/sdk/wandb_run.py
2,586
2,587
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,851
link_artifact
def link_artifact( self, artifact: Union[public.Artifact, Artifact], target_path: str, aliases: Optional[List[str]] = None, ) -> None: """Link the given artifact to a portfolio (a promoted collection of artifacts). The linked artifact will be visible in the UI for the specified portfolio. Arguments: artifact: the (public or local) artifact which will be linked target_path: `str` - takes the following forms: {portfolio}, {project}/{portfolio}, or {entity}/{project}/{portfolio} aliases: `List[str]` - optional alias(es) that will only be applied on this linked artifact inside the portfolio. The alias "latest" will always be applied to the latest version of an artifact that is linked. Returns: None """ portfolio, project, entity = wandb.util._parse_entity_project_item(target_path) if aliases is None: aliases = [] if self._backend and self._backend.interface: if isinstance(artifact, Artifact) and not artifact._logged_artifact: artifact = self._log_artifact(artifact) if not self._settings._offline: self._backend.interface.publish_link_artifact( self, artifact, portfolio, aliases, entity, project, ) else: # TODO: implement offline mode + sync raise NotImplementedError
python
wandb/sdk/wandb_run.py
2,591
2,631
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,852
use_artifact
def use_artifact( self, artifact_or_name: Union[str, public.Artifact, Artifact], type: Optional[str] = None, aliases: Optional[List[str]] = None, use_as: Optional[str] = None, ) -> Union[public.Artifact, Artifact]: """Declare an artifact as an input to a run. Call `download` or `file` on the returned object to get the contents locally. Arguments: artifact_or_name: (str or Artifact) An artifact name. May be prefixed with entity/project/. Valid names can be in the following forms: - name:version - name:alias - digest You can also pass an Artifact object created by calling `wandb.Artifact` type: (str, optional) The type of artifact to use. aliases: (list, optional) Aliases to apply to this artifact use_as: (string, optional) Optional string indicating what purpose the artifact was used with. Will be shown in UI. Returns: An `Artifact` object. """ if self._settings._offline: raise TypeError("Cannot use artifact when in offline mode.") r = self._run_obj assert r is not None api = internal.Api(default_settings={"entity": r.entity, "project": r.project}) api.set_current_run_id(self._run_id) if isinstance(artifact_or_name, str): if self._launch_artifact_mapping: name = self._swap_artifact_name(artifact_or_name, use_as) else: name = artifact_or_name public_api = self._public_api() artifact = public_api.artifact(type=type, name=name) if type is not None and type != artifact.type: raise ValueError( "Supplied type {} does not match type {} of artifact {}".format( type, artifact.type, artifact.name ) ) artifact._use_as = use_as or artifact_or_name if use_as: if ( use_as in self._used_artifact_slots.keys() and self._used_artifact_slots[use_as] != artifact.id ): raise ValueError( "Cannot call use_artifact with the same use_as argument more than once" ) elif ":" in use_as or "/" in use_as: raise ValueError( "use_as cannot contain special characters ':' or '/'" ) self._used_artifact_slots[use_as] = artifact.id api.use_artifact( artifact.id, use_as=use_as or artifact_or_name, ) else: artifact = artifact_or_name if aliases is None: aliases = [] elif isinstance(aliases, str): aliases = [aliases] if isinstance(artifact_or_name, wandb.Artifact): if use_as is not None: wandb.termwarn( "Indicating use_as is not supported when using an artifact with an instance of `wandb.Artifact`" ) self._log_artifact( artifact, aliases=aliases, is_user_created=True, use_after_commit=True, ) artifact.wait() artifact._use_as = use_as or artifact.name elif isinstance(artifact, public.Artifact): if ( self._launch_artifact_mapping and artifact.name in self._launch_artifact_mapping.keys() ): wandb.termwarn( "Swapping artifacts is not supported when using an instance of `public.Artifact`. " f"Using {artifact.name}." ) artifact._use_as = use_as or artifact.name api.use_artifact( artifact.id, use_as=use_as or artifact._use_as or artifact.name ) else: raise ValueError( 'You must pass an artifact name (e.g. "pedestrian-dataset:v1"), ' "an instance of `wandb.Artifact`, or `wandb.Api().artifact()` to `use_artifact`" ) if self._backend and self._backend.interface: self._backend.interface.publish_use_artifact(artifact) return artifact
python
wandb/sdk/wandb_run.py
2,635
2,739
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,853
log_artifact
def log_artifact( self, artifact_or_path: Union[wandb_artifacts.Artifact, StrPath], name: Optional[str] = None, type: Optional[str] = None, aliases: Optional[List[str]] = None, ) -> wandb_artifacts.Artifact: """Declare an artifact as an output of a run. Arguments: artifact_or_path: (str or Artifact) A path to the contents of this artifact, can be in the following forms: - `/local/directory` - `/local/directory/file.txt` - `s3://bucket/path` You can also pass an Artifact object created by calling `wandb.Artifact`. name: (str, optional) An artifact name. May be prefixed with entity/project. Valid names can be in the following forms: - name:version - name:alias - digest This will default to the basename of the path prepended with the current run id if not specified. type: (str) The type of artifact to log, examples include `dataset`, `model` aliases: (list, optional) Aliases to apply to this artifact, defaults to `["latest"]` Returns: An `Artifact` object. """ return self._log_artifact( artifact_or_path, name=name, type=type, aliases=aliases )
python
wandb/sdk/wandb_run.py
2,743
2,776
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,854
upsert_artifact
def upsert_artifact( self, artifact_or_path: Union[wandb_artifacts.Artifact, str], name: Optional[str] = None, type: Optional[str] = None, aliases: Optional[List[str]] = None, distributed_id: Optional[str] = None, ) -> wandb_artifacts.Artifact: """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. Arguments: artifact_or_path: (str or Artifact) A path to the contents of this artifact, can be in the following forms: - `/local/directory` - `/local/directory/file.txt` - `s3://bucket/path` You can also pass an Artifact object created by calling `wandb.Artifact`. name: (str, optional) An artifact name. May be prefixed with entity/project. Valid names can be in the following forms: - name:version - name:alias - digest This will default to the basename of the path prepended with the current run id if not specified. type: (str) The type of artifact to log, examples include `dataset`, `model` aliases: (list, optional) Aliases to apply to this artifact, defaults to `["latest"]` distributed_id: (string, optional) Unique string that all distributed jobs share. If None, defaults to the run's group name. Returns: An `Artifact` object. """ if self._get_group() == "" and distributed_id is None: raise TypeError( "Cannot upsert artifact unless run is in a group or distributed_id is provided" ) if distributed_id is None: distributed_id = self._get_group() return self._log_artifact( artifact_or_path, name=name, type=type, aliases=aliases, distributed_id=distributed_id, finalize=False, )
python
wandb/sdk/wandb_run.py
2,780
2,830
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,855
finish_artifact
def finish_artifact( self, artifact_or_path: Union[wandb_artifacts.Artifact, str], name: Optional[str] = None, type: Optional[str] = None, aliases: Optional[List[str]] = None, distributed_id: Optional[str] = None, ) -> wandb_artifacts.Artifact: """Finishes a non-finalized artifact as output of a run. Subsequent "upserts" with the same distributed ID will result in a new version. Arguments: artifact_or_path: (str or Artifact) A path to the contents of this artifact, can be in the following forms: - `/local/directory` - `/local/directory/file.txt` - `s3://bucket/path` You can also pass an Artifact object created by calling `wandb.Artifact`. name: (str, optional) An artifact name. May be prefixed with entity/project. Valid names can be in the following forms: - name:version - name:alias - digest This will default to the basename of the path prepended with the current run id if not specified. type: (str) The type of artifact to log, examples include `dataset`, `model` aliases: (list, optional) Aliases to apply to this artifact, defaults to `["latest"]` distributed_id: (string, optional) Unique string that all distributed jobs share. If None, defaults to the run's group name. Returns: An `Artifact` object. """ if self._get_group() == "" and distributed_id is None: raise TypeError( "Cannot finish artifact unless run is in a group or distributed_id is provided" ) if distributed_id is None: distributed_id = self._get_group() return self._log_artifact( artifact_or_path, name, type, aliases, distributed_id=distributed_id, finalize=True, )
python
wandb/sdk/wandb_run.py
2,834
2,884
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,856
_log_artifact
def _log_artifact( self, artifact_or_path: Union[wandb_artifacts.Artifact, StrPath], name: Optional[str] = None, type: Optional[str] = None, aliases: Optional[List[str]] = None, distributed_id: Optional[str] = None, finalize: bool = True, is_user_created: bool = False, use_after_commit: bool = False, ) -> wandb_artifacts.Artifact: api = internal.Api() if api.settings().get("anonymous") == "true": wandb.termwarn( "Artifacts logged anonymously cannot be claimed and expire after 7 days." ) if not finalize and distributed_id is None: raise TypeError("Must provide distributed_id if artifact is not finalize") if aliases is not None: if any(invalid in alias for alias in aliases for invalid in ["/", ":"]): raise ValueError( "Aliases must not contain any of the following characters: /, :" ) artifact, aliases = self._prepare_artifact( artifact_or_path, name, type, aliases ) artifact.distributed_id = distributed_id self._assert_can_log_artifact(artifact) if self._backend and self._backend.interface: if not self._settings._offline: future = self._backend.interface.communicate_artifact( self, artifact, aliases, self.step, finalize=finalize, is_user_created=is_user_created, use_after_commit=use_after_commit, ) artifact._logged_artifact = _LazyArtifact(self._public_api(), future) else: self._backend.interface.publish_artifact( self, artifact, aliases, finalize=finalize, is_user_created=is_user_created, use_after_commit=use_after_commit, ) elif self._internal_run_interface: self._internal_run_interface.publish_artifact( self, artifact, aliases, finalize=finalize, is_user_created=is_user_created, use_after_commit=use_after_commit, ) return artifact
python
wandb/sdk/wandb_run.py
2,886
2,944
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,857
_public_api
def _public_api(self, overrides: Optional[Dict[str, str]] = None) -> PublicApi: overrides = {"run": self._run_id} run_obj = self._run_obj if run_obj is not None: overrides["entity"] = run_obj.entity overrides["project"] = run_obj.project return public.Api(overrides)
python
wandb/sdk/wandb_run.py
2,946
2,952
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,858
_assert_can_log_artifact
def _assert_can_log_artifact(self, artifact) -> None: # type: ignore if not self._settings._offline: try: public_api = self._public_api() expected_type = public.Artifact.expected_type( public_api.client, artifact.name, public_api.settings["entity"], public_api.settings["project"], ) except requests.exceptions.RequestException: # Just return early if there is a network error. This is # ok, as this function is intended to help catch an invalid # type early, but not a hard requirement for valid operation. return if expected_type is not None and artifact.type != expected_type: raise ValueError( f"Artifact {artifact.name} already exists with type {expected_type}; " f"cannot create another with type {artifact.type}" )
python
wandb/sdk/wandb_run.py
2,955
2,974
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,859
_prepare_artifact
def _prepare_artifact( self, artifact_or_path: Union[wandb_artifacts.Artifact, StrPath], name: Optional[str] = None, type: Optional[str] = None, aliases: Optional[List[str]] = None, ) -> Tuple[wandb_artifacts.Artifact, List[str]]: if isinstance(artifact_or_path, (str, os.PathLike)): name = name or f"run-{self._run_id}-{os.path.basename(artifact_or_path)}" artifact = wandb.Artifact(name, type or "unspecified") if os.path.isfile(artifact_or_path): artifact.add_file(artifact_or_path) elif os.path.isdir(artifact_or_path): artifact.add_dir(artifact_or_path) elif "://" in str(artifact_or_path): artifact.add_reference(artifact_or_path) else: raise ValueError( "path must be a file, directory or external" "reference like s3://bucket/path" ) else: artifact = artifact_or_path if not isinstance(artifact, wandb.Artifact): raise ValueError( "You must pass an instance of wandb.Artifact or a " "valid file path to log_artifact" ) artifact.finalize() return artifact, _resolve_aliases(aliases)
python
wandb/sdk/wandb_run.py
2,976
3,005
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,860
alert
def alert( self, title: str, text: str, level: Optional[Union[str, "AlertLevel"]] = None, wait_duration: Union[int, float, timedelta, None] = None, ) -> None: """Launch an alert with the given title and text. Arguments: title: (str) The title of the alert, must be less than 64 characters long. text: (str) The text body of the alert. level: (str or wandb.AlertLevel, optional) The alert level to use, either: `INFO`, `WARN`, or `ERROR`. wait_duration: (int, float, or timedelta, optional) The time to wait (in seconds) before sending another alert with this title. """ level = level or wandb.AlertLevel.INFO level_str: str = level.value if isinstance(level, wandb.AlertLevel) else level if level_str not in {lev.value for lev in wandb.AlertLevel}: raise ValueError("level must be one of 'INFO', 'WARN', or 'ERROR'") wait_duration = wait_duration or timedelta(minutes=1) if isinstance(wait_duration, int) or isinstance(wait_duration, float): wait_duration = timedelta(seconds=wait_duration) elif not callable(getattr(wait_duration, "total_seconds", None)): raise ValueError( "wait_duration must be an int, float, or datetime.timedelta" ) wait_duration = int(wait_duration.total_seconds() * 1000) if self._backend and self._backend.interface: self._backend.interface.publish_alert(title, text, level_str, wait_duration)
python
wandb/sdk/wandb_run.py
3,009
3,040
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,861
__enter__
def __enter__(self) -> "Run": return self
python
wandb/sdk/wandb_run.py
3,042
3,043
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,862
__exit__
def __exit__( self, exc_type: Type[BaseException], exc_val: BaseException, exc_tb: TracebackType, ) -> bool: exit_code = 0 if exc_type is None else 1 self._finish(exit_code) return exc_type is None
python
wandb/sdk/wandb_run.py
3,045
3,053
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,863
mark_preempting
def mark_preempting(self) -> None: """Mark this run as preempting. Also tells the internal process to immediately report this to server. """ if self._backend and self._backend.interface: self._backend.interface.publish_preempting()
python
wandb/sdk/wandb_run.py
3,057
3,063
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,864
_header
def _header( check_version: Optional["CheckVersionResponse"] = None, *, settings: "Settings", printer: Union["PrinterTerm", "PrinterJupyter"], ) -> None: # printer = printer or get_printer(settings._jupyter) Run._header_version_check_info( check_version, settings=settings, printer=printer ) Run._header_wandb_version_info(settings=settings, printer=printer) Run._header_sync_info(settings=settings, printer=printer) Run._header_run_info(settings=settings, printer=printer)
python
wandb/sdk/wandb_run.py
3,071
3,083
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,865
_header_version_check_info
def _header_version_check_info( check_version: Optional["CheckVersionResponse"] = None, *, settings: "Settings", printer: Union["PrinterTerm", "PrinterJupyter"], ) -> None: if not check_version or settings._offline: return # printer = printer or get_printer(settings._jupyter) if check_version.delete_message: printer.display(check_version.delete_message, level="error") elif check_version.yank_message: printer.display(check_version.yank_message, level="warn") printer.display( check_version.upgrade_message, off=not check_version.upgrade_message )
python
wandb/sdk/wandb_run.py
3,086
3,103
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,866
_header_wandb_version_info
def _header_wandb_version_info( *, settings: "Settings", printer: Union["PrinterTerm", "PrinterJupyter"], ) -> None: if settings.quiet or settings.silent: return # printer = printer or get_printer(settings._jupyter) # TODO: add this to a higher verbosity level printer.display( f"Tracking run with wandb version {wandb.__version__}", off=False )
python
wandb/sdk/wandb_run.py
3,106
3,118
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,867
_header_sync_info
def _header_sync_info( *, settings: "Settings", printer: Union["PrinterTerm", "PrinterJupyter"], ) -> None: # printer = printer or get_printer(settings._jupyter) if settings._offline: printer.display( [ f"W&B syncing is set to {printer.code('`offline`')} in this directory. ", f"Run {printer.code('`wandb online`')} or set {printer.code('WANDB_MODE=online')} " "to enable cloud syncing.", ] ) else: info = [f"Run data is saved locally in {printer.files(settings.sync_dir)}"] if not printer._html: info.append( f"Run {printer.code('`wandb offline`')} to turn off syncing." ) printer.display(info, off=settings.quiet or settings.silent)
python
wandb/sdk/wandb_run.py
3,121
3,141
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,868
_header_run_info
def _header_run_info( *, settings: "Settings", printer: Union["PrinterTerm", "PrinterJupyter"], ) -> None: if settings._offline or settings.silent: return run_url = settings.run_url project_url = settings.project_url sweep_url = settings.sweep_url run_state_str = "Resuming run" if settings.resumed else "Syncing run" run_name = settings.run_name if not run_name: return # printer = printer or get_printer(settings._jupyter) if printer._html: if not wandb.jupyter.maybe_display(): run_line = f"<strong>{printer.link(run_url, run_name)}</strong>" project_line, sweep_line = "", "" # TODO(settings): make settings the source of truth if not wandb.jupyter.quiet(): doc_html = printer.link(wburls.get("doc_run"), "docs") project_html = printer.link(project_url, "Weights & Biases") project_line = f"to {project_html} ({doc_html})" if sweep_url: sweep_line = f"Sweep page: {printer.link(sweep_url, sweep_url)}" printer.display( [f"{run_state_str} {run_line} {project_line}", sweep_line], ) else: printer.display( f"{run_state_str} {printer.name(run_name)}", off=not run_name ) if not settings.quiet: # TODO: add verbosity levels and add this to higher levels printer.display( f'{printer.emoji("star")} View project at {printer.link(project_url)}' ) if sweep_url: printer.display( f'{printer.emoji("broom")} View sweep at {printer.link(sweep_url)}' ) printer.display( f'{printer.emoji("rocket")} View run at {printer.link(run_url)}', ) # TODO(settings) use `wandb_settings` (if self.settings.anonymous == "true":) if Api().api.settings().get("anonymous") == "true": printer.display( "Do NOT share these links with anyone. They can be used to claim your runs.", level="warn", off=not run_name, )
python
wandb/sdk/wandb_run.py
3,144
3,205
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,869
_footer
def _footer( sampled_history: Optional["SampledHistoryResponse"] = None, final_summary: Optional["GetSummaryResponse"] = None, poll_exit_response: Optional[PollExitResponse] = None, server_info_response: Optional[ServerInfoResponse] = None, check_version: Optional["CheckVersionResponse"] = None, reporter: Optional[Reporter] = None, quiet: Optional[bool] = None, *, settings: "Settings", printer: Union["PrinterTerm", "PrinterJupyter"], ) -> None: Run._footer_history_summary_info( history=sampled_history, summary=final_summary, quiet=quiet, settings=settings, printer=printer, ) Run._footer_sync_info( poll_exit_response=poll_exit_response, quiet=quiet, settings=settings, printer=printer, ) Run._footer_log_dir_info(quiet=quiet, settings=settings, printer=printer) Run._footer_version_check_info( check_version=check_version, quiet=quiet, settings=settings, printer=printer ) Run._footer_local_warn( server_info_response=server_info_response, quiet=quiet, settings=settings, printer=printer, ) Run._footer_reporter_warn_err( reporter=reporter, quiet=quiet, settings=settings, printer=printer ) Run._footer_server_messages( server_info_response=server_info_response, quiet=quiet, settings=settings, printer=printer, )
python
wandb/sdk/wandb_run.py
3,213
3,257
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,870
_footer_exit_status_info
def _footer_exit_status_info( exit_code: Optional[int], *, settings: "Settings", printer: Union["PrinterTerm", "PrinterJupyter"], ) -> None: if settings.silent: return status = "(success)." if not exit_code else f"(failed {exit_code})." info = [ f"Waiting for W&B process to finish... {printer.status(status, bool(exit_code))}" ] if not settings._offline and exit_code: info.append(f"Press {printer.abort()} to abort syncing.") printer.display(f'{" ".join(info)}')
python
wandb/sdk/wandb_run.py
3,260
3,277
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,871
_footer_file_pusher_status_info
def _footer_file_pusher_status_info( poll_exit_responses: Optional[ Union[PollExitResponse, List[Optional[PollExitResponse]]] ] = None, *, printer: Union["PrinterTerm", "PrinterJupyter"], ) -> None: if not poll_exit_responses: return if isinstance(poll_exit_responses, PollExitResponse): Run._footer_single_run_file_pusher_status_info( poll_exit_responses, printer=printer ) elif isinstance(poll_exit_responses, list): poll_exit_responses_list = poll_exit_responses assert all( response is None or isinstance(response, PollExitResponse) for response in poll_exit_responses_list ) if len(poll_exit_responses_list) == 0: return elif len(poll_exit_responses_list) == 1: Run._footer_single_run_file_pusher_status_info( poll_exit_responses_list[0], printer=printer ) else: Run._footer_multiple_runs_file_pusher_status_info( poll_exit_responses_list, printer=printer ) else: raise ValueError( f"Got the type `{type(poll_exit_responses)}` for `poll_exit_responses`. " "Expected either None, PollExitResponse or a List[Union[PollExitResponse, None]]" )
python
wandb/sdk/wandb_run.py
3,281
3,314
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,872
_footer_single_run_file_pusher_status_info
def _footer_single_run_file_pusher_status_info( poll_exit_response: Optional[PollExitResponse] = None, *, printer: Union["PrinterTerm", "PrinterJupyter"], ) -> None: # todo: is this same as settings._offline? if not poll_exit_response: return progress = poll_exit_response.pusher_stats done = poll_exit_response.done megabyte = wandb.util.POW_2_BYTES[2][1] line = ( f"{progress.uploaded_bytes / megabyte :.3f} MB of {progress.total_bytes / megabyte:.3f} MB uploaded " f"({progress.deduped_bytes / megabyte:.3f} MB deduped)\r" ) percent_done = ( 1.0 if progress.total_bytes == 0 else progress.uploaded_bytes / progress.total_bytes ) printer.progress_update(line, percent_done) if done: printer.progress_close() dedupe_fraction = ( progress.deduped_bytes / float(progress.total_bytes) if progress.total_bytes > 0 else 0 ) if dedupe_fraction > 0.01: printer.display( f"W&B sync reduced upload amount by {dedupe_fraction * 100:.1f}% " )
python
wandb/sdk/wandb_run.py
3,317
3,353
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,873
_footer_multiple_runs_file_pusher_status_info
def _footer_multiple_runs_file_pusher_status_info( poll_exit_responses: List[Optional[PollExitResponse]], *, printer: Union["PrinterTerm", "PrinterJupyter"], ) -> None: # todo: is this same as settings._offline? if not all(poll_exit_responses): return megabyte = wandb.util.POW_2_BYTES[2][1] total_files: int = sum( sum( [ response.file_counts.wandb_count, response.file_counts.media_count, response.file_counts.artifact_count, response.file_counts.other_count, ] ) for response in poll_exit_responses if response is not None and response.file_counts is not None ) uploaded = sum( response.pusher_stats.uploaded_bytes for response in poll_exit_responses if response is not None and response.pusher_stats is not None ) total = sum( response.pusher_stats.total_bytes for response in poll_exit_responses if response is not None and response.pusher_stats is not None ) line = ( f"Processing {len(poll_exit_responses)} runs with {total_files} files " f"({uploaded/megabyte :.2f} MB/{total/megabyte :.2f} MB)\r" ) # line = "{}{:<{max_len}}\r".format(line, " ", max_len=(80 - len(line))) printer.progress_update(line) # type: ignore [call-arg] done = all( [ poll_exit_response.done for poll_exit_response in poll_exit_responses if poll_exit_response ] ) if done: printer.progress_close()
python
wandb/sdk/wandb_run.py
3,356
3,404
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,874
_footer_sync_info
def _footer_sync_info( poll_exit_response: Optional[PollExitResponse] = None, quiet: Optional[bool] = None, *, settings: "Settings", printer: Union["PrinterTerm", "PrinterJupyter"], ) -> None: if settings.silent: return # printer = printer or get_printer(settings._jupyter) if settings._offline: printer.display( [ "You can sync this run to the cloud by running:", printer.code(f"wandb sync {settings.sync_dir}"), ], off=(quiet or settings.quiet), ) else: info = [] if settings.run_name and settings.run_url: info = [ f"{printer.emoji('rocket')} View run {printer.name(settings.run_name)} at: {printer.link(settings.run_url)}" ] if poll_exit_response and poll_exit_response.file_counts: logger.info("logging synced files") file_counts = poll_exit_response.file_counts info.append( f"Synced {file_counts.wandb_count} W&B file(s), {file_counts.media_count} media file(s), " f"{file_counts.artifact_count} artifact file(s) and {file_counts.other_count} other file(s)", ) printer.display(info)
python
wandb/sdk/wandb_run.py
3,407
3,440
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,875
_footer_log_dir_info
def _footer_log_dir_info( quiet: Optional[bool] = None, *, settings: "Settings", printer: Union["PrinterTerm", "PrinterJupyter"], ) -> None: if (quiet or settings.quiet) or settings.silent: return log_dir = settings.log_user or settings.log_internal if log_dir: log_dir = os.path.dirname(log_dir.replace(os.getcwd(), ".")) printer.display( f"Find logs at: {printer.files(log_dir)}", )
python
wandb/sdk/wandb_run.py
3,443
3,457
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,876
_footer_history_summary_info
def _footer_history_summary_info( history: Optional["SampledHistoryResponse"] = None, summary: Optional["GetSummaryResponse"] = None, quiet: Optional[bool] = None, *, settings: "Settings", printer: Union["PrinterTerm", "PrinterJupyter"], ) -> None: if (quiet or settings.quiet) or settings.silent: return # printer = printer or get_printer(settings._jupyter) panel = [] # Render history if available if history: logger.info("rendering history") sampled_history = { item.key: wandb.util.downsample( item.values_float or item.values_int, 40 ) for item in history.item if not item.key.startswith("_") } history_rows = [] for key, values in sorted(sampled_history.items()): if any(not isinstance(value, numbers.Number) for value in values): continue sparkline = printer.sparklines(values) if sparkline: history_rows.append([key, sparkline]) if history_rows: history_grid = printer.grid( history_rows, "Run history:", ) panel.append(history_grid) # Render summary if available if summary: final_summary = { item.key: json.loads(item.value_json) for item in summary.item if not item.key.startswith("_") } logger.info("rendering summary") summary_rows = [] for key, value in sorted(final_summary.items()): # arrays etc. might be too large. for now, we just don't print them if isinstance(value, str): value = value[:20] + "..." * (len(value) >= 20) summary_rows.append([key, value]) elif isinstance(value, numbers.Number): value = round(value, 5) if isinstance(value, float) else value summary_rows.append([key, str(value)]) else: continue if summary_rows: summary_grid = printer.grid( summary_rows, "Run summary:", ) panel.append(summary_grid) if panel: printer.display(printer.panel(panel))
python
wandb/sdk/wandb_run.py
3,460
3,529
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,877
_footer_local_warn
def _footer_local_warn( server_info_response: Optional[ServerInfoResponse] = None, quiet: Optional[bool] = None, *, settings: "Settings", printer: Union["PrinterTerm", "PrinterJupyter"], ) -> None: if (quiet or settings.quiet) or settings.silent: return if settings._offline: return if not server_info_response or not server_info_response.local_info: return if settings.is_local: local_info = server_info_response.local_info latest_version, out_of_date = local_info.version, local_info.out_of_date if out_of_date: # printer = printer or get_printer(settings._jupyter) printer.display( f"Upgrade to the {latest_version} version of W&B Server to get the latest features. " f"Learn more: {printer.link(wburls.get('upgrade_server'))}", level="warn", )
python
wandb/sdk/wandb_run.py
3,532
3,557
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,878
_footer_server_messages
def _footer_server_messages( server_info_response: Optional[ServerInfoResponse] = None, quiet: Optional[bool] = None, *, settings: "Settings", printer: Union["PrinterTerm", "PrinterJupyter"], ) -> None: if (quiet or settings.quiet) or settings.silent: return if settings.disable_hints: return if server_info_response and server_info_response.server_messages: for message in server_info_response.server_messages.item: printer.display( message.html_text if printer._html else message.utf_text, default_text=message.plain_text, level=message.level, off=message.type.lower() != "footer", )
python
wandb/sdk/wandb_run.py
3,560
3,580
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,879
_footer_version_check_info
def _footer_version_check_info( check_version: Optional["CheckVersionResponse"] = None, quiet: Optional[bool] = None, *, settings: "Settings", printer: Union["PrinterTerm", "PrinterJupyter"], ) -> None: if not check_version: return if settings._offline: return if (quiet or settings.quiet) or settings.silent: return # printer = printer or get_printer(settings._jupyter) if check_version.delete_message: printer.display(check_version.delete_message, level="error") elif check_version.yank_message: printer.display(check_version.yank_message, level="warn") # only display upgrade message if packages are bad package_problem = check_version.delete_message or check_version.yank_message if package_problem and check_version.upgrade_message: printer.display(check_version.upgrade_message)
python
wandb/sdk/wandb_run.py
3,583
3,608
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,880
_footer_reporter_warn_err
def _footer_reporter_warn_err( reporter: Optional[Reporter] = None, quiet: Optional[bool] = None, *, settings: "Settings", printer: Union["PrinterTerm", "PrinterJupyter"], ) -> None: if (quiet or settings.quiet) or settings.silent: return if not reporter: return # printer = printer or get_printer(settings._jupyter) warning_lines = reporter.warning_lines if warning_lines: warnings = ["Warnings:"] + [f"{line}" for line in warning_lines] if len(warning_lines) < reporter.warning_count: warnings.append("More warnings...") printer.display(warnings) error_lines = reporter.error_lines if error_lines: errors = ["Errors:"] + [f"{line}" for line in error_lines] if len(error_lines) < reporter.error_count: errors.append("More errors...") printer.display(errors)
python
wandb/sdk/wandb_run.py
3,611
3,638
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,881
restore
def restore( name: str, run_path: Optional[str] = None, replace: bool = False, root: Optional[str] = None, ) -> Union[None, TextIO]: """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. Arguments: name: the name of the file run_path: optional path to a run to pull files from, i.e. `username/project_name/run_id` if wandb.init has not been called, this is required. replace: whether to download the file even if it already exists locally root: the directory to download the file to. Defaults to the current directory or the run directory if wandb.init was called. Returns: None if it can't find the file, otherwise a file object open for reading Raises: wandb.CommError: if we can't connect to the wandb backend ValueError: if the file is not found or can't find run_path """ is_disabled = wandb.run is not None and wandb.run.disabled run = None if is_disabled else wandb.run if run_path is None: if run is not None: run_path = run.path else: raise ValueError( "run_path required when calling wandb.restore before wandb.init" ) if root is None: if run is not None: root = run.dir api = public.Api() api_run = api.run(run_path) if root is None: root = os.getcwd() path = os.path.join(root, name) if os.path.exists(path) and replace is False: return open(path) if is_disabled: return None files = api_run.files([name]) if len(files) == 0: return None # if the file does not exist, the file has an md5 of 0 if files[0].md5 == "0": raise ValueError(f"File {name} not found in {run_path or root}.") return files[0].download(root=root, replace=True)
python
wandb/sdk/wandb_run.py
3,642
3,695
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,882
finish
def finish(exit_code: Optional[int] = None, quiet: Optional[bool] = None) -> None: """Mark a run as finished, and finish uploading all data. This is used when creating multiple runs in the same process. We automatically call this method when your script exits. Arguments: exit_code: Set to something other than 0 to mark a run as failed quiet: Set to true to minimize log output """ if wandb.run: wandb.run.finish(exit_code=exit_code, quiet=quiet)
python
wandb/sdk/wandb_run.py
3,705
3,716
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,883
__init__
def __init__(self, base_artifact: "ArtifactInterface"): super().__setattr__("base_artifact", base_artifact)
python
wandb/sdk/wandb_run.py
3,722
3,723
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,884
__getattr__
def __getattr__(self, __name: str) -> Any: raise ArtifactNotLoggedError(artifact=self.base_artifact, attr=__name)
python
wandb/sdk/wandb_run.py
3,725
3,726
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,885
__setattr__
def __setattr__(self, __name: str, __value: Any) -> None: raise ArtifactNotLoggedError(artifact=self.base_artifact, attr=__name)
python
wandb/sdk/wandb_run.py
3,728
3,729
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,886
__bool__
def __bool__(self) -> bool: return False
python
wandb/sdk/wandb_run.py
3,731
3,732
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,887
__init__
def __init__(self, api: PublicApi, future: Any): self._api = api self._instance = InvalidArtifact(self) self._future = future
python
wandb/sdk/wandb_run.py
3,744
3,747
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,888
__getattr__
def __getattr__(self, item: str) -> Any: return getattr(self._instance, item)
python
wandb/sdk/wandb_run.py
3,749
3,750
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,889
wait
def wait(self, timeout: Optional[int] = None) -> ArtifactInterface: if not self._instance: future_get = self._future.get(timeout) if not future_get: raise WaitTimeoutError( "Artifact upload wait timed out, failed to fetch Artifact response" ) resp = future_get.response.log_artifact_response if resp.error_message: raise ValueError(resp.error_message) self._instance = public.Artifact.from_id(resp.artifact_id, self._api.client) assert isinstance( self._instance, ArtifactInterface ), "Insufficient permissions to fetch Artifact with id {} from {}".format( resp.artifact_id, self._api.client.app_url ) return self._instance
python
wandb/sdk/wandb_run.py
3,752
3,768
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,890
id
def id(self) -> Optional[str]: return self._instance.id
python
wandb/sdk/wandb_run.py
3,771
3,772
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,891
source_version
def source_version(self) -> Optional[str]: return self._instance.source_version
python
wandb/sdk/wandb_run.py
3,775
3,776
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,892
version
def version(self) -> str: return self._instance.version
python
wandb/sdk/wandb_run.py
3,779
3,780
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,893
name
def name(self) -> str: return self._instance.name
python
wandb/sdk/wandb_run.py
3,783
3,784
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,894
type
def type(self) -> str: return self._instance.type
python
wandb/sdk/wandb_run.py
3,787
3,788
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,895
entity
def entity(self) -> str: return self._instance.entity
python
wandb/sdk/wandb_run.py
3,791
3,792
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,896
project
def project(self) -> str: return self._instance.project
python
wandb/sdk/wandb_run.py
3,795
3,796
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,897
manifest
def manifest(self) -> "ArtifactManifest": return self._instance.manifest
python
wandb/sdk/wandb_run.py
3,799
3,800
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,898
digest
def digest(self) -> str: return self._instance.digest
python
wandb/sdk/wandb_run.py
3,803
3,804
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,899
state
def state(self) -> str: return self._instance.state
python
wandb/sdk/wandb_run.py
3,807
3,808
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
2,900
size
def size(self) -> int: return self._instance.size
python
wandb/sdk/wandb_run.py
3,811
3,812
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }