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,501 | __repr__ | def __repr__(self):
# use a copy of _dict, except add placeholders for h5 objects, etc.
# that haven't been loaded yet
repr_dict = dict(self._dict)
for k in self._json_dict:
v = self._json_dict[k]
if (
k not in repr_dict
and isinstance(v, dict)
and v.get("_type") in H5_TYPES
):
# unloaded h5 objects may be very large. use a placeholder for them
# if we haven't already loaded them
repr_dict[k] = "..."
else:
repr_dict[k] = self[k]
return repr(repr_dict) | python | wandb/old/summary.py | 146 | 163 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,502 | update | def update(self, key_vals=None, overwrite=True):
"""Locked keys will be overwritten unless overwrite=False.
Otherwise, written keys will be added to the "locked" list.
"""
if key_vals:
write_items = self._update(key_vals, overwrite)
self._root._root_set(self._path, write_items)
self._root._write(commit=True) | python | wandb/old/summary.py | 165 | 173 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,503 | _update | def _update(self, key_vals, overwrite):
if not key_vals:
return
key_vals = {k.strip(): v for k, v in key_vals.items()}
if overwrite:
write_items = list(key_vals.items())
self._locked_keys.update(key_vals.keys())
else:
write_keys = set(key_vals.keys()) - self._locked_keys
write_items = [(k, key_vals[k]) for k in write_keys]
for key, value in write_items:
if isinstance(value, dict):
self._dict[key] = SummarySubDict(self._root, self._path + (key,))
self._dict[key]._update(value, overwrite)
else:
self._dict[key] = value
return write_items | python | wandb/old/summary.py | 175 | 195 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,504 | __init__ | def __init__(self, run, summary=None):
super().__init__()
self._run = run
self._h5_path = os.path.join(self._run.dir, DEEP_SUMMARY_FNAME)
# Lazy load the h5 file
self._h5 = None
# Mirrored version of self._dict with versions of values that get written
# to JSON kept up to date by self._root_set() and self._root_del().
self._json_dict = {}
if summary is not None:
self._json_dict = summary | python | wandb/old/summary.py | 206 | 218 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,505 | _json_get | def _json_get(self, path):
pass | python | wandb/old/summary.py | 220 | 221 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,506 | _root_get | def _root_get(self, path, child_dict):
json_dict = self._json_dict
for key in path[:-1]:
json_dict = json_dict[key]
key = path[-1]
if key in json_dict:
child_dict[key] = self._decode(path, json_dict[key]) | python | wandb/old/summary.py | 223 | 230 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,507 | _root_del | def _root_del(self, path):
json_dict = self._json_dict
for key in path[:-1]:
json_dict = json_dict[key]
val = json_dict[path[-1]]
del json_dict[path[-1]]
if isinstance(val, dict) and val.get("_type") in H5_TYPES:
if not h5py:
wandb.termerror("Deleting tensors in summary requires h5py")
else:
self.open_h5()
h5_key = "summary/" + ".".join(path)
del self._h5[h5_key]
self._h5.flush() | python | wandb/old/summary.py | 232 | 246 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,508 | _root_set | def _root_set(self, path, new_keys_values):
json_dict = self._json_dict
for key in path:
json_dict = json_dict[key]
for new_key, new_value in new_keys_values:
json_dict[new_key] = self._encode(new_value, path + (new_key,)) | python | wandb/old/summary.py | 248 | 254 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,509 | write_h5 | def write_h5(self, path, val):
# ensure the file is open
self.open_h5()
if not self._h5:
wandb.termerror("Storing tensors in summary requires h5py")
else:
try:
del self._h5["summary/" + ".".join(path)]
except KeyError:
pass
self._h5["summary/" + ".".join(path)] = val
self._h5.flush() | python | wandb/old/summary.py | 256 | 268 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,510 | read_h5 | def read_h5(self, path, val=None):
# ensure the file is open
self.open_h5()
if not self._h5:
wandb.termerror("Reading tensors from summary requires h5py")
else:
return self._h5.get("summary/" + ".".join(path), val) | python | wandb/old/summary.py | 270 | 277 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,511 | open_h5 | def open_h5(self):
if not self._h5 and h5py:
self._h5 = h5py.File(self._h5_path, "a", libver="latest") | python | wandb/old/summary.py | 279 | 281 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,512 | _decode | def _decode(self, path, json_value):
"""Decode a `dict` encoded by `Summary._encode()`, loading h5 objects.
h5 objects may be very large, so we won't have loaded them automatically.
"""
if isinstance(json_value, dict):
if json_value.get("_type") in H5_TYPES:
return self.read_h5(path, json_value)
elif json_value.get("_type") == "data-frame":
wandb.termerror(
"This data frame was saved via the wandb data API. Contact support@wandb.com for help."
)
return None
# TODO: transform wandb objects and plots
else:
return SummarySubDict(self, path)
else:
return json_value | python | wandb/old/summary.py | 283 | 300 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,513 | _encode | def _encode(self, value, path_from_root):
"""Normalize, compress, and encode sub-objects for backend storage.
value: Object to encode.
path_from_root: `tuple` of key strings from the top-level summary to the
current `value`.
Returns:
A new tree of dict's with large objects replaced with dictionaries
with "_type" entries that say which type the original data was.
"""
# Constructs a new `dict` tree in `json_value` that discards and/or
# encodes objects that aren't JSON serializable.
if isinstance(value, dict):
json_value = {}
for key, value in value.items():
json_value[key] = self._encode(value, path_from_root + (key,))
return json_value
else:
path = ".".join(path_from_root)
friendly_value, converted = util.json_friendly(
val_to_json(self._run, path, value, namespace="summary")
)
json_value, compressed = util.maybe_compress_summary(
friendly_value, util.get_h5_typename(value)
)
if compressed:
self.write_h5(path_from_root, friendly_value)
return json_value | python | wandb/old/summary.py | 302 | 333 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,514 | download_h5 | def download_h5(run_id, entity=None, project=None, out_dir=None):
api = Api()
meta = api.download_url(
project or api.settings("project"),
DEEP_SUMMARY_FNAME,
entity=entity or api.settings("entity"),
run=run_id,
)
if meta and "md5" in meta and meta["md5"] is not None:
# TODO: make this non-blocking
wandb.termlog("Downloading summary data...")
path, res = api.download_write_file(meta, out_dir=out_dir)
return path | python | wandb/old/summary.py | 336 | 348 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,515 | upload_h5 | def upload_h5(file, run_id, entity=None, project=None):
api = Api()
wandb.termlog("Uploading summary data...")
with open(file, "rb") as f:
api.push(
{os.path.basename(file): f}, run=run_id, project=project, entity=entity
) | python | wandb/old/summary.py | 351 | 357 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,516 | __init__ | def __init__(self, run):
super().__init__(run)
self._fname = os.path.join(run.dir, wandb_lib.filenames.SUMMARY_FNAME)
self.load() | python | wandb/old/summary.py | 361 | 364 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,517 | load | def load(self):
try:
with open(self._fname) as f:
self._json_dict = json.load(f)
except (OSError, ValueError):
self._json_dict = {} | python | wandb/old/summary.py | 366 | 371 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,518 | _write | def _write(self, commit=False):
# TODO: we just ignore commit to ensure backward capability
with open(self._fname, "w") as f:
f.write(util.json_dumps_safer(self._json_dict))
f.write("\n")
f.flush()
os.fsync(f.fileno())
if self._h5:
self._h5.close()
self._h5 = None
if wandb.run and wandb.run._jupyter_agent:
wandb.run._jupyter_agent.start() | python | wandb/old/summary.py | 373 | 384 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,519 | __init__ | def __init__(self, run, client, summary=None):
super().__init__(run, summary=summary)
self._run = run
self._client = client
self._started = time.time() | python | wandb/old/summary.py | 388 | 392 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,520 | load | def load(self):
pass | python | wandb/old/summary.py | 394 | 395 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,521 | open_h5 | def open_h5(self):
if not self._h5 and h5py:
download_h5(
self._run.id,
entity=self._run.entity,
project=self._run.project,
out_dir=self._run.dir,
)
super().open_h5() | python | wandb/old/summary.py | 397 | 405 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,522 | _write | def _write(self, commit=False):
mutation = gql(
"""
mutation UpsertBucket( $id: String, $summaryMetrics: JSONString) {
upsertBucket(input: { id: $id, summaryMetrics: $summaryMetrics}) {
bucket { id }
}
}
"""
)
if commit:
if self._h5:
self._h5.close()
self._h5 = None
res = self._client.execute(
mutation,
variable_values={
"id": self._run.storage_id,
"summaryMetrics": util.json_dumps_safer(self._json_dict),
},
)
assert res["upsertBucket"]["bucket"]["id"]
entity, project, run = self._run.path
if (
os.path.exists(self._h5_path)
and os.path.getmtime(self._h5_path) >= self._started
):
upload_h5(self._h5_path, run, entity=entity, project=project)
else:
return False | python | wandb/old/summary.py | 407 | 436 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,523 | __init__ | def __init__(
self, load_settings: bool = True, root_dir: Optional[str] = None
) -> None:
self._global_settings = Settings._settings()
self._local_settings = Settings._settings()
self.root_dir = root_dir
if load_settings:
self._global_settings.read([Settings._global_path()])
# Only attempt to read if there is a directory existing
if os.path.isdir(core.wandb_dir(self.root_dir)):
self._local_settings.read([Settings._local_path(self.root_dir)]) | python | wandb/old/settings.py | 17 | 28 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,524 | get | def get(self, section: str, key: str, fallback: Any = _UNSET) -> Any:
# Try the local settings first. If we can't find the key, then try the global settings.
# If a fallback is provided, return it if we can't find the key in either the local or global
# settings.
try:
return self._local_settings.get(section, key)
except configparser.NoOptionError:
try:
return self._global_settings.get(section, key)
except configparser.NoOptionError:
if fallback is not Settings._UNSET:
return fallback
else:
raise | python | wandb/old/settings.py | 30 | 43 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,525 | set | def set(self, section, key, value, globally=False, persist=False) -> None:
"""Persist settings to disk if persist = True"""
def write_setting(settings, settings_path, persist):
if not settings.has_section(section):
Settings._safe_add_section(settings, Settings.DEFAULT_SECTION)
settings.set(section, key, str(value))
if persist:
with open(settings_path, "w+") as f:
settings.write(f)
if globally:
write_setting(self._global_settings, Settings._global_path(), persist)
else:
write_setting(
self._local_settings, Settings._local_path(self.root_dir), persist
) | python | wandb/old/settings.py | 45 | 61 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,526 | write_setting | def write_setting(settings, settings_path, persist):
if not settings.has_section(section):
Settings._safe_add_section(settings, Settings.DEFAULT_SECTION)
settings.set(section, key, str(value))
if persist:
with open(settings_path, "w+") as f:
settings.write(f) | python | wandb/old/settings.py | 48 | 54 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,527 | clear | def clear(self, section, key, globally=False, persist=False) -> None:
def clear_setting(settings, settings_path, persist):
settings.remove_option(section, key)
if persist:
with open(settings_path, "w+") as f:
settings.write(f)
if globally:
clear_setting(self._global_settings, Settings._global_path(), persist)
else:
clear_setting(
self._local_settings, Settings._local_path(self.root_dir), persist
) | python | wandb/old/settings.py | 63 | 75 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,528 | clear_setting | def clear_setting(settings, settings_path, persist):
settings.remove_option(section, key)
if persist:
with open(settings_path, "w+") as f:
settings.write(f) | python | wandb/old/settings.py | 64 | 68 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,529 | items | def items(self, section=None):
section = section if section is not None else Settings.DEFAULT_SECTION
result = {"section": section}
try:
if section in self._global_settings.sections():
for option in self._global_settings.options(section):
result[option] = self._global_settings.get(section, option)
if section in self._local_settings.sections():
for option in self._local_settings.options(section):
result[option] = self._local_settings.get(section, option)
except configparser.InterpolationSyntaxError:
core.termwarn("Unable to parse settings file")
return result | python | wandb/old/settings.py | 77 | 92 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,530 | _safe_add_section | def _safe_add_section(settings, section):
if not settings.has_section(section):
settings.add_section(section) | python | wandb/old/settings.py | 95 | 97 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,531 | _settings | def _settings(default_settings={}):
settings = configparser.ConfigParser()
Settings._safe_add_section(settings, Settings.DEFAULT_SECTION)
for key, value in default_settings.items():
settings.set(Settings.DEFAULT_SECTION, key, str(value))
return settings | python | wandb/old/settings.py | 100 | 105 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,532 | _global_path | def _global_path():
config_dir = os.environ.get(
env.CONFIG_DIR, os.path.join(os.path.expanduser("~"), ".config", "wandb")
)
os.makedirs(config_dir, exist_ok=True)
return os.path.join(config_dir, "settings") | python | wandb/old/settings.py | 108 | 113 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,533 | _local_path | def _local_path(root_dir=None):
filesystem.mkdir_exists_ok(core.wandb_dir(root_dir))
return os.path.join(core.wandb_dir(root_dir), "settings") | python | wandb/old/settings.py | 116 | 118 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,534 | cli_unsupported | def cli_unsupported(argument):
wandb.termerror(f"Unsupported argument `{argument}`")
sys.exit(1) | python | wandb/cli/cli.py | 79 | 81 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,535 | format_message | def format_message(self):
# log_file = util.get_log_file_path()
log_file = ""
orig_type = f"{self.orig_type.__module__}.{self.orig_type.__name__}"
if issubclass(self.orig_type, Error):
return click.style(str(self.message), fg="red")
else:
return (
f"An Exception was raised, see {log_file} for full traceback.\n"
f"{orig_type}: {self.message}"
) | python | wandb/cli/cli.py | 85 | 95 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,536 | display_error | def display_error(func):
"""Function decorator for catching common errors and re-raising as wandb.Error."""
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except wandb.Error as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
logger.error("".join(lines))
wandb.termerror(f"Find detailed error logs at: {_wandb_log_path}")
click_exc = ClickWandbException(e)
click_exc.orig_type = exc_type
raise click_exc.with_traceback(sys.exc_info()[2])
return wrapper | python | wandb/cli/cli.py | 98 | 114 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,537 | wrapper | def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except wandb.Error as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
logger.error("".join(lines))
wandb.termerror(f"Find detailed error logs at: {_wandb_log_path}")
click_exc = ClickWandbException(e)
click_exc.orig_type = exc_type
raise click_exc.with_traceback(sys.exc_info()[2]) | python | wandb/cli/cli.py | 102 | 112 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,538 | _get_cling_api | def _get_cling_api(reset=None):
"""Get a reference to the internal api with cling settings."""
global _api
if reset:
_api = None
wandb_sdk.wandb_setup._setup(_reset=True)
if _api is None:
# TODO(jhr): make a settings object that is better for non runs.
# only override the necessary setting
wandb.setup(settings=dict(_cli_only_mode=True))
_api = InternalApi()
return _api | python | wandb/cli/cli.py | 120 | 131 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,539 | prompt_for_project | def prompt_for_project(ctx, entity):
"""Ask the user for a project, creating one if necessary."""
result = ctx.invoke(projects, entity=entity, display=False)
api = _get_cling_api()
try:
if len(result) == 0:
project = click.prompt("Enter a name for your first project")
# description = editor()
project = api.upsert_project(project, entity=entity)["name"]
else:
project_names = [project["name"] for project in result] + ["Create New"]
wandb.termlog("Which project should we use?")
result = util.prompt_choices(project_names)
if result:
project = result
else:
project = "Create New"
# TODO: check with the server if the project exists
if project == "Create New":
project = click.prompt(
"Enter a name for your new project", value_proc=api.format_project
)
# description = editor()
project = api.upsert_project(project, entity=entity)["name"]
except wandb.errors.CommError as e:
raise ClickException(str(e))
return project | python | wandb/cli/cli.py | 134 | 162 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,540 | get_command | def get_command(self, ctx, cmd_name):
# TODO: check if cmd_name is a file in the current dir and not require `run`?
rv = click.Group.get_command(self, ctx, cmd_name)
if rv is not None:
return rv
return None | python | wandb/cli/cli.py | 167 | 172 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,541 | cli | def cli(ctx):
# wandb.try_to_set_up_global_logging()
if ctx.invoked_subcommand is None:
click.echo(ctx.get_help()) | python | wandb/cli/cli.py | 178 | 181 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,542 | projects | def projects(entity, display=True):
api = _get_cling_api()
projects = api.list_projects(entity=entity)
if len(projects) == 0:
message = "No projects found for %s" % entity
else:
message = 'Latest projects for "%s"' % entity
if display:
click.echo(click.style(message, bold=True))
for project in projects:
click.echo(
"".join(
(
click.style(project["name"], fg="blue", bold=True),
" - ",
str(project["description"] or "").split("\n")[0],
)
)
)
return projects | python | wandb/cli/cli.py | 193 | 212 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,543 | login | def login(key, host, cloud, relogin, anonymously, no_offline=False):
# TODO: handle no_offline
anon_mode = "must" if anonymously else "never"
wandb_sdk.wandb_login._handle_host_wandb_setting(host, cloud)
# A change in click or the test harness means key can be none...
key = key[0] if key is not None and len(key) > 0 else None
if key:
relogin = True
login_settings = dict(
_cli_only_mode=True,
_disable_viewer=relogin,
anonymous=anon_mode,
)
if host is not None:
login_settings["base_url"] = host
try:
wandb.setup(settings=login_settings)
except TypeError as e:
wandb.termerror(str(e))
sys.exit(1)
wandb.login(relogin=relogin, key=key, anonymous=anon_mode, host=host, force=True) | python | wandb/cli/cli.py | 224 | 248 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,544 | service | def service(
grpc_port=None,
sock_port=None,
port_filename=None,
address=None,
pid=None,
debug=False,
serve_sock=False,
serve_grpc=False,
):
from wandb.sdk.service.server import WandbServer
server = WandbServer(
grpc_port=grpc_port,
sock_port=sock_port,
port_fname=port_filename,
address=address,
pid=pid,
debug=debug,
serve_sock=serve_sock,
serve_grpc=serve_grpc,
)
server.serve() | python | wandb/cli/cli.py | 267 | 289 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,545 | init | def init(ctx, project, entity, reset, mode):
from wandb.old.core import __stage_dir__, _set_stage_dir, wandb_dir
if __stage_dir__ is None:
_set_stage_dir("wandb")
# non-interactive init
if reset or project or entity or mode:
api = InternalApi()
if reset:
api.clear_setting("entity", persist=True)
api.clear_setting("project", persist=True)
api.clear_setting("mode", persist=True)
# TODO(jhr): clear more settings?
if entity:
api.set_setting("entity", entity, persist=True)
if project:
api.set_setting("project", project, persist=True)
if mode:
api.set_setting("mode", mode, persist=True)
return
if os.path.isdir(wandb_dir()) and os.path.exists(
os.path.join(wandb_dir(), "settings")
):
click.confirm(
click.style(
"This directory has been configured previously, should we re-configure it?",
bold=True,
),
abort=True,
)
else:
click.echo(
click.style("Let's setup this directory for W&B!", fg="green", bold=True)
)
api = _get_cling_api()
if api.api_key is None:
ctx.invoke(login)
api = _get_cling_api(reset=True)
viewer = api.viewer()
# Viewer can be `None` in case your API information became invalid, or
# in testing if you switch hosts.
if not viewer:
click.echo(
click.style(
"Your login information seems to be invalid: can you log in again please?",
fg="red",
bold=True,
)
)
ctx.invoke(login)
api = _get_cling_api(reset=True)
# This shouldn't happen.
viewer = api.viewer()
if not viewer:
click.echo(
click.style(
"We're sorry, there was a problem logging you in. "
"Please send us a note at support@wandb.com and tell us how this happened.",
fg="red",
bold=True,
)
)
sys.exit(1)
# At this point we should be logged in successfully.
if len(viewer["teams"]["edges"]) > 1:
team_names = [e["node"]["name"] for e in viewer["teams"]["edges"]] + [
"Manual entry"
]
wandb.termlog(
"Which team should we use?",
)
result = util.prompt_choices(team_names)
# result can be empty on click
if result:
entity = result
else:
entity = "Manual Entry"
if entity == "Manual Entry":
entity = click.prompt("Enter the name of the team you want to use")
else:
entity = viewer.get("entity") or click.prompt(
"What username or team should we use?"
)
# TODO: this error handling sucks and the output isn't pretty
try:
project = prompt_for_project(ctx, entity)
except ClickWandbException:
raise ClickException(f"Could not find team: {entity}")
api.set_setting("entity", entity, persist=True)
api.set_setting("project", project, persist=True)
api.set_setting("base_url", api.settings().get("base_url"), persist=True)
filesystem.mkdir_exists_ok(wandb_dir())
with open(os.path.join(wandb_dir(), ".gitignore"), "w") as file:
file.write("*\n!settings")
click.echo(
click.style("This directory is configured! Next, track a run:\n", fg="green")
+ textwrap.dedent(
"""\
* In your training script:
{code1}
{code2}
* then `{run}`.
"""
).format(
code1=click.style("import wandb", bold=True),
code2=click.style('wandb.init(project="%s")' % project, bold=True),
run=click.style("python <train.py>", bold=True),
)
) | python | wandb/cli/cli.py | 308 | 426 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,546 | sync | def sync(
ctx,
path=None,
view=None,
verbose=None,
run_id=None,
project=None,
entity=None,
sync_tensorboard=None,
include_globs=None,
exclude_globs=None,
include_online=None,
include_offline=None,
include_synced=None,
mark_synced=None,
sync_all=None,
ignore=None,
show=None,
clean=None,
clean_old_hours=24,
clean_force=None,
append=None,
):
# TODO: rather unfortunate, needed to avoid creating a `wandb` directory
os.environ["WANDB_DIR"] = TMPDIR.name
api = _get_cling_api()
if api.api_key is None:
wandb.termlog("Login to W&B to sync offline runs")
ctx.invoke(login, no_offline=True)
api = _get_cling_api(reset=True)
if ignore:
exclude_globs = ignore
if include_globs:
include_globs = include_globs.split(",")
if exclude_globs:
exclude_globs = exclude_globs.split(",")
def _summary():
all_items = get_runs(
include_online=True,
include_offline=True,
include_synced=True,
include_unsynced=True,
)
sync_items = get_runs(
include_online=include_online if include_online is not None else True,
include_offline=include_offline if include_offline is not None else True,
include_synced=include_synced if include_synced is not None else False,
include_unsynced=True,
exclude_globs=exclude_globs,
include_globs=include_globs,
)
synced = []
unsynced = []
for item in all_items:
(synced if item.synced else unsynced).append(item)
if sync_items:
wandb.termlog(f"Number of runs to be synced: {len(sync_items)}")
if show and show < len(sync_items):
wandb.termlog(f"Showing {show} runs to be synced:")
for item in sync_items[: (show or len(sync_items))]:
wandb.termlog(f" {item}")
else:
wandb.termlog("No runs to be synced.")
if synced:
clean_cmd = click.style("wandb sync --clean", fg="yellow")
wandb.termlog(
f"NOTE: use {clean_cmd} to delete {len(synced)} synced runs from local directory."
)
if unsynced:
sync_cmd = click.style("wandb sync --sync-all", fg="yellow")
wandb.termlog(
f"NOTE: use {sync_cmd} to sync {len(unsynced)} unsynced runs from local directory."
)
def _sync_path(_path, _sync_tensorboard):
if run_id and len(_path) > 1:
wandb.termerror("id can only be set for a single run.")
sys.exit(1)
sm = SyncManager(
project=project,
entity=entity,
run_id=run_id,
mark_synced=mark_synced,
app_url=api.app_url,
view=view,
verbose=verbose,
sync_tensorboard=_sync_tensorboard,
log_path=_wandb_log_path,
append=append,
)
for p in _path:
sm.add(p)
sm.start()
while not sm.is_done():
_ = sm.poll()
def _sync_all():
sync_items = get_runs(
include_online=include_online if include_online is not None else True,
include_offline=include_offline if include_offline is not None else True,
include_synced=include_synced if include_synced is not None else False,
include_unsynced=True,
exclude_globs=exclude_globs,
include_globs=include_globs,
)
if not sync_items:
wandb.termerror("Nothing to sync.")
else:
# When syncing run directories, default to not syncing tensorboard
sync_tb = sync_tensorboard if sync_tensorboard is not None else False
_sync_path(sync_items, sync_tb)
def _clean():
if path:
runs = list(map(get_run_from_path, path))
if not clean_force:
click.confirm(
click.style(
f"Are you sure you want to remove {len(runs)} runs?",
bold=True,
),
abort=True,
)
for run in runs:
shutil.rmtree(run.path)
click.echo(click.style("Success!", fg="green"))
return
runs = get_runs(
include_online=include_online if include_online is not None else True,
include_offline=include_offline if include_offline is not None else True,
include_synced=include_synced if include_synced is not None else True,
include_unsynced=False,
exclude_globs=exclude_globs,
include_globs=include_globs,
)
since = datetime.datetime.now() - datetime.timedelta(hours=clean_old_hours)
old_runs = [run for run in runs if run.datetime < since]
old_runs.sort(key=lambda _run: _run.datetime)
if old_runs:
click.echo(
f"Found {len(runs)} runs, {len(old_runs)} are older than {clean_old_hours} hours"
)
for run in old_runs:
click.echo(run.path)
if not clean_force:
click.confirm(
click.style(
f"Are you sure you want to remove {len(old_runs)} runs?",
bold=True,
),
abort=True,
)
for run in old_runs:
shutil.rmtree(run.path)
click.echo(click.style("Success!", fg="green"))
else:
click.echo(
click.style(
f"No runs older than {clean_old_hours} hours found", fg="red"
)
)
if sync_all:
_sync_all()
elif clean:
_clean()
elif path:
# When syncing a specific path, default to syncing tensorboard
sync_tb = sync_tensorboard if sync_tensorboard is not None else True
_sync_path(path, sync_tb)
else:
_summary() | python | wandb/cli/cli.py | 489 | 662 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,547 | _summary | def _summary():
all_items = get_runs(
include_online=True,
include_offline=True,
include_synced=True,
include_unsynced=True,
)
sync_items = get_runs(
include_online=include_online if include_online is not None else True,
include_offline=include_offline if include_offline is not None else True,
include_synced=include_synced if include_synced is not None else False,
include_unsynced=True,
exclude_globs=exclude_globs,
include_globs=include_globs,
)
synced = []
unsynced = []
for item in all_items:
(synced if item.synced else unsynced).append(item)
if sync_items:
wandb.termlog(f"Number of runs to be synced: {len(sync_items)}")
if show and show < len(sync_items):
wandb.termlog(f"Showing {show} runs to be synced:")
for item in sync_items[: (show or len(sync_items))]:
wandb.termlog(f" {item}")
else:
wandb.termlog("No runs to be synced.")
if synced:
clean_cmd = click.style("wandb sync --clean", fg="yellow")
wandb.termlog(
f"NOTE: use {clean_cmd} to delete {len(synced)} synced runs from local directory."
)
if unsynced:
sync_cmd = click.style("wandb sync --sync-all", fg="yellow")
wandb.termlog(
f"NOTE: use {sync_cmd} to sync {len(unsynced)} unsynced runs from local directory."
) | python | wandb/cli/cli.py | 527 | 563 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,548 | _sync_path | def _sync_path(_path, _sync_tensorboard):
if run_id and len(_path) > 1:
wandb.termerror("id can only be set for a single run.")
sys.exit(1)
sm = SyncManager(
project=project,
entity=entity,
run_id=run_id,
mark_synced=mark_synced,
app_url=api.app_url,
view=view,
verbose=verbose,
sync_tensorboard=_sync_tensorboard,
log_path=_wandb_log_path,
append=append,
)
for p in _path:
sm.add(p)
sm.start()
while not sm.is_done():
_ = sm.poll() | python | wandb/cli/cli.py | 565 | 585 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,549 | _sync_all | def _sync_all():
sync_items = get_runs(
include_online=include_online if include_online is not None else True,
include_offline=include_offline if include_offline is not None else True,
include_synced=include_synced if include_synced is not None else False,
include_unsynced=True,
exclude_globs=exclude_globs,
include_globs=include_globs,
)
if not sync_items:
wandb.termerror("Nothing to sync.")
else:
# When syncing run directories, default to not syncing tensorboard
sync_tb = sync_tensorboard if sync_tensorboard is not None else False
_sync_path(sync_items, sync_tb) | python | wandb/cli/cli.py | 587 | 601 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,550 | _clean | def _clean():
if path:
runs = list(map(get_run_from_path, path))
if not clean_force:
click.confirm(
click.style(
f"Are you sure you want to remove {len(runs)} runs?",
bold=True,
),
abort=True,
)
for run in runs:
shutil.rmtree(run.path)
click.echo(click.style("Success!", fg="green"))
return
runs = get_runs(
include_online=include_online if include_online is not None else True,
include_offline=include_offline if include_offline is not None else True,
include_synced=include_synced if include_synced is not None else True,
include_unsynced=False,
exclude_globs=exclude_globs,
include_globs=include_globs,
)
since = datetime.datetime.now() - datetime.timedelta(hours=clean_old_hours)
old_runs = [run for run in runs if run.datetime < since]
old_runs.sort(key=lambda _run: _run.datetime)
if old_runs:
click.echo(
f"Found {len(runs)} runs, {len(old_runs)} are older than {clean_old_hours} hours"
)
for run in old_runs:
click.echo(run.path)
if not clean_force:
click.confirm(
click.style(
f"Are you sure you want to remove {len(old_runs)} runs?",
bold=True,
),
abort=True,
)
for run in old_runs:
shutil.rmtree(run.path)
click.echo(click.style("Success!", fg="green"))
else:
click.echo(
click.style(
f"No runs older than {clean_old_hours} hours found", fg="red"
)
) | python | wandb/cli/cli.py | 603 | 651 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,551 | sweep | def sweep(
ctx,
project,
entity,
controller,
verbose,
name,
program,
settings,
update,
launch_config, # TODO(gst): deprecate
stop,
cancel,
pause,
resume,
config_yaml_or_sweep_id,
queue,
project_queue,
):
state_args = "stop", "cancel", "pause", "resume"
lcls = locals()
is_state_change_command = sum(lcls[k] for k in state_args)
if is_state_change_command > 1:
raise Exception("Only one state flag (stop/cancel/pause/resume) is allowed.")
elif is_state_change_command == 1:
sweep_id = config_yaml_or_sweep_id
api = _get_cling_api()
if api.api_key is None:
wandb.termlog("Login to W&B to use the sweep feature")
ctx.invoke(login, no_offline=True)
api = _get_cling_api(reset=True)
parts = dict(entity=entity, project=project, name=sweep_id)
err = util.parse_sweep_id(parts)
if err:
wandb.termerror(err)
return
entity = parts.get("entity") or entity
project = parts.get("project") or project
sweep_id = parts.get("name") or sweep_id
state = [s for s in state_args if lcls[s]][0]
ings = {
"stop": "Stopping",
"cancel": "Cancelling",
"pause": "Pausing",
"resume": "Resuming",
}
wandb.termlog(
"{} sweep {}.".format(ings[state], f"{entity}/{project}/{sweep_id}")
)
getattr(api, "%s_sweep" % state)(sweep_id, entity=entity, project=project)
wandb.termlog("Done.")
return
else:
config_yaml = config_yaml_or_sweep_id
def _parse_settings(settings):
"""Parse settings from json or comma separated assignments."""
ret = {}
# TODO(jhr): merge with magic:_parse_magic
if settings.find("=") > 0:
for item in settings.split(","):
kv = item.split("=")
if len(kv) != 2:
wandb.termwarn(
"Unable to parse sweep settings key value pair", repeat=False
)
ret.update(dict([kv]))
return ret
wandb.termwarn("Unable to parse settings parameter", repeat=False)
return ret
api = _get_cling_api()
if api.api_key is None:
wandb.termlog("Login to W&B to use the sweep feature")
ctx.invoke(login, no_offline=True)
api = _get_cling_api(reset=True)
sweep_obj_id = None
if update:
parts = dict(entity=entity, project=project, name=update)
err = util.parse_sweep_id(parts)
if err:
wandb.termerror(err)
return
entity = parts.get("entity") or entity
project = parts.get("project") or project
sweep_id = parts.get("name") or update
has_project = (project or api.settings("project")) is not None
has_entity = (entity or api.settings("entity")) is not None
termerror_msg = (
"Sweep lookup requires a valid %s, and none was specified. \n"
"Either set a default %s in wandb/settings, or, if invoking \n`wandb sweep` "
"from the command line, specify the full sweep path via: \n\n"
" wandb sweep {username}/{projectname}/{sweepid}\n\n"
)
if not has_entity:
wandb.termerror(termerror_msg % (("entity",) * 2))
return
if not has_project:
wandb.termerror(termerror_msg % (("project",) * 2))
return
found = api.sweep(sweep_id, "{}", entity=entity, project=project)
if not found:
wandb.termerror(f"Could not find sweep {entity}/{project}/{sweep_id}")
return
sweep_obj_id = found["id"]
wandb.termlog(
"{} sweep from: {}".format(
"Updating" if sweep_obj_id else "Creating", config_yaml
)
)
try:
yaml_file = open(config_yaml)
except OSError:
wandb.termerror("Couldn't open sweep file: %s" % config_yaml)
return
try:
config = util.load_yaml(yaml_file)
except yaml.YAMLError as err:
wandb.termerror("Error in configuration file: %s" % err)
return
if config is None:
wandb.termerror("Configuration file is empty")
return
# Set or override parameters
if name:
config["name"] = name
if program:
config["program"] = program
if settings:
settings = _parse_settings(settings)
if settings:
config.setdefault("settings", {})
config["settings"].update(settings)
if controller:
config.setdefault("controller", {})
config["controller"]["type"] = "local"
is_local = config.get("controller", {}).get("type") == "local"
if is_local:
from wandb import controller as wandb_controller
tuner = wandb_controller()
err = tuner._validate(config)
if err:
wandb.termerror("Error in sweep file: %s" % err)
return
env = os.environ
entity = (
entity
or env.get("WANDB_ENTITY")
or config.get("entity")
or api.settings("entity")
)
project = (
project
or env.get("WANDB_PROJECT")
or config.get("project")
or api.settings("project")
or util.auto_project_name(config.get("program"))
)
_launch_scheduler_spec = None
if launch_config is not None or queue:
if launch_config:
launch_config = util.load_json_yaml_dict(launch_config)
if launch_config is None:
raise LaunchError(
f"Invalid format for launch config at {launch_config}"
)
else:
launch_config = {}
wandb.termlog(f"Using launch 🚀 with config: {launch_config}")
if entity is None:
_msg = "Must specify --entity flag when using launch."
wandb.termerror(_msg)
raise LaunchError(_msg)
elif project is None:
_msg = "A project must be configured when using launch."
wandb.termerror(_msg)
raise LaunchError(_msg)
# Try and get job from sweep config
_job = config.get("job")
_image_uri = config.get("image_uri")
if not _job and not _image_uri: # don't allow empty string
raise LaunchError("No 'job' or 'image_uri' found in sweep config")
elif _job and _image_uri:
raise LaunchError("Sweep has both 'job' and 'image_uri'")
if not queue:
if launch_config.get("queue"):
queue = launch_config["queue"]
else:
raise LaunchError(
"No queue passed from CLI or in launch config for launch-sweep."
)
scheduler_config = launch_config.get("scheduler", {})
num_workers = f'{scheduler_config.get("num_workers")}'
if num_workers is None or not str.isdigit(num_workers):
num_workers = "8"
scheduler_entrypoint = [
"wandb",
"scheduler",
"WANDB_SWEEP_ID",
"--queue",
f"{queue!r}",
"--project",
project,
"--num_workers",
num_workers,
]
if _job:
if ":" not in _job:
wandb.termwarn("No alias specified for job, defaulting to 'latest'")
_job += ":latest"
scheduler_entrypoint += [
"--job",
_job,
]
elif _image_uri:
scheduler_entrypoint += ["--image_uri", _image_uri]
# Launch job spec for the Scheduler
_launch_scheduler_spec = json.dumps(
{
"queue": queue,
"run_queue_project": project_queue,
"run_spec": json.dumps(
construct_launch_spec(
uri=SCHEDULER_URI,
job=None,
api=api,
name="Scheduler.WANDB_SWEEP_ID",
project=project,
entity=entity,
docker_image=scheduler_config.get("docker_image"),
resource=scheduler_config.get("resource", "local-process"),
entry_point=scheduler_entrypoint,
version=None,
parameters=None,
resource_args=scheduler_config.get("resource_args", {}),
launch_config=None,
run_id=None,
repository=launch_config.get("registry", {}).get("url", None),
)
),
}
)
sweep_id, warnings = api.upsert_sweep(
config,
project=project,
entity=entity,
obj_id=sweep_obj_id,
launch_scheduler=_launch_scheduler_spec,
)
util.handle_sweep_config_violations(warnings)
wandb.termlog(
"{} sweep with ID: {}".format(
"Updated" if sweep_obj_id else "Created", click.style(sweep_id, fg="yellow")
)
)
sweep_url = wandb_sdk.wandb_sweep._get_sweep_url(api, sweep_id)
if sweep_url:
wandb.termlog(
"View sweep at: {}".format(
click.style(sweep_url, underline=True, fg="blue")
)
)
# re-probe entity and project if it was auto-detected by upsert_sweep
entity = entity or env.get("WANDB_ENTITY")
project = project or env.get("WANDB_PROJECT")
if entity and project:
sweep_path = f"{entity}/{project}/{sweep_id}"
elif project:
sweep_path = f"{project}/{sweep_id}"
else:
sweep_path = sweep_id
if sweep_path.find(" ") >= 0:
sweep_path = f"{sweep_path!r}"
if launch_config is not None or queue:
wandb.termlog("Scheduler added to launch queue. Starting sweep...")
else:
wandb.termlog(
"Run sweep agent with: {}".format(
click.style("wandb agent %s" % sweep_path, fg="yellow")
)
)
if controller:
wandb.termlog("Starting wandb controller...")
from wandb import controller as wandb_controller
tuner = wandb_controller(sweep_id)
tuner.run(verbose=verbose) | python | wandb/cli/cli.py | 718 | 1,031 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,552 | _parse_settings | def _parse_settings(settings):
"""Parse settings from json or comma separated assignments."""
ret = {}
# TODO(jhr): merge with magic:_parse_magic
if settings.find("=") > 0:
for item in settings.split(","):
kv = item.split("=")
if len(kv) != 2:
wandb.termwarn(
"Unable to parse sweep settings key value pair", repeat=False
)
ret.update(dict([kv]))
return ret
wandb.termwarn("Unable to parse settings parameter", repeat=False)
return ret | python | wandb/cli/cli.py | 773 | 787 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,553 | launch | def launch(
uri,
job,
entry_point,
git_version,
args_list,
name,
resource,
entity,
project,
docker_image,
config,
queue,
run_async,
resource_args,
build,
repository,
project_queue,
):
"""Start a W&B run from the given URI.
The URI can bea wandb URI, a GitHub repo uri, or a local path). In the case of a
wandb URI the arguments used in the original run will be used by default. These
arguments can be overridden using the args option, or specifying those arguments in
the config's 'overrides' key, 'args' field as a list of strings.
Running `wandb launch [URI]` will launch the run directly. To add the run to a
queue, run `wandb launch [URI] --queue [optional queuename]`.
"""
logger.info(
f"=== Launch called with kwargs {locals()} CLI Version: {wandb.__version__}==="
)
wandb._sentry.configure_scope(process_context="launch_cli")
from wandb.sdk.launch import launch as wandb_launch
wandb.termlog(
f"W&B launch is in an experimental state and usage APIs may change without warning. See {wburls.get('cli_launch')}"
)
api = _get_cling_api()
if run_async and queue is not None:
raise LaunchError(
"Cannot use both --async and --queue with wandb launch, see help for details."
)
args_dict = util._user_args_to_dict(args_list)
if resource_args is not None:
resource_args = util.load_json_yaml_dict(resource_args)
if resource_args is None:
raise LaunchError("Invalid format for resource-args")
else:
resource_args = {}
if entry_point is not None:
entry_point = shlex.split(entry_point)
if config is not None:
config = util.load_json_yaml_dict(config)
if config is None:
raise LaunchError("Invalid format for config")
else:
config = {}
resource = resource or config.get("resource")
if build and queue is None:
raise LaunchError("Build flag requires a queue to be set")
try:
check_logged_in(api)
except Exception:
wandb.termerror(f"Error running job: {traceback.format_exc()}")
run_id = config.get("run_id")
if queue is None:
# direct launch
try:
wandb_launch.run(
api,
uri,
job,
entry_point,
git_version,
project=project,
entity=entity,
docker_image=docker_image,
name=name,
parameters=args_dict,
resource=resource,
resource_args=resource_args,
config=config,
synchronous=(not run_async),
run_id=run_id,
repository=repository,
)
except LaunchError as e:
logger.error("=== %s ===", e)
wandb._sentry.exception(e)
sys.exit(e)
except ExecutionError as e:
logger.error("=== %s ===", e)
wandb._sentry.exception(e)
sys.exit(e)
else:
try:
_launch_add(
api,
uri,
job,
config,
project,
entity,
queue,
resource,
entry_point,
name,
git_version,
docker_image,
args_dict,
project_queue,
resource_args,
build=build,
run_id=run_id,
repository=repository,
)
except Exception as e:
wandb._sentry.exception(e)
raise e | python | wandb/cli/cli.py | 1,168 | 1,297 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,554 | launch_agent | def launch_agent(
ctx,
project=None,
entity=None,
queues=None,
max_jobs=None,
config=None,
url=None,
):
logger.info(
f"=== Launch-agent called with kwargs {locals()} CLI Version: {wandb.__version__} ==="
)
wandb._sentry.configure_scope(process_context="launch_agent")
if url is not None:
raise LaunchError(
"--url is not supported in this version, upgrade with: pip install -u wandb"
)
from wandb.sdk.launch import launch as wandb_launch
wandb.termlog(
f"W&B launch is in an experimental state and usage APIs may change without warning. See {wburls.get('cli_launch')}"
)
api = _get_cling_api()
agent_config, api = wandb_launch.resolve_agent_config(
api, entity, project, max_jobs, queues, config
)
if agent_config.get("project") is None:
raise LaunchError(
"You must specify a project name or set WANDB_PROJECT environment variable."
)
if len(agent_config.get("queues")) == 0:
raise LaunchError(
"To launch an agent please specify a queue or a list of queues in the configuration file or cli."
)
check_logged_in(api)
wandb.termlog("Starting launch agent ✨")
try:
wandb_launch.create_and_run_agent(api, agent_config)
except Exception as e:
wandb._sentry.exception(e)
raise e | python | wandb/cli/cli.py | 1,344 | 1,388 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,555 | agent | def agent(ctx, project, entity, count, sweep_id):
api = _get_cling_api()
if api.api_key is None:
wandb.termlog("Login to W&B to use the sweep agent feature")
ctx.invoke(login, no_offline=True)
api = _get_cling_api(reset=True)
wandb.termlog("Starting wandb agent 🕵️")
wandb_agent.agent(sweep_id, entity=entity, project=project, count=count)
# you can send local commands like so:
# agent_api.command({'type': 'run', 'program': 'train.py',
# 'args': ['--max_epochs=10']}) | python | wandb/cli/cli.py | 1,400 | 1,412 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,556 | scheduler | def scheduler(
ctx,
sweep_id,
):
api = _get_cling_api()
if api.api_key is None:
wandb.termlog("Login to W&B to use the sweep scheduler feature")
ctx.invoke(login, no_offline=True)
api = _get_cling_api(reset=True)
wandb._sentry.configure_scope(process_context="sweep_scheduler")
wandb.termlog("Starting a Launch Scheduler 🚀")
from wandb.sdk.launch.sweeps import load_scheduler
# TODO(gst): remove this monstrosity
# Future-proofing hack to pull any kwargs that get passed in through the CLI
kwargs = {}
for i, _arg in enumerate(ctx.args):
if isinstance(_arg, str) and _arg.startswith("--"):
# convert input kwargs from hyphens to underscores
_key = _arg[2:].replace("-", "_")
_args = ctx.args[i + 1]
if str.isdigit(_args):
_args = int(_args)
kwargs[_key] = _args
try:
_scheduler = load_scheduler("sweep")(
api,
sweep_id=sweep_id,
**kwargs,
)
_scheduler.start()
except Exception as e:
wandb._sentry.exception(e)
raise e | python | wandb/cli/cli.py | 1,421 | 1,455 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,557 | controller | def controller(verbose, sweep_id):
click.echo("Starting wandb controller...")
from wandb import controller as wandb_controller
tuner = wandb_controller(sweep_id)
tuner.run(verbose=verbose) | python | wandb/cli/cli.py | 1,462 | 1,467 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,558 | docker_run | def docker_run(ctx, docker_run_args):
"""Wrap `docker run` and adds WANDB_API_KEY and WANDB_DOCKER environment variables.
This will also set the runtime to nvidia if the nvidia-docker executable is present
on the system and --runtime wasn't set.
See `docker run --help` for more details.
"""
api = InternalApi()
args = list(docker_run_args)
if len(args) > 0 and args[0] == "run":
args.pop(0)
if len([a for a in args if a.startswith("--runtime")]) == 0 and find_executable(
"nvidia-docker"
):
args = ["--runtime", "nvidia"] + args
# TODO: image_from_docker_args uses heuristics to find the docker image arg, there are likely cases
# where this won't work
image = util.image_from_docker_args(args)
resolved_image = None
if image:
resolved_image = wandb.docker.image_id(image)
if resolved_image:
args = ["-e", "WANDB_DOCKER=%s" % resolved_image] + args
else:
wandb.termlog(
"Couldn't detect image argument, running command without the WANDB_DOCKER env variable"
)
if api.api_key:
args = ["-e", "WANDB_API_KEY=%s" % api.api_key] + args
else:
wandb.termlog(
"Not logged in, run `wandb login` from the host machine to enable result logging"
)
subprocess.call(["docker", "run"] + args) | python | wandb/cli/cli.py | 1,473 | 1,507 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,559 | docker | def docker(
ctx,
docker_run_args,
docker_image,
nvidia,
digest,
jupyter,
dir,
no_dir,
shell,
port,
cmd,
no_tty,
):
"""Run your code in a docker container.
W&B docker lets you run your code in a docker image ensuring wandb is configured. It
adds the WANDB_DOCKER and WANDB_API_KEY environment variables to your container and
mounts the current directory in /app by default. You can pass additional args which
will be added to `docker run` before the image name is declared, we'll choose a
default image for you if one isn't passed:
```sh
wandb docker -v /mnt/dataset:/app/data
wandb docker gcr.io/kubeflow-images-public/tensorflow-1.12.0-notebook-cpu:v0.4.0 --jupyter
wandb docker wandb/deepo:keras-gpu --no-tty --cmd "python train.py --epochs=5"
```
By default, we override the entrypoint to check for the existence of wandb and
install it if not present. If you pass the --jupyter flag we will ensure jupyter is
installed and start jupyter lab on port 8888. If we detect nvidia-docker on your
system we will use the nvidia runtime. If you just want wandb to set environment
variable to an existing docker run command, see the wandb docker-run command.
"""
api = InternalApi()
if not find_executable("docker"):
raise ClickException("Docker not installed, install it from https://docker.com")
args = list(docker_run_args)
image = docker_image or ""
# remove run for users used to nvidia-docker
if len(args) > 0 and args[0] == "run":
args.pop(0)
if image == "" and len(args) > 0:
image = args.pop(0)
# If the user adds docker args without specifying an image (should be rare)
if not util.docker_image_regex(image.split("@")[0]):
if image:
args = args + [image]
image = wandb.docker.default_image(gpu=nvidia)
subprocess.call(["docker", "pull", image])
_, repo_name, tag = wandb.docker.parse(image)
resolved_image = wandb.docker.image_id(image)
if resolved_image is None:
raise ClickException(
"Couldn't find image locally or in a registry, try running `docker pull %s`"
% image
)
if digest:
sys.stdout.write(resolved_image)
exit(0)
existing = wandb.docker.shell(["ps", "-f", "ancestor=%s" % resolved_image, "-q"])
if existing:
if click.confirm(
"Found running container with the same image, do you want to attach?"
):
subprocess.call(["docker", "attach", existing.split("\n")[0]])
exit(0)
cwd = os.getcwd()
command = [
"docker",
"run",
"-e",
"LANG=C.UTF-8",
"-e",
"WANDB_DOCKER=%s" % resolved_image,
"--ipc=host",
"-v",
wandb.docker.entrypoint + ":/wandb-entrypoint.sh",
"--entrypoint",
"/wandb-entrypoint.sh",
]
if nvidia:
command.extend(["--runtime", "nvidia"])
if not no_dir:
# TODO: We should default to the working directory if defined
command.extend(["-v", cwd + ":" + dir, "-w", dir])
if api.api_key:
command.extend(["-e", "WANDB_API_KEY=%s" % api.api_key])
else:
wandb.termlog(
"Couldn't find WANDB_API_KEY, run `wandb login` to enable streaming metrics"
)
if jupyter:
command.extend(["-e", "WANDB_ENSURE_JUPYTER=1", "-p", port + ":8888"])
no_tty = True
cmd = (
"jupyter lab --no-browser --ip=0.0.0.0 --allow-root --NotebookApp.token= --notebook-dir %s"
% dir
)
command.extend(args)
if no_tty:
command.extend([image, shell, "-c", cmd])
else:
if cmd:
command.extend(["-e", "WANDB_COMMAND=%s" % cmd])
command.extend(["-it", image, shell])
wandb.termlog("Launching docker container \U0001F6A2")
subprocess.call(command) | python | wandb/cli/cli.py | 1,538 | 1,647 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,560 | local | def local(ctx, *args, **kwargs):
wandb.termwarn("`wandb local` has been replaced with `wandb server start`.")
ctx.invoke(start, *args, **kwargs) | python | wandb/cli/cli.py | 1,670 | 1,672 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,561 | server | def server():
pass | python | wandb/cli/cli.py | 1,676 | 1,677 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,562 | start | def start(ctx, port, env, daemon, upgrade, edge):
api = InternalApi()
if not find_executable("docker"):
raise ClickException("Docker not installed, install it from https://docker.com")
local_image_sha = wandb.docker.image_id("wandb/local").split("wandb/local")[-1]
registry_image_sha = wandb.docker.image_id_from_registry("wandb/local").split(
"wandb/local"
)[-1]
if local_image_sha != registry_image_sha:
if upgrade:
subprocess.call(["docker", "pull", "wandb/local"])
else:
wandb.termlog(
"A new version of the W&B server is available, upgrade by calling `wandb server start --upgrade`"
)
running = subprocess.check_output(
["docker", "ps", "--filter", "name=wandb-local", "--format", "{{.ID}}"]
)
if running != b"":
if upgrade:
subprocess.call(["docker", "stop", "wandb-local"])
else:
wandb.termerror(
"A container named wandb-local is already running, run `docker stop wandb-local` if you want to start a new instance"
)
exit(1)
image = "docker.pkg.github.com/wandb/core/local" if edge else "wandb/local"
username = getpass.getuser()
env_vars = ["-e", "LOCAL_USERNAME=%s" % username]
for e in env:
env_vars.append("-e")
env_vars.append(e)
command = [
"docker",
"run",
"--rm",
"-v",
"wandb:/vol",
"-p",
port + ":8080",
"--name",
"wandb-local",
] + env_vars
host = f"http://localhost:{port}"
api.set_setting("base_url", host, globally=True, persist=True)
if daemon:
command += ["-d"]
command += [image]
# DEVNULL is only in py3
try:
from subprocess import DEVNULL
except ImportError:
DEVNULL = open(os.devnull, "wb") # noqa: N806
code = subprocess.call(command, stdout=DEVNULL)
if daemon:
if code != 0:
wandb.termerror(
"Failed to launch the W&B server container, see the above error."
)
exit(1)
else:
wandb.termlog("W&B server started at http://localhost:%s \U0001F680" % port)
wandb.termlog("You can stop the server by running `wandb server stop`")
if not api.api_key:
# Let the server start before potentially launching a browser
time.sleep(2)
ctx.invoke(login, host=host) | python | wandb/cli/cli.py | 1,702 | 1,769 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,563 | stop | def stop():
if not find_executable("docker"):
raise ClickException("Docker not installed, install it from https://docker.com")
subprocess.call(["docker", "stop", "wandb-local"]) | python | wandb/cli/cli.py | 1,773 | 1,776 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,564 | artifact | def artifact():
pass | python | wandb/cli/cli.py | 1,780 | 1,781 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,565 | put | def put(path, name, description, type, alias):
if name is None:
name = os.path.basename(path)
public_api = PublicApi()
entity, project, artifact_name = public_api._parse_artifact_path(name)
if project is None:
project = click.prompt("Enter the name of the project you want to use")
# TODO: settings nightmare...
api = InternalApi()
api.set_setting("entity", entity)
api.set_setting("project", project)
artifact = wandb.Artifact(name=artifact_name, type=type, description=description)
artifact_path = "{entity}/{project}/{name}:{alias}".format(
entity=entity, project=project, name=artifact_name, alias=alias[0]
)
if os.path.isdir(path):
wandb.termlog(
'Uploading directory {path} to: "{artifact_path}" ({type})'.format(
path=path, type=type, artifact_path=artifact_path
)
)
artifact.add_dir(path)
elif os.path.isfile(path):
wandb.termlog(
'Uploading file {path} to: "{artifact_path}" ({type})'.format(
path=path, type=type, artifact_path=artifact_path
)
)
artifact.add_file(path)
elif "://" in path:
wandb.termlog(
'Logging reference artifact from {path} to: "{artifact_path}" ({type})'.format(
path=path, type=type, artifact_path=artifact_path
)
)
artifact.add_reference(path)
else:
raise ClickException("Path argument must be a file or directory")
run = wandb.init(
entity=entity, project=project, config={"path": path}, job_type="cli_put"
)
# We create the artifact manually to get the current version
res, _ = api.create_artifact(
type,
artifact_name,
artifact.digest,
client_id=artifact._client_id,
sequence_client_id=artifact._sequence_client_id,
entity_name=entity,
project_name=project,
run_name=run.id,
description=description,
aliases=[{"artifactCollectionName": artifact_name, "alias": a} for a in alias],
)
artifact_path = artifact_path.split(":")[0] + ":" + res.get("version", "latest")
# Re-create the artifact and actually upload any files needed
run.log_artifact(artifact, aliases=alias)
artifact.wait()
wandb.termlog(
"Artifact uploaded, use this artifact in a run by adding:\n", prefix=False
)
wandb.termlog(
' artifact = run.use_artifact("{path}")\n'.format(
path=artifact_path,
),
prefix=False,
) | python | wandb/cli/cli.py | 1,799 | 1,868 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,566 | get | def get(path, root, type):
public_api = PublicApi()
entity, project, artifact_name = public_api._parse_artifact_path(path)
if project is None:
project = click.prompt("Enter the name of the project you want to use")
try:
artifact_parts = artifact_name.split(":")
if len(artifact_parts) > 1:
version = artifact_parts[1]
artifact_name = artifact_parts[0]
else:
version = "latest"
full_path = "{entity}/{project}/{artifact}:{version}".format(
entity=entity, project=project, artifact=artifact_name, version=version
)
wandb.termlog(
"Downloading {type} artifact {full_path}".format(
type=type or "dataset", full_path=full_path
)
)
artifact = public_api.artifact(full_path, type=type)
path = artifact.download(root=root)
wandb.termlog("Artifact downloaded to %s" % path)
except ValueError:
raise ClickException("Unable to download artifact") | python | wandb/cli/cli.py | 1,876 | 1,901 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,567 | ls | def ls(path, type):
public_api = PublicApi()
if type is not None:
types = [public_api.artifact_type(type, path)]
else:
types = public_api.artifact_types(path)
for kind in types:
for collection in kind.collections():
versions = public_api.artifact_versions(
kind.type,
"/".join([kind.entity, kind.project, collection.name]),
per_page=1,
)
latest = next(versions)
print(
"{:<15s}{:<15s}{:>15s} {:<20s}".format(
kind.type,
latest.updated_at,
util.to_human_size(latest.size),
latest.name,
)
) | python | wandb/cli/cli.py | 1,910 | 1,932 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,568 | cache | def cache():
pass | python | wandb/cli/cli.py | 1,936 | 1,937 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,569 | cleanup | def cleanup(target_size):
target_size = util.from_human_size(target_size)
cache = wandb_sdk.wandb_artifacts.get_artifacts_cache()
reclaimed_bytes = cache.cleanup(target_size)
print(f"Reclaimed {util.to_human_size(reclaimed_bytes)} of space") | python | wandb/cli/cli.py | 1,946 | 1,950 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,570 | pull | def pull(run, project, entity):
api = InternalApi()
project, run = api.parse_slug(run, project=project)
urls = api.download_urls(project, run=run, entity=entity)
if len(urls) == 0:
raise ClickException("Run has no files")
click.echo(
"Downloading: {project}/{run}".format(
project=click.style(project, bold=True), run=run
)
)
for name in urls:
if api.file_current(name, urls[name]["md5"]):
click.echo("File %s is up to date" % name)
else:
length, response = api.download_file(urls[name]["url"])
# TODO: I had to add this because some versions in CI broke click.progressbar
sys.stdout.write("File %s\r" % name)
dirname = os.path.dirname(name)
if dirname != "":
filesystem.mkdir_exists_ok(dirname)
with click.progressbar(
length=length,
label="File %s" % name,
fill_char=click.style("&", fg="green"),
) as bar:
with open(name, "wb") as f:
for data in response.iter_content(chunk_size=4096):
f.write(data)
bar.update(len(data)) | python | wandb/cli/cli.py | 1,966 | 1,996 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,571 | restore | def restore(ctx, run, no_git, branch, project, entity):
from wandb.old.core import wandb_dir
api = _get_cling_api()
if ":" in run:
if "/" in run:
entity, rest = run.split("/", 1)
else:
rest = run
project, run = rest.split(":", 1)
elif run.count("/") > 1:
entity, run = run.split("/", 1)
project, run = api.parse_slug(run, project=project)
commit, json_config, patch_content, metadata = api.run_config(
project, run=run, entity=entity
)
repo = metadata.get("git", {}).get("repo")
image = metadata.get("docker")
restore_message = (
"""`wandb restore` needs to be run from the same git repository as the original run.
Run `git clone %s` and restore from there or pass the --no-git flag."""
% repo
)
if no_git:
commit = None
elif not api.git.enabled:
if repo:
raise ClickException(restore_message)
elif image:
wandb.termlog(
"Original run has no git history. Just restoring config and docker"
)
if commit and api.git.enabled:
wandb.termlog(f"Fetching origin and finding commit: {commit}")
subprocess.check_call(["git", "fetch", "--all"])
try:
api.git.repo.commit(commit)
except ValueError:
wandb.termlog(f"Couldn't find original commit: {commit}")
commit = None
files = api.download_urls(project, run=run, entity=entity)
for filename in files:
if filename.startswith("upstream_diff_") and filename.endswith(
".patch"
):
commit = filename[len("upstream_diff_") : -len(".patch")]
try:
api.git.repo.commit(commit)
except ValueError:
commit = None
else:
break
if commit:
wandb.termlog(f"Falling back to upstream commit: {commit}")
patch_path, _ = api.download_write_file(files[filename])
else:
raise ClickException(restore_message)
else:
if patch_content:
patch_path = os.path.join(wandb_dir(), "diff.patch")
with open(patch_path, "w") as f:
f.write(patch_content)
else:
patch_path = None
branch_name = "wandb/%s" % run
if branch and branch_name not in api.git.repo.branches:
api.git.repo.git.checkout(commit, b=branch_name)
wandb.termlog("Created branch %s" % click.style(branch_name, bold=True))
elif branch:
wandb.termlog(
"Using existing branch, run `git branch -D %s` from master for a clean checkout"
% branch_name
)
api.git.repo.git.checkout(branch_name)
else:
wandb.termlog("Checking out %s in detached mode" % commit)
api.git.repo.git.checkout(commit)
if patch_path:
# we apply the patch from the repository root so git doesn't exclude
# things outside the current directory
root = api.git.root
patch_rel_path = os.path.relpath(patch_path, start=root)
# --reject is necessary or else this fails any time a binary file
# occurs in the diff
exit_code = subprocess.call(
["git", "apply", "--reject", patch_rel_path], cwd=root
)
if exit_code == 0:
wandb.termlog("Applied patch")
else:
wandb.termerror(
"Failed to apply patch, try un-staging any un-committed changes"
)
filesystem.mkdir_exists_ok(wandb_dir())
config_path = os.path.join(wandb_dir(), "config.yaml")
config = Config()
for k, v in json_config.items():
if k not in ("_wandb", "wandb_version"):
config[k] = v
s = b"wandb_version: 1"
s += b"\n\n" + yaml.dump(
config._as_dict(),
Dumper=yaml.SafeDumper,
default_flow_style=False,
allow_unicode=True,
encoding="utf-8",
)
s = s.decode("utf-8")
with open(config_path, "w") as f:
f.write(s)
wandb.termlog("Restored config variables to %s" % config_path)
if image:
if not metadata["program"].startswith("<") and metadata.get("args") is not None:
# TODO: we may not want to default to python here.
runner = util.find_runner(metadata["program"]) or ["python"]
command = runner + [metadata["program"]] + metadata["args"]
cmd = " ".join(command)
else:
wandb.termlog("Couldn't find original command, just restoring environment")
cmd = None
wandb.termlog("Docker image found, attempting to start")
ctx.invoke(docker, docker_run_args=[image], cmd=cmd)
return commit, json_config, patch_content, repo, metadata | python | wandb/cli/cli.py | 2,017 | 2,147 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,572 | magic | def magic(ctx, program, args):
def magic_run(cmd, globals, locals):
try:
exec(cmd, globals, locals)
finally:
pass
sys.argv[:] = args
sys.argv.insert(0, program)
sys.path.insert(0, os.path.dirname(program))
try:
with open(program, "rb") as fp:
code = compile(fp.read(), program, "exec")
except OSError:
click.echo(click.style("Could not launch program: %s" % program, fg="red"))
sys.exit(1)
globs = {
"__file__": program,
"__name__": "__main__",
"__package__": None,
"wandb_magic_install": magic_install,
}
prep = (
"""
import __main__
__main__.__file__ = "%s"
wandb_magic_install()
"""
% program
)
magic_run(prep, globs, None)
magic_run(code, globs, None) | python | wandb/cli/cli.py | 2,155 | 2,186 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,573 | magic_run | def magic_run(cmd, globals, locals):
try:
exec(cmd, globals, locals)
finally:
pass | python | wandb/cli/cli.py | 2,156 | 2,160 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,574 | online | def online():
api = InternalApi()
try:
api.clear_setting("disabled", persist=True)
api.clear_setting("mode", persist=True)
except configparser.Error:
pass
click.echo(
"W&B online. Running your script from this directory will now sync to the cloud."
) | python | wandb/cli/cli.py | 2,191 | 2,200 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,575 | offline | def offline():
api = InternalApi()
try:
api.set_setting("disabled", "true", persist=True)
api.set_setting("mode", "offline", persist=True)
click.echo(
"W&B offline. Running your script from this directory will only write metadata locally. Use wandb disabled to completely turn off W&B."
)
except configparser.Error:
click.echo(
"Unable to write config, copy and paste the following in your terminal to turn off W&B:\nexport WANDB_MODE=offline"
) | python | wandb/cli/cli.py | 2,205 | 2,216 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,576 | on | def on(ctx):
ctx.invoke(online) | python | wandb/cli/cli.py | 2,222 | 2,223 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,577 | off | def off(ctx):
ctx.invoke(offline) | python | wandb/cli/cli.py | 2,229 | 2,230 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,578 | status | def status(settings):
api = _get_cling_api()
if settings:
click.echo(click.style("Current Settings", bold=True))
settings = api.settings()
click.echo(
json.dumps(settings, sort_keys=True, indent=2, separators=(",", ": "))
) | python | wandb/cli/cli.py | 2,237 | 2,244 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,579 | disabled | def disabled(service):
api = InternalApi()
try:
api.set_setting("mode", "disabled", persist=True)
click.echo("W&B disabled.")
os.environ[wandb.env._DISABLE_SERVICE] = str(service)
except configparser.Error:
click.echo(
"Unable to write config, copy and paste the following in your terminal to turn off W&B:\nexport WANDB_MODE=disabled"
) | python | wandb/cli/cli.py | 2,255 | 2,264 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,580 | enabled | def enabled(service):
api = InternalApi()
try:
api.set_setting("mode", "online", persist=True)
click.echo("W&B enabled.")
os.environ[wandb.env._DISABLE_SERVICE] = str(not service)
except configparser.Error:
click.echo(
"Unable to write config, copy and paste the following in your terminal to turn on W&B:\nexport WANDB_MODE=online"
) | python | wandb/cli/cli.py | 2,275 | 2,284 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,581 | gc | def gc(args):
click.echo(
"`wandb gc` command has been removed. Use `wandb sync --clean` to clean up synced runs."
) | python | wandb/cli/cli.py | 2,289 | 2,292 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,582 | verify | def verify(host):
# TODO: (kdg) Build this all into a WandbVerify object, and clean this up.
os.environ["WANDB_SILENT"] = "true"
os.environ["WANDB_PROJECT"] = "verify"
api = _get_cling_api()
reinit = False
if host is None:
host = api.settings("base_url")
print(f"Default host selected: {host}")
# if the given host does not match the default host, re-run init
elif host != api.settings("base_url"):
reinit = True
tmp_dir = tempfile.mkdtemp()
print(
"Find detailed logs for this test at: {}".format(os.path.join(tmp_dir, "wandb"))
)
os.chdir(tmp_dir)
os.environ["WANDB_BASE_URL"] = host
wandb.login(host=host)
if reinit:
api = _get_cling_api(reset=True)
if not wandb_verify.check_host(host):
sys.exit(1)
if not wandb_verify.check_logged_in(api, host):
sys.exit(1)
url_success, url = wandb_verify.check_graphql_put(api, host)
large_post_success = wandb_verify.check_large_post()
wandb_verify.check_secure_requests(
api.settings("base_url"),
"Checking requests to base url",
"Connections are not made over https. SSL required for secure communications.",
)
if url:
wandb_verify.check_secure_requests(
url,
"Checking requests made over signed URLs",
"Signed URL requests not made over https. SSL is required for secure communications.",
)
wandb_verify.check_cors_configuration(url, host)
wandb_verify.check_wandb_version(api)
check_run_success = wandb_verify.check_run(api)
check_artifacts_success = wandb_verify.check_artifacts()
if not (
check_artifacts_success
and check_run_success
and large_post_success
and url_success
):
sys.exit(1) | python | wandb/cli/cli.py | 2,297 | 2,346 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,583 | importer | def importer():
pass | python | wandb/cli/cli.py | 2,350 | 2,351 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,584 | mlflow | def mlflow(mlflow_tracking_uri, target_entity, target_project):
from wandb.apis.importers import MlflowImporter
importer = MlflowImporter(mlflow_tracking_uri=mlflow_tracking_uri)
overrides = {
"entity": target_entity,
"project": target_project,
}
importer.import_all_parallel(overrides=overrides) | python | wandb/cli/cli.py | 2,364 | 2,373 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,585 | __init__ | def __init__(self, message, status_code: int = 500):
Exception.__init__(self)
self.message = message
self.status_code = status_code | python | wandb/testing/relay.py | 64 | 67 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,586 | get_response | def get_response(self):
return flask.Response(self.message, status=self.status_code) | python | wandb/testing/relay.py | 69 | 70 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,587 | __repr__ | def __repr__(self):
return f"DeliberateHTTPError({self.message!r}, {self.status_code!r})" | python | wandb/testing/relay.py | 72 | 73 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,588 | __init__ | def __init__(self) -> None:
self.start: float = time.perf_counter()
self.stop: float = self.start | python | wandb/testing/relay.py | 77 | 79 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,589 | __enter__ | def __enter__(self) -> "Timer":
return self | python | wandb/testing/relay.py | 81 | 82 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,590 | __exit__ | def __exit__(self, *args: Any) -> None:
self.stop = time.perf_counter() | python | wandb/testing/relay.py | 84 | 85 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,591 | elapsed | def elapsed(self) -> float:
return self.stop - self.start | python | wandb/testing/relay.py | 88 | 89 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,592 | __init__ | def __init__(self) -> None:
# parsed/merged data. keys are the individual wandb run id's.
self._entries = defaultdict(dict)
# container for raw requests and responses:
self.raw_data: List["RawRequestResponse"] = []
# concatenated file contents for all runs:
self._history: Optional[pd.DataFrame] = None
self._events: Optional[pd.DataFrame] = None
self._summary: Optional[pd.DataFrame] = None
self._config: Optional[Dict[str, Any]] = None | python | wandb/testing/relay.py | 99 | 108 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,593 | upsert | def upsert(self, entry: Dict[str, Any]) -> None:
entry_id: str = entry["name"]
self._entries[entry_id] = wandb.util.merge_dicts(entry, self._entries[entry_id]) | python | wandb/testing/relay.py | 110 | 112 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,594 | __getitem__ | def __getitem__(self, key: str) -> Any:
return self._entries[key] | python | wandb/testing/relay.py | 115 | 116 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,595 | keys | def keys(self) -> Iterable[str]:
return self._entries.keys() | python | wandb/testing/relay.py | 118 | 119 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,596 | get_file_contents | def get_file_contents(self, file_name: str) -> pd.DataFrame:
dfs = []
for entry_id in self._entries:
# - extract the content from `file_name`
# - sort by offset (will be useful when relay server goes async)
# - extract data, merge into a list of dicts and convert to a pandas dataframe
content_list = self._entries[entry_id].get("files", {}).get(file_name, [])
content_list.sort(key=lambda x: x["offset"])
content_list = [item["content"] for item in content_list]
# merge list of lists content_list:
content_list = [item for sublist in content_list for item in sublist]
df = pd.DataFrame.from_records(content_list)
df["__run_id"] = entry_id
dfs.append(df)
return pd.concat(dfs) | python | wandb/testing/relay.py | 121 | 137 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,597 | entries | def entries(self) -> Dict[str, Any]:
return deepcopy(self._entries) | python | wandb/testing/relay.py | 141 | 142 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,598 | history | def history(self) -> pd.DataFrame:
# todo: caveat: this assumes that all assertions happen at the end of a test
if self._history is not None:
return deepcopy(self._history)
self._history = self.get_file_contents("wandb-history.jsonl")
return deepcopy(self._history) | python | wandb/testing/relay.py | 145 | 151 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,599 | events | def events(self) -> pd.DataFrame:
if self._events is not None:
return deepcopy(self._events)
self._events = self.get_file_contents("wandb-events.jsonl")
return deepcopy(self._events) | python | wandb/testing/relay.py | 154 | 159 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
2,600 | summary | def summary(self) -> pd.DataFrame:
if self._summary is not None:
return deepcopy(self._summary)
_summary = self.get_file_contents("wandb-summary.json")
# run summary may be updated multiple times,
# but we are only interested in the last one.
# we can have multiple runs saved to context,
# so we need to group by run id and take the
# last one for each run.
self._summary = (
_summary.groupby("__run_id").last().reset_index(level=["__run_id"])
)
return deepcopy(self._summary) | python | wandb/testing/relay.py | 162 | 177 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.