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 |
|---|---|---|---|---|---|---|---|
3,101 | _project_url_base | def _project_url_base(self) -> str:
if not all([self.entity, self.project]):
return ""
app_url = wandb.util.app_url(self.base_url)
return f"{app_url}/{quote(self.entity)}/{quote(self.project)}" | python | wandb/sdk/wandb_settings.py | 1,082 | 1,087 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,102 | _project_url | def _project_url(self) -> str:
project_url = self._project_url_base()
if not project_url:
return ""
query = self._get_url_query_string()
return f"{project_url}{query}" | python | wandb/sdk/wandb_settings.py | 1,089 | 1,096 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,103 | _run_url | def _run_url(self) -> str:
"""Return the run url."""
project_url = self._project_url_base()
if not all([project_url, self.run_id]):
return ""
query = self._get_url_query_string()
return f"{project_url}/runs/{quote(self.run_id)}{query}" | python | wandb/sdk/wandb_settings.py | 1,098 | 1,105 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,104 | _set_run_start_time | def _set_run_start_time(self, source: int = Source.BASE) -> None:
"""Set the time stamps for the settings.
Called once the run is initialized.
"""
time_stamp: float = time.time()
datetime_now: datetime = datetime.fromtimestamp(time_stamp)
object.__setattr__(self, "_Settings_start_datetime", datetime_now)
object.__setattr__(self, "_Settings_start_time", time_stamp)
self.update(
_start_datetime=datetime_now,
_start_time=time_stamp,
source=source,
) | python | wandb/sdk/wandb_settings.py | 1,107 | 1,120 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,105 | _sweep_url | def _sweep_url(self) -> str:
"""Return the sweep url."""
project_url = self._project_url_base()
if not all([project_url, self.sweep_id]):
return ""
query = self._get_url_query_string()
return f"{project_url}/sweeps/{quote(self.sweep_id)}{query}" | python | wandb/sdk/wandb_settings.py | 1,122 | 1,129 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,106 | __init__ | def __init__(self, **kwargs: Any) -> None:
self.__frozen: bool = False
self.__initialized: bool = False
self.__modification_order = SETTINGS_TOPOLOGICALLY_SORTED
# todo: this is collect telemetry on validation errors and unexpected args
# values are stored as strings to avoid potential json serialization errors down the line
self.__preprocessing_warnings: Dict[str, str] = dict()
self.__validation_warnings: Dict[str, str] = dict()
self.__unexpected_args: Set[str] = set()
# Set default settings values
# We start off with the class attributes and `default_props` dicts
# and then create Property objects.
# Once initialized, attributes are to only be updated using the `update` method
default_props = self._default_props()
# Init instance attributes as Property objects.
# Type hints of class attributes are used to generate a type validator function
# for runtime checks for each attribute.
# These are defaults, using Source.BASE for non-policy attributes and Source.RUN for policies.
for prop, type_hint in get_type_hints(Settings).items():
validators = [self._validator_factory(type_hint)]
if prop in default_props:
validator = default_props[prop].pop("validator", [])
# Property validator could be either Callable or Sequence[Callable]
if callable(validator):
validators.append(validator)
elif isinstance(validator, Sequence):
validators.extend(list(validator))
object.__setattr__(
self,
prop,
Property(
name=prop,
**default_props[prop],
validator=validators,
# todo: double-check this logic:
source=Source.RUN
if default_props[prop].get("is_policy", False)
else Source.BASE,
),
)
else:
object.__setattr__(
self,
prop,
Property(
name=prop,
validator=validators,
source=Source.BASE,
),
)
# todo: this is to collect stats on preprocessing and validation errors
if self.__dict__[prop].__dict__["_Property__failed_preprocessing"]:
self.__preprocessing_warnings[prop] = str(self.__dict__[prop]._value)
if self.__dict__[prop].__dict__["_Property__failed_validation"]:
self.__validation_warnings[prop] = str(self.__dict__[prop]._value)
# update overridden defaults from kwargs
unexpected_arguments = [k for k in kwargs.keys() if k not in self.__dict__]
# allow only explicitly defined arguments
if unexpected_arguments:
# todo: remove this and raise error instead once we are confident
self.__unexpected_args.update(unexpected_arguments)
wandb.termwarn(
f"Ignoring unexpected arguments: {unexpected_arguments}. "
"This will raise an error in the future."
)
for k in unexpected_arguments:
kwargs.pop(k)
# raise TypeError(f"Got unexpected arguments: {unexpected_arguments}")
# automatically inspect setting validators and runtime hooks and topologically sort them
# so that we can safely update them. throw error if there are cycles.
for prop in self.__modification_order:
if prop in kwargs:
source = Source.RUN if self.__dict__[prop].is_policy else Source.BASE
self.update({prop: kwargs[prop]}, source=source)
kwargs.pop(prop)
for k, v in kwargs.items():
# todo: double-check this logic:
source = Source.RUN if self.__dict__[k].is_policy else Source.BASE
self.update({k: v}, source=source)
# setup private attributes
object.__setattr__(self, "_Settings_start_datetime", None)
object.__setattr__(self, "_Settings_start_time", None)
# done with init, use self.update() to update attributes from now on
self.__initialized = True
# todo? freeze settings to prevent accidental changes
# self.freeze() | python | wandb/sdk/wandb_settings.py | 1,131 | 1,229 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,107 | __str__ | def __str__(self) -> str:
# get attributes that are instances of the Property class:
representation = {
k: v.value for k, v in self.__dict__.items() if isinstance(v, Property)
}
return f"<Settings {_redact_dict(representation)}>" | python | wandb/sdk/wandb_settings.py | 1,231 | 1,236 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,108 | __repr__ | def __repr__(self) -> str:
# private attributes
private = {k: v for k, v in self.__dict__.items() if k.startswith("_Settings")}
# get attributes that are instances of the Property class:
attributes = {
k: f"<Property value={v.value} source={v.source}>"
for k, v in self.__dict__.items()
if isinstance(v, Property)
}
representation = {**private, **attributes}
return f"<Settings {representation}>" | python | wandb/sdk/wandb_settings.py | 1,238 | 1,248 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,109 | __copy__ | def __copy__(self) -> "Settings":
"""Ensure that a copy of the settings object is a truly deep copy.
Note that the copied object will not be frozen todo? why is this needed?
"""
# get attributes that are instances of the Property class:
attributes = {k: v for k, v in self.__dict__.items() if isinstance(v, Property)}
new = Settings()
# update properties that have deps or are dependent on in the topologically-sorted order
for prop in self.__modification_order:
new.update({prop: attributes[prop]._value}, source=attributes[prop].source)
attributes.pop(prop)
# update the remaining attributes
for k, v in attributes.items():
# make sure to use the raw property value (v._value),
# not the potential result of runtime hooks applied to it (v.value)
new.update({k: v._value}, source=v.source)
new.unfreeze()
return new | python | wandb/sdk/wandb_settings.py | 1,250 | 1,270 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,110 | __deepcopy__ | def __deepcopy__(self, memo: dict) -> "Settings":
return self.__copy__() | python | wandb/sdk/wandb_settings.py | 1,272 | 1,273 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,111 | __getattribute__ | def __getattribute__(self, name: str) -> Any:
"""Expose `attribute.value` if `attribute` is a Property."""
item = object.__getattribute__(self, name)
if isinstance(item, Property):
return item.value
return item | python | wandb/sdk/wandb_settings.py | 1,277 | 1,282 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,112 | __setattr__ | def __setattr__(self, key: str, value: Any) -> None:
if "_Settings__initialized" in self.__dict__ and self.__initialized:
raise TypeError(f"Please use update() to update attribute `{key}` value")
object.__setattr__(self, key, value) | python | wandb/sdk/wandb_settings.py | 1,284 | 1,287 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,113 | __iter__ | def __iter__(self) -> Iterable:
return iter(self.make_static()) | python | wandb/sdk/wandb_settings.py | 1,289 | 1,290 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,114 | copy | def copy(self) -> "Settings":
return self.__copy__() | python | wandb/sdk/wandb_settings.py | 1,292 | 1,293 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,115 | keys | def keys(self) -> Iterable[str]:
return self.make_static().keys() | python | wandb/sdk/wandb_settings.py | 1,296 | 1,297 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,116 | __getitem__ | def __getitem__(self, name: str) -> Any:
"""Expose attribute.value if attribute is a Property."""
item = object.__getattribute__(self, name)
if isinstance(item, Property):
return item.value
return item | python | wandb/sdk/wandb_settings.py | 1,300 | 1,305 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,117 | update | def update(
self,
settings: Optional[Union[Dict[str, Any], "Settings"]] = None,
source: int = Source.OVERRIDE,
**kwargs: Any,
) -> None:
"""Update individual settings."""
if "_Settings__frozen" in self.__dict__ and self.__frozen:
raise TypeError("Settings object is frozen")
if isinstance(settings, Settings):
# If a Settings object is passed, detect the settings that differ
# from defaults, collect them into a dict, and apply them using `source`.
# This comes up in `wandb.init(settings=wandb.Settings(...))` and
# seems like the behavior that the user would expect when calling init that way.
defaults = Settings()
settings_dict = dict()
for k, v in settings.__dict__.items():
if isinstance(v, Property):
if v._value != defaults.__dict__[k]._value:
settings_dict[k] = v._value
# todo: store warnings from the passed Settings object, if any,
# to collect telemetry on validation errors and unexpected args.
# remove this once strict checking is enforced.
for attr in (
"_Settings__unexpected_args",
"_Settings__preprocessing_warnings",
"_Settings__validation_warnings",
):
getattr(self, attr).update(getattr(settings, attr))
# replace with the generated dict
settings = settings_dict
# add kwargs to settings
settings = settings or dict()
# explicit kwargs take precedence over settings
settings = {**settings, **kwargs}
unknown_properties = []
for key in settings.keys():
# only allow updating known Properties
if key not in self.__dict__ or not isinstance(self.__dict__[key], Property):
unknown_properties.append(key)
if unknown_properties:
raise KeyError(f"Unknown settings: {unknown_properties}")
# only if all keys are valid, update them
# store settings to be updated in a dict to preserve stats on preprocessing and validation errors
updated_settings = settings.copy()
# update properties that have deps or are dependent on in the topologically-sorted order
for key in self.__modification_order:
if key in settings:
self.__dict__[key].update(settings.pop(key), source=source)
# update the remaining properties
for key, value in settings.items():
self.__dict__[key].update(value, source)
for key in updated_settings.keys():
# todo: this is to collect stats on preprocessing and validation errors
if self.__dict__[key].__dict__["_Property__failed_preprocessing"]:
self.__preprocessing_warnings[key] = str(self.__dict__[key]._value)
else:
self.__preprocessing_warnings.pop(key, None)
if self.__dict__[key].__dict__["_Property__failed_validation"]:
self.__validation_warnings[key] = str(self.__dict__[key]._value)
else:
self.__validation_warnings.pop(key, None) | python | wandb/sdk/wandb_settings.py | 1,307 | 1,375 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,118 | items | def items(self) -> ItemsView[str, Any]:
return self.make_static().items() | python | wandb/sdk/wandb_settings.py | 1,377 | 1,378 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,119 | get | def get(self, key: str, default: Optional[Any] = None) -> Any:
return self.make_static().get(key, default) | python | wandb/sdk/wandb_settings.py | 1,380 | 1,381 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,120 | freeze | def freeze(self) -> None:
object.__setattr__(self, "_Settings__frozen", True) | python | wandb/sdk/wandb_settings.py | 1,383 | 1,384 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,121 | unfreeze | def unfreeze(self) -> None:
object.__setattr__(self, "_Settings__frozen", False) | python | wandb/sdk/wandb_settings.py | 1,386 | 1,387 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,122 | is_frozen | def is_frozen(self) -> bool:
return self.__frozen | python | wandb/sdk/wandb_settings.py | 1,389 | 1,390 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,123 | make_static | def make_static(self) -> Dict[str, Any]:
"""Generate a static, serializable version of the settings."""
# get attributes that are instances of the Property class:
attributes = {
k: v.value for k, v in self.__dict__.items() if isinstance(v, Property)
}
return attributes | python | wandb/sdk/wandb_settings.py | 1,392 | 1,398 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,124 | _apply_settings | def _apply_settings(
self,
settings: "Settings",
_logger: Optional[_EarlyLogger] = None,
) -> None:
"""Apply settings from a Settings object."""
if _logger is not None:
_logger.info(f"Applying settings from {settings}")
attributes = {
k: v for k, v in settings.__dict__.items() if isinstance(v, Property)
}
# update properties that have deps or are dependent on in the topologically-sorted order
for prop in self.__modification_order:
self.update({prop: attributes[prop]._value}, source=attributes[prop].source)
attributes.pop(prop)
# update the remaining properties
for k, v in attributes.items():
# note that only the same/higher priority settings are propagated
self.update({k: v._value}, source=v.source)
# todo: this is to pass on info on unexpected args in settings
if settings.__dict__["_Settings__unexpected_args"]:
self.__dict__["_Settings__unexpected_args"].update(
settings.__dict__["_Settings__unexpected_args"]
) | python | wandb/sdk/wandb_settings.py | 1,402 | 1,426 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,125 | _load_config_file | def _load_config_file(file_name: str, section: str = "default") -> dict:
parser = configparser.ConfigParser()
parser.add_section(section)
parser.read(file_name)
config: Dict[str, Any] = dict()
for k in parser[section]:
config[k] = parser[section][k]
# TODO (cvp): we didn't do this in the old cli, but it seems necessary
if k == "ignore_globs":
config[k] = config[k].split(",")
return config | python | wandb/sdk/wandb_settings.py | 1,429 | 1,439 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,126 | _apply_base | def _apply_base(self, pid: int, _logger: Optional[_EarlyLogger] = None) -> None:
if _logger is not None:
_logger.info(f"Configure stats pid to {pid}")
self.update({"_stats_pid": pid}, source=Source.SETUP) | python | wandb/sdk/wandb_settings.py | 1,441 | 1,444 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,127 | _apply_config_files | def _apply_config_files(self, _logger: Optional[_EarlyLogger] = None) -> None:
# TODO(jhr): permit setting of config in system and workspace
if self.settings_system is not None:
if _logger is not None:
_logger.info(f"Loading settings from {self.settings_system}")
self.update(
self._load_config_file(self.settings_system),
source=Source.SYSTEM,
)
if self.settings_workspace is not None:
if _logger is not None:
_logger.info(f"Loading settings from {self.settings_workspace}")
self.update(
self._load_config_file(self.settings_workspace),
source=Source.WORKSPACE,
) | python | wandb/sdk/wandb_settings.py | 1,446 | 1,461 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,128 | _apply_env_vars | def _apply_env_vars(
self,
environ: Mapping[str, Any],
_logger: Optional[_EarlyLogger] = None,
) -> None:
env_prefix: str = "WANDB_"
special_env_var_names = {
"WANDB_TRACELOG": "_tracelog",
"WANDB_DISABLE_SERVICE": "_disable_service",
"WANDB_SERVICE_TRANSPORT": "_service_transport",
"WANDB_DIR": "root_dir",
"WANDB_NAME": "run_name",
"WANDB_NOTES": "run_notes",
"WANDB_TAGS": "run_tags",
"WANDB_JOB_TYPE": "run_job_type",
}
env = dict()
for setting, value in environ.items():
if not setting.startswith(env_prefix):
continue
if setting in special_env_var_names:
key = special_env_var_names[setting]
else:
# otherwise, strip the prefix and convert to lowercase
key = setting[len(env_prefix) :].lower()
if key in self.__dict__:
if key in ("ignore_globs", "run_tags"):
value = value.split(",")
env[key] = value
elif _logger is not None:
_logger.warning(f"Unknown environment variable: {setting}")
if _logger is not None:
_logger.info(
f"Loading settings from environment variables: {_redact_dict(env)}"
)
self.update(env, source=Source.ENV) | python | wandb/sdk/wandb_settings.py | 1,463 | 1,501 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,129 | _infer_settings_from_environment | def _infer_settings_from_environment(
self, _logger: Optional[_EarlyLogger] = None
) -> None:
"""Modify settings based on environment (for runs and cli)."""
settings: Dict[str, Union[bool, str, Sequence, None]] = dict()
# disable symlinks if on windows (requires admin or developer setup)
settings["symlink"] = True
if self._windows:
settings["symlink"] = False
# TODO(jhr): this needs to be moved last in setting up settings ?
# (dd): loading order does not matter as long as source is set correctly
# For code saving, only allow env var override if value from server is true, or
# if no preference was specified.
if (self.save_code is True or self.save_code is None) and (
os.getenv(wandb.env.SAVE_CODE) is not None
or os.getenv(wandb.env.DISABLE_CODE) is not None
):
settings["save_code"] = wandb.env.should_save_code()
settings["disable_git"] = wandb.env.disable_git()
# Attempt to get notebook information if not already set by the user
if self._jupyter and (self.notebook_name is None or self.notebook_name == ""):
meta = wandb.jupyter.notebook_metadata(self.silent)
settings["_jupyter_path"] = meta.get("path")
settings["_jupyter_name"] = meta.get("name")
settings["_jupyter_root"] = meta.get("root")
elif (
self._jupyter
and self.notebook_name is not None
and os.path.exists(self.notebook_name)
):
settings["_jupyter_path"] = self.notebook_name
settings["_jupyter_name"] = self.notebook_name
settings["_jupyter_root"] = os.getcwd()
elif self._jupyter:
wandb.termwarn(
"WANDB_NOTEBOOK_NAME should be a path to a notebook file, "
f"couldn't find {self.notebook_name}.",
)
# host and username are populated by apply_env_vars if corresponding env
# vars exist -- but if they don't, we'll fill them in here
if self.host is None:
settings["host"] = socket.gethostname() # type: ignore
if self.username is None:
try: # type: ignore
settings["username"] = getpass.getuser()
except KeyError:
# getuser() could raise KeyError in restricted environments like
# chroot jails or docker containers. Return user id in these cases.
settings["username"] = str(os.getuid())
_executable = (
self._executable
or os.environ.get(wandb.env._EXECUTABLE)
or sys.executable
or shutil.which("python3")
or "python3"
)
settings["_executable"] = _executable
settings["docker"] = wandb.env.get_docker(wandb.util.image_id_from_k8s())
# TODO: we should use the cuda library to collect this
if os.path.exists("/usr/local/cuda/version.txt"):
with open("/usr/local/cuda/version.txt") as f:
settings["_cuda"] = f.read().split(" ")[-1].strip()
if not self._jupyter:
settings["_args"] = sys.argv[1:]
settings["_os"] = platform.platform(aliased=True)
settings["_python"] = platform.python_version()
# hack to make sure we don't hang on windows
if self._windows and self._except_exit is None:
settings["_except_exit"] = True # type: ignore
if _logger is not None:
_logger.info(
f"Inferring settings from compute environment: {_redact_dict(settings)}"
)
self.update(settings, source=Source.ENV) | python | wandb/sdk/wandb_settings.py | 1,503 | 1,587 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,130 | _infer_run_settings_from_environment | def _infer_run_settings_from_environment(
self,
_logger: Optional[_EarlyLogger] = None,
) -> None:
"""Modify settings based on environment (for runs only)."""
# If there's not already a program file, infer it now.
settings: Dict[str, Union[bool, str, None]] = dict()
program = self.program or _get_program()
if program is not None:
program_relpath = self.program_relpath or _get_program_relpath_from_gitrepo(
program, _logger=_logger
)
settings["program_relpath"] = program_relpath
else:
program = "<python with no main file>"
settings["program"] = program
if _logger is not None:
_logger.info(
f"Inferring run settings from compute environment: {_redact_dict(settings)}"
)
self.update(settings, source=Source.ENV) | python | wandb/sdk/wandb_settings.py | 1,589 | 1,612 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,131 | _apply_setup | def _apply_setup(
self, setup_settings: Dict[str, Any], _logger: Optional[_EarlyLogger] = None
) -> None:
if _logger:
_logger.info(f"Applying setup settings: {_redact_dict(setup_settings)}")
self.update(setup_settings, source=Source.SETUP) | python | wandb/sdk/wandb_settings.py | 1,614 | 1,619 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,132 | _apply_user | def _apply_user(
self, user_settings: Dict[str, Any], _logger: Optional[_EarlyLogger] = None
) -> None:
if _logger:
_logger.info(f"Applying user settings: {_redact_dict(user_settings)}")
self.update(user_settings, source=Source.USER) | python | wandb/sdk/wandb_settings.py | 1,621 | 1,626 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,133 | _apply_init | def _apply_init(self, init_settings: Dict[str, Union[str, int, None]]) -> None:
# prevent setting project, entity if in sweep
# TODO(jhr): these should be locked elements in the future
if self.sweep_id:
for key in ("project", "entity", "id"):
val = init_settings.pop(key, None)
if val:
wandb.termwarn(
f"Ignored wandb.init() arg {key} when running a sweep."
)
if self.launch:
for key in ("project", "entity", "id"):
val = init_settings.pop(key, None)
if val:
wandb.termwarn(
"Project, entity and id are ignored when running from wandb launch context. "
f"Ignored wandb.init() arg {key} when running running from launch.",
)
# strip out items where value is None
param_map = dict(
name="run_name",
id="run_id",
tags="run_tags",
group="run_group",
job_type="run_job_type",
notes="run_notes",
dir="root_dir",
)
init_settings = {
param_map.get(k, k): v for k, v in init_settings.items() if v is not None
}
# fun logic to convert the resume init arg
if init_settings.get("resume"):
if isinstance(init_settings["resume"], str):
if init_settings["resume"] not in ("allow", "must", "never", "auto"):
if init_settings.get("run_id") is None:
# TODO: deprecate or don't support
init_settings["run_id"] = init_settings["resume"]
init_settings["resume"] = "allow"
elif init_settings["resume"] is True:
# todo: add deprecation warning, switch to literal strings for resume
init_settings["resume"] = "auto"
# update settings
self.update(init_settings, source=Source.INIT)
# handle auto resume logic
if self.resume == "auto":
if os.path.exists(self.resume_fname):
with open(self.resume_fname) as f:
resume_run_id = json.load(f)["run_id"]
if self.run_id is None:
self.update({"run_id": resume_run_id}, source=Source.INIT) # type: ignore
elif self.run_id != resume_run_id:
wandb.termwarn(
"Tried to auto resume run with "
f"id {resume_run_id} but id {self.run_id} is set.",
)
self.update({"run_id": self.run_id or generate_id()}, source=Source.INIT)
# persist our run id in case of failure
# check None for mypy
if self.resume == "auto" and self.resume_fname is not None:
filesystem.mkdir_exists_ok(self.wandb_dir)
with open(self.resume_fname, "w") as f:
f.write(json.dumps({"run_id": self.run_id})) | python | wandb/sdk/wandb_settings.py | 1,628 | 1,693 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,134 | _apply_login | def _apply_login(
self, login_settings: Dict[str, Any], _logger: Optional[_EarlyLogger] = None
) -> None:
param_map = dict(key="api_key", host="base_url", timeout="login_timeout")
login_settings = {
param_map.get(k, k): v for k, v in login_settings.items() if v is not None
}
if login_settings:
if _logger:
_logger.info(f"Applying login settings: {_redact_dict(login_settings)}")
self.update(login_settings, source=Source.LOGIN) | python | wandb/sdk/wandb_settings.py | 1,695 | 1,705 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,135 | _apply_run_start | def _apply_run_start(self, run_start_settings: Dict[str, Any]) -> None:
# This dictionary maps from the "run message dict" to relevant fields in settings
# Note: that config is missing
param_map = {
"run_id": "run_id",
"entity": "entity",
"project": "project",
"run_group": "run_group",
"job_type": "run_job_type",
"display_name": "run_name",
"notes": "run_notes",
"tags": "run_tags",
"sweep_id": "sweep_id",
"host": "host",
"resumed": "resumed",
"git.remote_url": "git_remote_url",
"git.commit": "git_commit",
}
run_settings = {
name: reduce(lambda d, k: d.get(k, {}), attr.split("."), run_start_settings)
for attr, name in param_map.items()
}
run_settings = {key: value for key, value in run_settings.items() if value}
if run_settings:
self.update(run_settings, source=Source.RUN) | python | wandb/sdk/wandb_settings.py | 1,707 | 1,731 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,136 | _get_dict | def _get_dict(d):
if isinstance(d, dict):
return d
# assume argparse Namespace
return vars(d) | python | wandb/sdk/wandb_summary.py | 7 | 11 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,137 | _as_dict | def _as_dict(self):
raise NotImplementedError | python | wandb/sdk/wandb_summary.py | 21 | 22 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,138 | _update | def _update(self, record: SummaryRecord):
raise NotImplementedError | python | wandb/sdk/wandb_summary.py | 25 | 26 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,139 | keys | def keys(self):
return [k for k in self._as_dict().keys() if k != "_wandb"] | python | wandb/sdk/wandb_summary.py | 28 | 29 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,140 | get | def get(self, key, default=None):
return self._as_dict().get(key, default) | python | wandb/sdk/wandb_summary.py | 31 | 32 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,141 | __getitem__ | def __getitem__(self, key):
item = self._as_dict()[key]
if isinstance(item, dict):
# this nested dict needs to be wrapped:
wrapped_item = SummarySubDict()
object.__setattr__(wrapped_item, "_items", item)
object.__setattr__(wrapped_item, "_parent", self)
object.__setattr__(wrapped_item, "_parent_key", key)
return wrapped_item
# this item isn't a nested dict
return item | python | wandb/sdk/wandb_summary.py | 34 | 47 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,142 | __setitem__ | def __setitem__(self, key, val):
self.update({key: val}) | python | wandb/sdk/wandb_summary.py | 51 | 52 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,143 | __delattr__ | def __delattr__(self, key):
record = SummaryRecord()
item = SummaryItem()
item.key = (key,)
record.remove = (item,)
self._update(record) | python | wandb/sdk/wandb_summary.py | 56 | 61 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,144 | update | def update(self, d: t.Dict):
# import ipdb; ipdb.set_trace()
record = SummaryRecord()
for key, value in d.items():
item = SummaryItem()
item.key = (key,)
item.value = value
record.update.append(item)
self._update(record) | python | wandb/sdk/wandb_summary.py | 65 | 74 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,145 | __init__ | def __init__(self, get_current_summary_callback: t.Callable):
super().__init__()
object.__setattr__(self, "_update_callback", None)
object.__setattr__(
self, "_get_current_summary_callback", get_current_summary_callback
) | python | wandb/sdk/wandb_summary.py | 113 | 118 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,146 | _set_update_callback | def _set_update_callback(self, update_callback: t.Callable):
object.__setattr__(self, "_update_callback", update_callback) | python | wandb/sdk/wandb_summary.py | 120 | 121 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,147 | _as_dict | def _as_dict(self):
return self._get_current_summary_callback() | python | wandb/sdk/wandb_summary.py | 123 | 124 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,148 | _update | def _update(self, record: SummaryRecord):
if self._update_callback:
self._update_callback(record) | python | wandb/sdk/wandb_summary.py | 126 | 128 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,149 | __init__ | def __init__(self):
object.__setattr__(self, "_items", dict())
object.__setattr__(self, "_parent", None)
object.__setattr__(self, "_parent_key", None) | python | wandb/sdk/wandb_summary.py | 141 | 144 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,150 | _as_dict | def _as_dict(self):
return self._items | python | wandb/sdk/wandb_summary.py | 146 | 147 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,151 | _update | def _update(self, record: SummaryRecord):
return self._parent._update(record._add_next_parent(self._parent_key)) | python | wandb/sdk/wandb_summary.py | 149 | 150 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,152 | watch | def watch(
models,
criterion=None,
log: Optional[Literal["gradients", "parameters", "all"]] = "gradients",
log_freq: int = 1000,
idx: Optional[int] = None,
log_graph: bool = False,
):
"""Hook into the torch model to collect gradients and the topology.
Should be extended to accept arbitrary ML models.
Args:
models: (torch.Module) The model to hook, can be a tuple
criterion: (torch.F) An optional loss value being optimized
log: (str) One of "gradients", "parameters", "all", or None
log_freq: (int) log gradients and parameters every N batches
idx: (int) an index to be used when calling wandb.watch on multiple models
log_graph: (boolean) log graph topology
Returns:
`wandb.Graph`: The graph object that will populate after the first backward pass
Raises:
ValueError: If called before `wandb.init` or if any of models is not a torch.nn.Module.
"""
global _global_watch_idx
with telemetry.context() as tel:
tel.feature.watch = True
logger.info("Watching")
if wandb.run is None:
raise ValueError("You must call `wandb.init` before calling watch")
if log not in {"gradients", "parameters", "all", None}:
raise ValueError("log must be one of 'gradients', 'parameters', 'all', or None")
log_parameters = log in {"parameters", "all"}
log_gradients = log in {"gradients", "all"}
if not isinstance(models, (tuple, list)):
models = (models,)
torch = wandb.util.get_module(
"torch", required="wandb.watch only works with pytorch, couldn't import torch."
)
for model in models:
if not isinstance(model, torch.nn.Module):
raise ValueError(
"Expected a pytorch model (torch.nn.Module). Received "
+ str(type(model))
)
graphs = []
prefix = ""
if idx is None:
idx = _global_watch_idx
for local_idx, model in enumerate(models):
global_idx = idx + local_idx
_global_watch_idx += 1
if global_idx > 0:
# TODO: this makes ugly chart names like gradients/graph_1conv1d.bias
prefix = "graph_%i" % global_idx
if log_parameters:
wandb.run._torch.add_log_parameters_hook(
model,
prefix=prefix,
log_freq=log_freq,
)
if log_gradients:
wandb.run._torch.add_log_gradients_hook(
model,
prefix=prefix,
log_freq=log_freq,
)
if log_graph:
graph = wandb.run._torch.hook_torch(model, criterion, graph_idx=global_idx)
graphs.append(graph)
# NOTE: the graph is set in run.summary by hook_torch on the backward pass
return graphs | python | wandb/sdk/wandb_watch.py | 20 | 106 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,153 | unwatch | def unwatch(models=None):
"""Remove pytorch model topology, gradient and parameter hooks.
Args:
models: (list) Optional list of pytorch models that have had watch called on them
"""
if models:
if not isinstance(models, (tuple, list)):
models = (models,)
for model in models:
if not hasattr(model, "_wandb_hook_names"):
wandb.termwarn("%s model has not been watched" % model)
else:
for name in model._wandb_hook_names:
wandb.run._torch.unhook(name)
delattr(model, "_wandb_hook_names")
# TODO: we should also remove recursively model._wandb_watch_called
else:
wandb.run._torch.unhook_all() | python | wandb/sdk/wandb_watch.py | 109 | 128 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,154 | _handle_host_wandb_setting | def _handle_host_wandb_setting(host: Optional[str], cloud: bool = False) -> None:
"""Write the host parameter to the global settings file.
This takes the parameter from wandb.login or wandb login for use by the
application's APIs.
"""
_api = InternalApi()
if host == "https://api.wandb.ai" or (host is None and cloud):
_api.clear_setting("base_url", globally=True, persist=True)
# To avoid writing an empty local settings file, we only clear if it exists
if os.path.exists(OldSettings._local_path()):
_api.clear_setting("base_url", persist=True)
elif host:
host = host.rstrip("/")
# force relogin if host is specified
_api.set_setting("base_url", host, globally=True, persist=True) | python | wandb/sdk/wandb_login.py | 28 | 43 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,155 | login | def login(
anonymous: Optional[Literal["must", "allow", "never"]] = None,
key: Optional[str] = None,
relogin: Optional[bool] = None,
host: Optional[str] = None,
force: Optional[bool] = None,
timeout: Optional[int] = None,
) -> bool:
"""Log in to W&B.
Arguments:
anonymous: (string, optional) Can be "must", "allow", or "never".
If set to "must" we'll always log in anonymously, if set to
"allow" we'll only create an anonymous user if the user
isn't already logged in.
key: (string, optional) authentication key.
relogin: (bool, optional) If true, will re-prompt for API key.
host: (string, optional) The host to connect to.
force: (bool, optional) If true, will force a relogin.
timeout: (int, optional) Number of seconds to wait for user input.
Returns:
bool: if key is configured
Raises:
UsageError - if api_key cannot be configured and no tty
"""
_handle_host_wandb_setting(host)
if wandb.setup()._settings._noop:
return True
kwargs = dict(locals())
configured = _login(**kwargs)
return True if configured else False | python | wandb/sdk/wandb_login.py | 46 | 78 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,156 | __init__ | def __init__(self):
self.kwargs: Optional[Dict] = None
self._settings: Union[Settings, Dict[str, Any], None] = None
self._backend = None
self._silent = None
self._entity = None
self._wl = None
self._key = None
self._relogin = None | python | wandb/sdk/wandb_login.py | 89 | 97 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,157 | setup | def setup(self, kwargs):
self.kwargs = kwargs
# built up login settings
login_settings: Settings = wandb.Settings()
settings_param = kwargs.pop("_settings", None)
# note that this case does not come up anywhere except for the tests
if settings_param is not None:
if isinstance(settings_param, Settings):
login_settings._apply_settings(settings_param)
elif isinstance(settings_param, dict):
login_settings.update(settings_param, source=Source.LOGIN)
_logger = wandb.setup()._get_logger()
# Do not save relogin into settings as we just want to relogin once
self._relogin = kwargs.pop("relogin", None)
login_settings._apply_login(kwargs, _logger=_logger)
# make sure they are applied globally
self._wl = wandb.setup(settings=login_settings)
self._settings = self._wl.settings | python | wandb/sdk/wandb_login.py | 99 | 118 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,158 | is_apikey_configured | def is_apikey_configured(self):
return apikey.api_key(settings=self._settings) is not None | python | wandb/sdk/wandb_login.py | 120 | 121 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,159 | set_backend | def set_backend(self, backend):
self._backend = backend | python | wandb/sdk/wandb_login.py | 123 | 124 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,160 | set_silent | def set_silent(self, silent: bool):
self._silent = silent | python | wandb/sdk/wandb_login.py | 126 | 127 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,161 | set_entity | def set_entity(self, entity: str):
self._entity = entity | python | wandb/sdk/wandb_login.py | 129 | 130 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,162 | login | def login(self):
apikey_configured = self.is_apikey_configured()
if self._settings.relogin or self._relogin:
apikey_configured = False
if not apikey_configured:
return False
if not self._silent:
self.login_display()
return apikey_configured | python | wandb/sdk/wandb_login.py | 132 | 142 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,163 | login_display | def login_display(self):
username = self._wl._get_username()
if username:
# check to see if we got an entity from the setup call or from the user
entity = self._entity or self._wl._get_entity()
entity_str = ""
# check if entity exist, valid (is part of a certain team) and different from the username
if entity and entity in self._wl._get_teams() and entity != username:
entity_str = f" ({click.style(entity, fg='yellow')})"
login_state_str = f"Currently logged in as: {click.style(username, fg='yellow')}{entity_str}"
else:
login_state_str = "W&B API key is configured"
login_info_str = (
f"Use {click.style('`wandb login --relogin`', bold=True)} to force relogin"
)
wandb.termlog(
f"{login_state_str}. {login_info_str}",
repeat=False,
) | python | wandb/sdk/wandb_login.py | 144 | 166 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,164 | configure_api_key | def configure_api_key(self, key):
if self._settings._jupyter and not self._settings.silent:
wandb.termwarn(
"If you're specifying your api key in code, ensure this "
"code is not shared publicly.\nConsider setting the "
"WANDB_API_KEY environment variable, or running "
"`wandb login` from the command line."
)
apikey.write_key(self._settings, key)
self.update_session(key)
self._key = key | python | wandb/sdk/wandb_login.py | 168 | 178 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,165 | update_session | def update_session(
self, key: Optional[str], status: ApiKeyStatus = ApiKeyStatus.VALID
) -> None:
_logger = wandb.setup()._get_logger()
login_settings = dict()
if status == ApiKeyStatus.OFFLINE:
login_settings = dict(mode="offline")
elif status == ApiKeyStatus.DISABLED:
login_settings = dict(mode="disabled")
elif key:
login_settings = dict(api_key=key)
self._wl._settings._apply_login(login_settings, _logger=_logger)
# Whenever the key changes, make sure to pull in user settings
# from server.
if not self._wl.settings._offline:
self._wl._update_user_settings() | python | wandb/sdk/wandb_login.py | 180 | 195 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,166 | _prompt_api_key | def _prompt_api_key(self) -> Tuple[Optional[str], ApiKeyStatus]:
api = Api(self._settings)
while True:
try:
key = apikey.prompt_api_key(
self._settings,
api=api,
no_offline=self._settings.force if self._settings else None,
no_create=self._settings.force if self._settings else None,
)
except ValueError as e:
# invalid key provided, try again
wandb.termerror(e.args[0])
continue
except TimeoutError:
wandb.termlog("W&B disabled due to login timeout.")
return None, ApiKeyStatus.DISABLED
if key is False:
return None, ApiKeyStatus.NOTTY
if not key:
return None, ApiKeyStatus.OFFLINE
return key, ApiKeyStatus.VALID | python | wandb/sdk/wandb_login.py | 197 | 218 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,167 | prompt_api_key | def prompt_api_key(self):
key, status = self._prompt_api_key()
if status == ApiKeyStatus.NOTTY:
directive = (
"wandb login [your_api_key]"
if self._settings._cli_only_mode
else "wandb.login(key=[your_api_key])"
)
raise UsageError("api_key not configured (no-tty). call " + directive)
self.update_session(key, status=status)
self._key = key | python | wandb/sdk/wandb_login.py | 220 | 231 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,168 | propogate_login | def propogate_login(self):
# TODO(jhr): figure out if this is really necessary
if self._backend:
# TODO: calling this twice is gross, this deserves a refactor
# Make sure our backend picks up the new creds
# _ = self._backend.interface.communicate_login(key, anonymous)
pass | python | wandb/sdk/wandb_login.py | 233 | 239 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,169 | _login | def _login(
anonymous: Optional[Literal["must", "allow", "never"]] = None,
key: Optional[str] = None,
relogin: Optional[bool] = None,
host: Optional[str] = None,
force: Optional[bool] = None,
timeout: Optional[int] = None,
_backend=None,
_silent: Optional[bool] = None,
_disable_warning: Optional[bool] = None,
_entity: Optional[str] = None,
):
kwargs = dict(locals())
_disable_warning = kwargs.pop("_disable_warning", None)
if wandb.run is not None:
if not _disable_warning:
wandb.termwarn("Calling wandb.login() after wandb.init() has no effect.")
return True
wlogin = _WandbLogin()
_backend = kwargs.pop("_backend", None)
if _backend:
wlogin.set_backend(_backend)
_silent = kwargs.pop("_silent", None)
if _silent:
wlogin.set_silent(_silent)
_entity = kwargs.pop("_entity", None)
if _entity:
wlogin.set_entity(_entity)
# configure login object
wlogin.setup(kwargs)
if wlogin._settings._offline:
return False
elif wandb.util._is_kaggle() and not wandb.util._has_internet():
wandb.termerror(
"To use W&B in kaggle you must enable internet in the settings panel on the right."
)
return False
# perform a login
logged_in = wlogin.login()
key = kwargs.get("key")
if key:
wlogin.configure_api_key(key)
if logged_in:
return logged_in
if not key:
wlogin.prompt_api_key()
# make sure login credentials get to the backend
wlogin.propogate_login()
return wlogin._key or False | python | wandb/sdk/wandb_login.py | 242 | 303 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,170 | __init__ | def __init__(
self,
name: str,
step_metric: Optional[str] = None,
step_sync: Optional[bool] = None,
hidden: Optional[bool] = None,
summary: Optional[Sequence[str]] = None,
goal: Optional[str] = None,
overwrite: Optional[bool] = None,
) -> None:
self._callback = None
self._name = name
self._step_metric = step_metric
# default to step_sync=True if step metric is set
step_sync = step_sync if step_sync is not None else step_metric is not None
self._step_sync = step_sync
self._hidden = hidden
self._summary = summary
self._goal = goal
self._overwrite = overwrite | python | wandb/sdk/wandb_metric.py | 23 | 42 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,171 | _set_callback | def _set_callback(self, cb: Callable[[pb.MetricRecord], None]) -> None:
self._callback = cb | python | wandb/sdk/wandb_metric.py | 44 | 45 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,172 | name | def name(self) -> str:
return self._name | python | wandb/sdk/wandb_metric.py | 48 | 49 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,173 | step_metric | def step_metric(self) -> Optional[str]:
return self._step_metric | python | wandb/sdk/wandb_metric.py | 52 | 53 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,174 | step_sync | def step_sync(self) -> Optional[bool]:
return self._step_sync | python | wandb/sdk/wandb_metric.py | 56 | 57 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,175 | summary | def summary(self) -> Optional[Tuple[str, ...]]:
if self._summary is None:
return None
return tuple(self._summary) | python | wandb/sdk/wandb_metric.py | 60 | 63 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,176 | hidden | def hidden(self) -> Optional[bool]:
return self._hidden | python | wandb/sdk/wandb_metric.py | 66 | 67 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,177 | goal | def goal(self) -> Optional[str]:
goal_dict = dict(min="minimize", max="maximize")
return goal_dict[self._goal] if self._goal else None | python | wandb/sdk/wandb_metric.py | 70 | 72 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,178 | _commit | def _commit(self) -> None:
m = pb.MetricRecord()
m.options.defined = True
if self._name.endswith("*"):
m.glob_name = self._name
else:
m.name = self._name
if self._step_metric:
m.step_metric = self._step_metric
if self._step_sync:
m.options.step_sync = self._step_sync
if self._hidden:
m.options.hidden = self._hidden
if self._summary:
summary_set = set(self._summary)
if "min" in summary_set:
m.summary.min = True
if "max" in summary_set:
m.summary.max = True
if "mean" in summary_set:
m.summary.mean = True
if "last" in summary_set:
m.summary.last = True
if "copy" in summary_set:
m.summary.copy = True
if "none" in summary_set:
m.summary.none = True
if "best" in summary_set:
m.summary.best = True
if self._goal == "min":
m.goal = m.GOAL_MINIMIZE
if self._goal == "max":
m.goal = m.GOAL_MAXIMIZE
if self._overwrite:
m._control.overwrite = self._overwrite
if self._callback:
self._callback(m) | python | wandb/sdk/wandb_metric.py | 74 | 110 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,179 | __init__ | def __init__(self, features: Union[str, Sequence[str]]) -> None:
self._features = (
tuple([features]) if isinstance(features, str) else tuple(features)
) | python | wandb/sdk/wandb_require.py | 25 | 28 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,180 | require_require | def require_require(self) -> None:
pass | python | wandb/sdk/wandb_require.py | 30 | 31 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,181 | _require_service | def _require_service(self) -> None:
wandb.teardown = wandb._teardown # type: ignore
wandb.attach = wandb._attach # type: ignore
wandb_run.Run.detach = wandb_run.Run._detach # type: ignore | python | wandb/sdk/wandb_require.py | 33 | 36 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,182 | require_service | def require_service(self) -> None:
self._require_service() | python | wandb/sdk/wandb_require.py | 38 | 39 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,183 | apply | def apply(self) -> None:
"""Call require_* method for supported features."""
last_message: str = ""
for feature_item in self._features:
full_feature = feature_item.split("@", 2)[0]
feature = full_feature.split(":", 2)[0]
func_str = "require_{}".format(feature.replace("-", "_"))
func = getattr(self, func_str, None)
if not func:
last_message = f"require() unsupported requirement: {feature}"
wandb.termwarn(last_message)
continue
func()
if last_message:
wandb.termerror(
f"Supported wandb.require() features can be found at: {wburls.get('doc_require')}"
)
raise UnsupportedError(last_message) | python | wandb/sdk/wandb_require.py | 41 | 59 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,184 | require | def require(
requirement: Optional[Union[str, Sequence[str]]] = None,
experiment: Optional[Union[str, Sequence[str]]] = None,
) -> None:
"""Indicate which experimental features are used by the script.
Args:
requirement: (str or list) Features to require
experiment: (str or list) Features to require
Raises:
wandb.errors.UnsupportedError: if not supported
"""
features = requirement or experiment
if not features:
return
f = _Requires(features=features)
f.apply() | python | wandb/sdk/wandb_require.py | 62 | 80 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,185 | _import_module_hook | def _import_module_hook() -> None:
"""On wandb import, setup anything needed based on parent process require calls."""
# TODO: optimize by caching which pids this has been done for or use real import hooks
# TODO: make this more generic, but for now this works
require("service") | python | wandb/sdk/wandb_require.py | 83 | 87 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,186 | _get_sweep_url | def _get_sweep_url(api, sweep_id):
"""Return sweep url if we can figure it out."""
if api.api_key:
if api.settings("entity") is None:
viewer = api.viewer()
if viewer.get("entity"):
api.set_setting("entity", viewer["entity"])
project = api.settings("project")
if not project:
return
if api.settings("entity"):
return "{base}/{entity}/{project}/sweeps/{sweepid}".format(
base=api.app_url,
entity=urllib.parse.quote(api.settings("entity")),
project=urllib.parse.quote(project),
sweepid=urllib.parse.quote(sweep_id),
) | python | wandb/sdk/wandb_sweep.py | 12 | 28 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,187 | sweep | def sweep(
sweep: Union[dict, Callable],
entity: Optional[str] = None,
project: Optional[str] = None,
) -> str:
"""Initialize a hyperparameter sweep.
To generate hyperparameter suggestions from the sweep and use them
to train a model, call `wandb.agent` with the sweep_id returned by
this command. For command line functionality, see the command line
tool `wandb sweep` (https://docs.wandb.ai/ref/cli/wandb-sweep).
Args:
sweep: dict, SweepConfig, or callable. The sweep configuration
(or configuration generator). If a dict or SweepConfig,
should conform to the W&B sweep config specification
(https://docs.wandb.ai/guides/sweeps/define-sweep-configuration). If a
callable, should take no arguments and return a dict that
conforms to the W&B sweep config spec.
entity: str (optional). An entity is a username or team name
where you're sending runs. This entity must exist before you
can send runs there, so make sure to create your account or
team in the UI before starting to log runs. If you don't
specify an entity, the run will be sent to your default
entity, which is usually your username. Change your default
entity in [Settings](https://wandb.ai/settings) under "default
location to create new projects".
project: str (optional). The name of the project where you're
sending the new run. If the project is not specified, the
run is put in an "Uncategorized" project.
Returns:
sweep_id: str. A unique identifier for the sweep.
Examples:
Basic usage
<!--yeadoc-test:one-parameter-sweep-->
```python
import wandb
sweep_configuration = {
"name": "my-awesome-sweep",
"metric": {"name": "accuracy", "goal": "maximize"},
"method": "grid",
"parameters": {"a": {"values": [1, 2, 3, 4]}},
}
def my_train_func():
# read the current value of parameter "a" from wandb.config
wandb.init()
a = wandb.config.a
wandb.log({"a": a, "accuracy": a + 1})
sweep_id = wandb.sweep(sweep_configuration)
# run the sweep
wandb.agent(sweep_id, function=my_train_func)
```
"""
if callable(sweep):
sweep = sweep()
"""Sweep create for controller api and jupyter (eventually for cli)."""
# Project may be only found in the sweep config.
if project is None and isinstance(sweep, dict):
project = sweep.get("project", None)
if entity:
env.set_entity(entity)
if project:
env.set_project(project)
# Make sure we are logged in
if wandb.run is None:
wandb_login._login(_silent=True)
api = InternalApi()
sweep_id, warnings = api.upsert_sweep(sweep)
handle_sweep_config_violations(warnings)
print("Create sweep with ID:", sweep_id)
sweep_url = _get_sweep_url(api, sweep_id)
if sweep_url:
print("Sweep URL:", sweep_url)
return sweep_id | python | wandb/sdk/wandb_sweep.py | 31 | 116 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,188 | controller | def controller(
sweep_id_or_config: Optional[Union[str, Dict]] = None,
entity: Optional[str] = None,
project: Optional[str] = None,
):
"""Public sweep controller constructor.
Usage:
```python
import wandb
tuner = wandb.controller(...)
print(tuner.sweep_config)
print(tuner.sweep_id)
tuner.configure_search(...)
tuner.configure_stopping(...)
```
"""
from ..wandb_controller import _WandbController
c = _WandbController(
sweep_id_or_config=sweep_id_or_config, entity=entity, project=project
)
return c | python | wandb/sdk/wandb_sweep.py | 119 | 143 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,189 | __init__ | def __init__(self, token: str) -> None:
self._token_str = token
self._parse() | python | wandb/sdk/wandb_manager.py | 46 | 48 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,190 | from_environment | def from_environment(cls) -> Optional["_ManagerToken"]:
token = os.environ.get(env.SERVICE)
if not token:
return None
return cls(token=token) | python | wandb/sdk/wandb_manager.py | 51 | 55 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,191 | from_params | def from_params(cls, transport: str, host: str, port: int) -> "_ManagerToken":
version = cls._version
pid = os.getpid()
token = "-".join([version, str(pid), transport, host, str(port)])
return cls(token=token) | python | wandb/sdk/wandb_manager.py | 58 | 62 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,192 | set_environment | def set_environment(self) -> None:
os.environ[env.SERVICE] = self._token_str | python | wandb/sdk/wandb_manager.py | 64 | 65 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,193 | _parse | def _parse(self) -> None:
assert self._token_str
parts = self._token_str.split("-")
assert len(parts) == 5, f"token must have 5 parts: {parts}"
# TODO: make more robust?
version, pid_str, transport, host, port_str = parts
assert version == self._version
assert transport in self._supported_transports
self._pid = int(pid_str)
self._transport = transport
self._host = host
self._port = int(port_str) | python | wandb/sdk/wandb_manager.py | 67 | 78 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,194 | reset_environment | def reset_environment(self) -> None:
os.environ.pop(env.SERVICE, None) | python | wandb/sdk/wandb_manager.py | 80 | 81 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,195 | token | def token(self) -> str:
return self._token_str | python | wandb/sdk/wandb_manager.py | 84 | 85 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,196 | pid | def pid(self) -> int:
return self._pid | python | wandb/sdk/wandb_manager.py | 88 | 89 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,197 | transport | def transport(self) -> str:
return self._transport | python | wandb/sdk/wandb_manager.py | 92 | 93 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,198 | host | def host(self) -> str:
return self._host | python | wandb/sdk/wandb_manager.py | 96 | 97 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,199 | port | def port(self) -> int:
return self._port | python | wandb/sdk/wandb_manager.py | 100 | 101 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,200 | _service_connect | def _service_connect(self) -> None:
port = self._token.port
svc_iface = self._get_service_interface()
try:
svc_iface._svc_connect(port=port)
except ConnectionRefusedError as e:
if not psutil.pid_exists(self._token.pid):
message = (
"Connection to wandb service failed "
"since the process is not available. "
)
else:
message = f"Connection to wandb service failed: {e}. "
raise ManagerConnectionRefusedError(message)
except Exception as e:
raise ManagerConnectionError(f"Connection to wandb service failed: {e}") | python | wandb/sdk/wandb_manager.py | 111 | 127 | {
"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.