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,001 | scheme | def scheme(self) -> str:
return self._scheme | python | wandb/sdk/wandb_artifacts.py | 1,334 | 1,335 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,002 | init_boto | def init_boto(self) -> "boto3.resources.base.ServiceResource":
if self._s3 is not None:
return self._s3
boto: "boto3" = util.get_module(
"boto3",
required="s3:// references requires the boto3 library, run pip install wandb[aws]",
lazy=False,
)
self._s3 = boto.session.Session().resource(
"s3",
endpoint_url=os.getenv("AWS_S3_ENDPOINT_URL"),
region_name=os.getenv("AWS_REGION"),
)
self._botocore = util.get_module("botocore")
return self._s3 | python | wandb/sdk/wandb_artifacts.py | 1,337 | 1,351 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,003 | _parse_uri | def _parse_uri(self, uri: str) -> Tuple[str, str, Optional[str]]:
url = urlparse(uri)
query = dict(parse_qsl(url.query))
bucket = url.netloc
key = url.path[1:] # strip leading slash
version = query.get("versionId")
return bucket, key, version | python | wandb/sdk/wandb_artifacts.py | 1,353 | 1,361 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,004 | versioning_enabled | def versioning_enabled(self, bucket: str) -> bool:
self.init_boto()
assert self._s3 is not None # mypy: unwraps optionality
if self._versioning_enabled is not None:
return self._versioning_enabled
res = self._s3.BucketVersioning(bucket)
self._versioning_enabled = res.status == "Enabled"
return self._versioning_enabled | python | wandb/sdk/wandb_artifacts.py | 1,363 | 1,370 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,005 | load_path | def load_path(
self,
manifest_entry: ArtifactManifestEntry,
local: bool = False,
) -> Union[URIStr, FilePathStr]:
if not local:
assert manifest_entry.ref is not None
return manifest_entry.ref
assert manifest_entry.ref is not None
path, hit, cache_open = self._cache.check_etag_obj_path(
URIStr(manifest_entry.ref),
ETag(manifest_entry.digest), # TODO(spencerpearson): unsafe cast
manifest_entry.size if manifest_entry.size is not None else 0,
)
if hit:
return path
self.init_boto()
assert self._s3 is not None # mypy: unwraps optionality
bucket, key, _ = self._parse_uri(manifest_entry.ref)
version = manifest_entry.extra.get("versionID")
extra_args = {}
if version is None:
# We don't have version information so just get the latest version
# and fallback to listing all versions if we don't have a match.
obj = self._s3.Object(bucket, key)
etag = self._etag_from_obj(obj)
if etag != manifest_entry.digest:
if self.versioning_enabled(bucket):
# Fallback to listing versions
obj = None
object_versions = self._s3.Bucket(bucket).object_versions.filter(
Prefix=key
)
for object_version in object_versions:
if (
manifest_entry.extra.get("etag")
== object_version.e_tag[1:-1]
):
obj = object_version.Object()
extra_args["VersionId"] = object_version.version_id
break
if obj is None:
raise ValueError(
"Couldn't find object version for %s/%s matching etag %s"
% (bucket, key, manifest_entry.extra.get("etag"))
)
else:
raise ValueError(
"Digest mismatch for object %s: expected %s but found %s"
% (manifest_entry.ref, manifest_entry.digest, etag)
)
else:
obj = self._s3.ObjectVersion(bucket, key, version).Object()
extra_args["VersionId"] = version
with cache_open(mode="wb") as f:
obj.download_fileobj(f, ExtraArgs=extra_args)
return path | python | wandb/sdk/wandb_artifacts.py | 1,372 | 1,433 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,006 | store_path | def store_path(
self,
artifact: ArtifactInterface,
path: Union[URIStr, FilePathStr],
name: Optional[str] = None,
checksum: bool = True,
max_objects: Optional[int] = None,
) -> Sequence[ArtifactManifestEntry]:
self.init_boto()
assert self._s3 is not None # mypy: unwraps optionality
# The passed in path might have query string parameters.
# We only need to care about a subset, like version, when
# parsing. Once we have that, we can store the rest of the
# metadata in the artifact entry itself.
bucket, key, version = self._parse_uri(path)
path = URIStr(f"{self.scheme}://{bucket}/{key}")
if not self.versioning_enabled(bucket) and version:
raise ValueError(
f"Specifying a versionId is not valid for s3://{bucket} as it does not have versioning enabled."
)
max_objects = max_objects or DEFAULT_MAX_OBJECTS
if not checksum:
return [
ArtifactManifestEntry(
path=LogicalFilePathStr(name or key), ref=path, digest=path
)
]
# If an explicit version is specified, use that. Otherwise, use the head version.
objs = (
[self._s3.ObjectVersion(bucket, key, version).Object()]
if version
else [self._s3.Object(bucket, key)]
)
start_time = None
multi = False
try:
objs[0].load()
# S3 doesn't have real folders, however there are cases where the folder key has a valid file which will not
# trigger a recursive upload.
# we should check the object's metadata says it is a directory and do a multi file upload if it is
if "x-directory" in objs[0].content_type:
multi = True
except self._botocore.exceptions.ClientError as e:
if e.response["Error"]["Code"] == "404":
multi = True
else:
raise CommError(
"Unable to connect to S3 (%s): %s"
% (e.response["Error"]["Code"], e.response["Error"]["Message"])
)
if multi:
start_time = time.time()
termlog(
'Generating checksum for up to %i objects with prefix "%s"... '
% (max_objects, key),
newline=False,
)
objs = self._s3.Bucket(bucket).objects.filter(Prefix=key).limit(max_objects)
# Weird iterator scoping makes us assign this to a local function
size = self._size_from_obj
entries = [
self._entry_from_obj(obj, path, name, prefix=key, multi=multi)
for obj in objs
if size(obj) > 0
]
if start_time is not None:
termlog("Done. %.1fs" % (time.time() - start_time), prefix=False)
if len(entries) > max_objects:
raise ValueError(
"Exceeded %i objects tracked, pass max_objects to add_reference"
% max_objects
)
return entries | python | wandb/sdk/wandb_artifacts.py | 1,435 | 1,510 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,007 | _size_from_obj | def _size_from_obj(self, obj: "boto3.s3.Object") -> int:
# ObjectSummary has size, Object has content_length
size: int
if hasattr(obj, "size"):
size = obj.size
else:
size = obj.content_length
return size | python | wandb/sdk/wandb_artifacts.py | 1,512 | 1,519 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,008 | _entry_from_obj | def _entry_from_obj(
self,
obj: "boto3.s3.Object",
path: str,
name: Optional[str] = None,
prefix: str = "",
multi: bool = False,
) -> ArtifactManifestEntry:
"""Create an ArtifactManifestEntry from an S3 object.
Arguments:
obj: The S3 object
path: The S3-style path (e.g.: "s3://bucket/file.txt")
name: The user assigned name, or None if not specified
prefix: The prefix to add (will be the same as `path` for directories)
multi: Whether or not this is a multi-object add.
"""
bucket, key, _ = self._parse_uri(path)
# Always use posix paths, since that's what S3 uses.
posix_key = pathlib.PurePosixPath(obj.key) # the bucket key
posix_path = pathlib.PurePosixPath(bucket) / pathlib.PurePosixPath(
key
) # the path, with the scheme stripped
posix_prefix = pathlib.PurePosixPath(prefix) # the prefix, if adding a prefix
posix_name = pathlib.PurePosixPath(name or "")
posix_ref = posix_path
if name is None:
# We're adding a directory (prefix), so calculate a relative path.
if str(posix_prefix) in str(posix_key) and posix_prefix != posix_key:
posix_name = posix_key.relative_to(posix_prefix)
posix_ref = posix_path / posix_name
else:
posix_name = pathlib.PurePosixPath(posix_key.name)
posix_ref = posix_path
elif multi:
# We're adding a directory with a name override.
relpath = posix_key.relative_to(posix_prefix)
posix_name = posix_name / relpath
posix_ref = posix_path / relpath
return ArtifactManifestEntry(
path=LogicalFilePathStr(str(posix_name)),
ref=URIStr(f"{self.scheme}://{str(posix_ref)}"),
digest=ETag(self._etag_from_obj(obj)),
size=self._size_from_obj(obj),
extra=self._extra_from_obj(obj),
) | python | wandb/sdk/wandb_artifacts.py | 1,521 | 1,568 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,009 | _etag_from_obj | def _etag_from_obj(obj: "boto3.s3.Object") -> ETag:
etag: ETag
etag = obj.e_tag[1:-1] # escape leading and trailing quote
return etag | python | wandb/sdk/wandb_artifacts.py | 1,571 | 1,574 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,010 | _extra_from_obj | def _extra_from_obj(obj: "boto3.s3.Object") -> Dict[str, str]:
extra = {
"etag": obj.e_tag[1:-1], # escape leading and trailing quote
}
# ObjectSummary will never have version_id
if hasattr(obj, "version_id") and obj.version_id != "null":
extra["versionID"] = obj.version_id
return extra | python | wandb/sdk/wandb_artifacts.py | 1,577 | 1,584 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,011 | _content_addressed_path | def _content_addressed_path(md5: str) -> FilePathStr:
# TODO: is this the structure we want? not at all human
# readable, but that's probably OK. don't want people
# poking around in the bucket
return FilePathStr(
"wandb/%s" % base64.b64encode(md5.encode("ascii")).decode("ascii")
) | python | wandb/sdk/wandb_artifacts.py | 1,587 | 1,593 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,012 | __init__ | def __init__(self, scheme: Optional[str] = None) -> None:
self._scheme = scheme or "gs"
self._client = None
self._versioning_enabled = None
self._cache = get_artifacts_cache() | python | wandb/sdk/wandb_artifacts.py | 1,600 | 1,604 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,013 | versioning_enabled | def versioning_enabled(self, bucket_path: str) -> bool:
if self._versioning_enabled is not None:
return self._versioning_enabled
self.init_gcs()
assert self._client is not None # mypy: unwraps optionality
bucket = self._client.bucket(bucket_path)
bucket.reload()
self._versioning_enabled = bucket.versioning_enabled
return self._versioning_enabled | python | wandb/sdk/wandb_artifacts.py | 1,606 | 1,614 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,014 | scheme | def scheme(self) -> str:
return self._scheme | python | wandb/sdk/wandb_artifacts.py | 1,617 | 1,618 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,015 | init_gcs | def init_gcs(self) -> "gcs_module.client.Client":
if self._client is not None:
return self._client
storage = util.get_module(
"google.cloud.storage",
required="gs:// references requires the google-cloud-storage library, run pip install wandb[gcp]",
)
self._client = storage.Client()
return self._client | python | wandb/sdk/wandb_artifacts.py | 1,620 | 1,628 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,016 | _parse_uri | def _parse_uri(self, uri: str) -> Tuple[str, str, Optional[str]]:
url = urlparse(uri)
bucket = url.netloc
key = url.path[1:]
version = url.fragment if url.fragment else None
return bucket, key, version | python | wandb/sdk/wandb_artifacts.py | 1,630 | 1,635 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,017 | load_path | def load_path(
self,
manifest_entry: ArtifactManifestEntry,
local: bool = False,
) -> Union[URIStr, FilePathStr]:
if not local:
assert manifest_entry.ref is not None
return manifest_entry.ref
path, hit, cache_open = self._cache.check_md5_obj_path(
B64MD5(manifest_entry.digest), # TODO(spencerpearson): unsafe cast
manifest_entry.size if manifest_entry.size is not None else 0,
)
if hit:
return path
self.init_gcs()
assert self._client is not None # mypy: unwraps optionality
assert manifest_entry.ref is not None
bucket, key, _ = self._parse_uri(manifest_entry.ref)
version = manifest_entry.extra.get("versionID")
obj = None
# First attempt to get the generation specified, this will return None if versioning is not enabled
if version is not None:
obj = self._client.bucket(bucket).get_blob(key, generation=version)
if obj is None:
# Object versioning is disabled on the bucket, so just get
# the latest version and make sure the MD5 matches.
obj = self._client.bucket(bucket).get_blob(key)
if obj is None:
raise ValueError(
"Unable to download object %s with generation %s"
% (manifest_entry.ref, version)
)
md5 = obj.md5_hash
if md5 != manifest_entry.digest:
raise ValueError(
"Digest mismatch for object %s: expected %s but found %s"
% (manifest_entry.ref, manifest_entry.digest, md5)
)
with cache_open(mode="wb") as f:
obj.download_to_file(f)
return path | python | wandb/sdk/wandb_artifacts.py | 1,637 | 1,682 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,018 | store_path | def store_path(
self,
artifact: ArtifactInterface,
path: Union[URIStr, FilePathStr],
name: Optional[str] = None,
checksum: bool = True,
max_objects: Optional[int] = None,
) -> Sequence[ArtifactManifestEntry]:
self.init_gcs()
assert self._client is not None # mypy: unwraps optionality
# After parsing any query params / fragments for additional context,
# such as version identifiers, pare down the path to just the bucket
# and key.
bucket, key, version = self._parse_uri(path)
path = URIStr(f"{self.scheme}://{bucket}/{key}")
max_objects = max_objects or DEFAULT_MAX_OBJECTS
if not self.versioning_enabled(bucket) and version:
raise ValueError(
f"Specifying a versionId is not valid for s3://{bucket} as it does not have versioning enabled."
)
if not checksum:
return [
ArtifactManifestEntry(
path=LogicalFilePathStr(name or key), ref=path, digest=path
)
]
start_time = None
obj = self._client.bucket(bucket).get_blob(key, generation=version)
multi = obj is None
if multi:
start_time = time.time()
termlog(
'Generating checksum for up to %i objects with prefix "%s"... '
% (max_objects, key),
newline=False,
)
objects = self._client.bucket(bucket).list_blobs(
prefix=key, max_results=max_objects
)
else:
objects = [obj]
entries = [
self._entry_from_obj(obj, path, name, prefix=key, multi=multi)
for obj in objects
]
if start_time is not None:
termlog("Done. %.1fs" % (time.time() - start_time), prefix=False)
if len(entries) > max_objects:
raise ValueError(
"Exceeded %i objects tracked, pass max_objects to add_reference"
% max_objects
)
return entries | python | wandb/sdk/wandb_artifacts.py | 1,684 | 1,740 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,019 | _entry_from_obj | def _entry_from_obj(
self,
obj: "gcs_module.blob.Blob",
path: str,
name: Optional[str] = None,
prefix: str = "",
multi: bool = False,
) -> ArtifactManifestEntry:
"""Create an ArtifactManifestEntry from a GCS object.
Arguments:
obj: The GCS object
path: The GCS-style path (e.g.: "gs://bucket/file.txt")
name: The user assigned name, or None if not specified
prefix: The prefix to add (will be the same as `path` for directories)
multi: Whether or not this is a multi-object add.
"""
bucket, key, _ = self._parse_uri(path)
# Always use posix paths, since that's what S3 uses.
posix_key = pathlib.PurePosixPath(obj.name) # the bucket key
posix_path = pathlib.PurePosixPath(bucket) / pathlib.PurePosixPath(
key
) # the path, with the scheme stripped
posix_prefix = pathlib.PurePosixPath(prefix) # the prefix, if adding a prefix
posix_name = pathlib.PurePosixPath(name or "")
posix_ref = posix_path
if name is None:
# We're adding a directory (prefix), so calculate a relative path.
if str(posix_prefix) in str(posix_key) and posix_prefix != posix_key:
posix_name = posix_key.relative_to(posix_prefix)
posix_ref = posix_path / posix_name
else:
posix_name = pathlib.PurePosixPath(posix_key.name)
posix_ref = posix_path
elif multi:
# We're adding a directory with a name override.
relpath = posix_key.relative_to(posix_prefix)
posix_name = posix_name / relpath
posix_ref = posix_path / relpath
return ArtifactManifestEntry(
path=LogicalFilePathStr(str(posix_name)),
ref=URIStr(f"{self.scheme}://{str(posix_ref)}"),
digest=obj.md5_hash,
size=obj.size,
extra=self._extra_from_obj(obj),
) | python | wandb/sdk/wandb_artifacts.py | 1,742 | 1,789 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,020 | _extra_from_obj | def _extra_from_obj(obj: "gcs_module.blob.Blob") -> Dict[str, str]:
return {
"etag": obj.etag,
"versionID": obj.generation,
} | python | wandb/sdk/wandb_artifacts.py | 1,792 | 1,796 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,021 | _content_addressed_path | def _content_addressed_path(md5: str) -> FilePathStr:
# TODO: is this the structure we want? not at all human
# readable, but that's probably OK. don't want people
# poking around in the bucket
return FilePathStr(
"wandb/%s" % base64.b64encode(md5.encode("ascii")).decode("ascii")
) | python | wandb/sdk/wandb_artifacts.py | 1,799 | 1,805 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,022 | __init__ | def __init__(self, session: requests.Session, scheme: Optional[str] = None) -> None:
self._scheme = scheme or "http"
self._cache = get_artifacts_cache()
self._session = session | python | wandb/sdk/wandb_artifacts.py | 1,809 | 1,812 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,023 | scheme | def scheme(self) -> str:
return self._scheme | python | wandb/sdk/wandb_artifacts.py | 1,815 | 1,816 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,024 | load_path | def load_path(
self,
manifest_entry: ArtifactManifestEntry,
local: bool = False,
) -> Union[URIStr, FilePathStr]:
if not local:
assert manifest_entry.ref is not None
return manifest_entry.ref
assert manifest_entry.ref is not None
path, hit, cache_open = self._cache.check_etag_obj_path(
URIStr(manifest_entry.ref),
ETag(manifest_entry.digest), # TODO(spencerpearson): unsafe cast
manifest_entry.size if manifest_entry.size is not None else 0,
)
if hit:
return path
response = self._session.get(manifest_entry.ref, stream=True)
response.raise_for_status()
digest: Optional[Union[ETag, FilePathStr, URIStr]]
digest, size, extra = self._entry_from_headers(response.headers)
digest = digest or manifest_entry.ref
if manifest_entry.digest != digest:
raise ValueError(
"Digest mismatch for url %s: expected %s but found %s"
% (manifest_entry.ref, manifest_entry.digest, digest)
)
with cache_open(mode="wb") as file:
for data in response.iter_content(chunk_size=16 * 1024):
file.write(data)
return path | python | wandb/sdk/wandb_artifacts.py | 1,818 | 1,852 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,025 | store_path | def store_path(
self,
artifact: ArtifactInterface,
path: Union[URIStr, FilePathStr],
name: Optional[str] = None,
checksum: bool = True,
max_objects: Optional[int] = None,
) -> Sequence[ArtifactManifestEntry]:
name = LogicalFilePathStr(name or os.path.basename(path))
if not checksum:
return [ArtifactManifestEntry(path=name, ref=path, digest=path)]
with self._session.get(path, stream=True) as response:
response.raise_for_status()
digest: Optional[Union[ETag, FilePathStr, URIStr]]
digest, size, extra = self._entry_from_headers(response.headers)
digest = digest or path
return [
ArtifactManifestEntry(
path=name, ref=path, digest=digest, size=size, extra=extra
)
] | python | wandb/sdk/wandb_artifacts.py | 1,854 | 1,875 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,026 | _entry_from_headers | def _entry_from_headers(
self, headers: requests.structures.CaseInsensitiveDict
) -> Tuple[Optional[ETag], Optional[int], Dict[str, str]]:
response_headers = {k.lower(): v for k, v in headers.items()}
size = None
if response_headers.get("content-length", None):
size = int(response_headers["content-length"])
digest = response_headers.get("etag", None)
extra = {}
if digest:
extra["etag"] = digest
if digest and digest[:1] == '"' and digest[-1:] == '"':
digest = digest[1:-1] # trim leading and trailing quotes around etag
return digest, size, extra | python | wandb/sdk/wandb_artifacts.py | 1,877 | 1,891 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,027 | __init__ | def __init__(self) -> None:
self._scheme = "wandb-artifact"
self._cache = get_artifacts_cache()
self._client = None | python | wandb/sdk/wandb_artifacts.py | 1,899 | 1,902 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,028 | scheme | def scheme(self) -> str:
"""Scheme this handler applies to."""
return self._scheme | python | wandb/sdk/wandb_artifacts.py | 1,905 | 1,907 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,029 | client | def client(self) -> PublicApi:
if self._client is None:
self._client = PublicApi()
return self._client | python | wandb/sdk/wandb_artifacts.py | 1,910 | 1,913 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,030 | load_path | def load_path(
self,
manifest_entry: ArtifactManifestEntry,
local: bool = False,
) -> Union[URIStr, FilePathStr]:
"""Load the file in the specified artifact given its corresponding entry.
Download the referenced artifact; create and return a new symlink to the caller.
Arguments:
manifest_entry (ArtifactManifestEntry): The index entry to load
Returns:
(os.PathLike): A path to the file represented by `index_entry`
"""
# We don't check for cache hits here. Since we have 0 for size (since this
# is a cross-artifact reference which and we've made the choice to store 0
# in the size field), we can't confirm if the file is complete. So we just
# rely on the dep_artifact entry's download() method to do its own cache
# check.
# Parse the reference path and download the artifact if needed
artifact_id = util.host_from_path(manifest_entry.ref)
artifact_file_path = util.uri_from_path(manifest_entry.ref)
dep_artifact = PublicArtifact.from_id(hex_to_b64_id(artifact_id), self.client)
link_target_path: FilePathStr
if local:
link_target_path = dep_artifact.get_path(artifact_file_path).download()
else:
link_target_path = dep_artifact.get_path(artifact_file_path).ref_target()
return link_target_path | python | wandb/sdk/wandb_artifacts.py | 1,915 | 1,947 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,031 | store_path | def store_path(
self,
artifact: ArtifactInterface,
path: Union[URIStr, FilePathStr],
name: Optional[str] = None,
checksum: bool = True,
max_objects: Optional[int] = None,
) -> Sequence[ArtifactManifestEntry]:
"""Store the file or directory at the given path into the specified artifact.
Recursively resolves the reference until the result is a concrete asset.
Arguments:
artifact: The artifact doing the storing path (str): The path to store name
(str): If specified, the logical name that should map to `path`
Returns:
(list[ArtifactManifestEntry]): A list of manifest entries to store within
the artifact
"""
# Recursively resolve the reference until a concrete asset is found
# TODO: Consider resolving server-side for performance improvements.
while path is not None and urlparse(path).scheme == self._scheme:
artifact_id = util.host_from_path(path)
artifact_file_path = util.uri_from_path(path)
target_artifact = PublicArtifact.from_id(
hex_to_b64_id(artifact_id), self.client
)
# this should only have an effect if the user added the reference by url
# string directly (in other words they did not already load the artifact into ram.)
target_artifact._load_manifest()
entry = target_artifact._manifest.get_entry_by_path(artifact_file_path)
path = entry.ref
# Create the path reference
path = URIStr(
"{}://{}/{}".format(
self._scheme,
b64_to_hex_id(target_artifact.id),
artifact_file_path,
)
)
# Return the new entry
return [
ArtifactManifestEntry(
path=LogicalFilePathStr(name or os.path.basename(path)),
ref=path,
size=0,
digest=entry.digest,
)
] | python | wandb/sdk/wandb_artifacts.py | 1,949 | 2,002 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,032 | __init__ | def __init__(self) -> None:
self._scheme = "wandb-client-artifact"
self._cache = get_artifacts_cache() | python | wandb/sdk/wandb_artifacts.py | 2,010 | 2,012 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,033 | scheme | def scheme(self) -> str:
"""Scheme this handler applies to."""
return self._scheme | python | wandb/sdk/wandb_artifacts.py | 2,015 | 2,017 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,034 | load_path | def load_path(
self,
manifest_entry: ArtifactManifestEntry,
local: bool = False,
) -> Union[URIStr, FilePathStr]:
raise NotImplementedError(
"Should not be loading a path for an artifact entry with unresolved client id."
) | python | wandb/sdk/wandb_artifacts.py | 2,019 | 2,026 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,035 | store_path | def store_path(
self,
artifact: ArtifactInterface,
path: Union[URIStr, FilePathStr],
name: Optional[str] = None,
checksum: bool = True,
max_objects: Optional[int] = None,
) -> Sequence[ArtifactManifestEntry]:
"""Store the file or directory at the given path within the specified artifact.
Arguments:
artifact: The artifact doing the storing
path (str): The path to store
name (str): If specified, the logical name that should map to `path`
Returns:
(list[ArtifactManifestEntry]): A list of manifest entries to store within the artifact
"""
client_id = util.host_from_path(path)
target_path = util.uri_from_path(path)
target_artifact = self._cache.get_client_artifact(client_id)
if not isinstance(target_artifact, Artifact):
raise RuntimeError("Local Artifact not found - invalid reference")
target_entry = target_artifact._manifest.entries[target_path]
if target_entry is None:
raise RuntimeError("Local entry not found - invalid reference")
# Return the new entry
return [
ArtifactManifestEntry(
path=LogicalFilePathStr(name or os.path.basename(path)),
ref=path,
size=0,
digest=target_entry.digest,
)
] | python | wandb/sdk/wandb_artifacts.py | 2,028 | 2,063 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,036 | _set_logger | def _set_logger(log_object: logging.Logger) -> None:
"""Configure module logger."""
global logger
logger = log_object | python | wandb/sdk/wandb_init.py | 56 | 59 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,037 | _huggingface_version | def _huggingface_version() -> Optional[str]:
if "transformers" in sys.modules:
trans = wandb.util.get_module("transformers")
if hasattr(trans, "__version__"):
return str(trans.__version__)
return None | python | wandb/sdk/wandb_init.py | 62 | 67 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,038 | _maybe_mp_process | def _maybe_mp_process(backend: Backend) -> bool:
parent_process = getattr(
backend._multiprocessing, "parent_process", None
) # New in version 3.8.
if parent_process:
return parent_process() is not None
process = backend._multiprocessing.current_process()
if process.name == "MainProcess":
return False
if process.name.startswith("Process-"):
return True
return False | python | wandb/sdk/wandb_init.py | 70 | 81 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,039 | _handle_launch_config | def _handle_launch_config(settings: "Settings") -> Dict[str, Any]:
launch_run_config: Dict[str, Any] = {}
if not settings.launch:
return launch_run_config
if os.environ.get("WANDB_CONFIG") is not None:
try:
launch_run_config = json.loads(os.environ.get("WANDB_CONFIG", "{}"))
except (ValueError, SyntaxError):
wandb.termwarn("Malformed WANDB_CONFIG, using original config")
elif settings.launch_config_path and os.path.exists(settings.launch_config_path):
with open(settings.launch_config_path) as fp:
launch_config = json.loads(fp.read())
launch_run_config = launch_config.get("overrides", {}).get("run_config")
return launch_run_config | python | wandb/sdk/wandb_init.py | 84 | 97 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,040 | __init__ | def __init__(self) -> None:
self.kwargs = None
self.settings: Optional[Settings] = None
self.sweep_config: Dict[str, Any] = {}
self.launch_config: Dict[str, Any] = {}
self.config: Dict[str, Any] = {}
self.run: Optional[Run] = None
self.backend: Optional[Backend] = None
self._teardown_hooks: List[TeardownHook] = []
self._wl: Optional[wandb_setup._WandbSetup] = None
self._reporter: Optional[wandb.sdk.lib.reporting.Reporter] = None
self.notebook: Optional["wandb.jupyter.Notebook"] = None # type: ignore
self.printer: Optional[Printer] = None
self._init_telemetry_obj = telemetry.TelemetryRecord()
self.deprecated_features_used: Dict[str, str] = dict() | python | wandb/sdk/wandb_init.py | 103 | 120 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,041 | _setup_printer | def _setup_printer(self, settings: Settings) -> None:
if self.printer:
return
self.printer = get_printer(settings._jupyter) | python | wandb/sdk/wandb_init.py | 122 | 125 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,042 | setup | def setup(self, kwargs: Any) -> None: # noqa: C901
"""Complete setup for `wandb.init()`.
This includes parsing all arguments, applying them with settings and enabling logging.
"""
self.kwargs = kwargs
# if the user ran, for example, `wandb.login(`) before `wandb.init()`,
# the singleton will already be set up and so if e.g. env vars are set
# in between, they will be ignored, which we need to inform the user about.
singleton = wandb_setup._WandbSetup._instance
if singleton is not None:
self._setup_printer(settings=singleton._settings)
assert self.printer
exclude_env_vars = {"WANDB_SERVICE", "WANDB_KUBEFLOW_URL"}
# check if environment variables have changed
singleton_env = {
k: v
for k, v in singleton._environ.items()
if k.startswith("WANDB_") and k not in exclude_env_vars
}
os_env = {
k: v
for k, v in os.environ.items()
if k.startswith("WANDB_") and k not in exclude_env_vars
}
if set(singleton_env.keys()) != set(os_env.keys()) or set(
singleton_env.values()
) != set(os_env.values()):
line = (
"Changes to your `wandb` environment variables will be ignored "
"because your `wandb` session has already started. "
"For more information on how to modify your settings with "
"`wandb.init()` arguments, please refer to "
f"{self.printer.link(wburls.get('wandb_init'), 'the W&B docs')}."
)
self.printer.display(line, level="warn")
# we add this logic to be backward compatible with the old behavior of disable
# where it would disable the service if the mode was set to disabled
mode = kwargs.get("mode")
settings_mode = (kwargs.get("settings") or {}).get("mode")
_disable_service = mode == "disabled" or settings_mode == "disabled"
setup_settings = {"_disable_service": _disable_service}
self._wl = wandb_setup.setup(settings=setup_settings)
# Make sure we have a logger setup (might be an early logger)
assert self._wl is not None
_set_logger(self._wl._get_logger())
# Start with settings from wandb library singleton
settings: Settings = self._wl.settings.copy()
# when using launch, we don't want to reuse the same run id from the singleton
# since users might launch multiple runs in the same process
# TODO(kdg): allow users to control this via launch settings
if settings.launch and singleton is not None:
settings.update({"run_id": None}, source=Source.INIT)
settings_param = kwargs.pop("settings", None)
if settings_param is not None and isinstance(settings_param, (Settings, dict)):
settings.update(settings_param, source=Source.INIT)
self._setup_printer(settings)
self._reporter = reporting.setup_reporter(settings=settings)
sagemaker_config: Dict = (
dict() if settings.sagemaker_disable else sagemaker.parse_sm_config()
)
if sagemaker_config:
sagemaker_api_key = sagemaker_config.get("wandb_api_key", None)
sagemaker_run, sagemaker_env = sagemaker.parse_sm_resources()
if sagemaker_env:
if sagemaker_api_key:
sagemaker_env["WANDB_API_KEY"] = sagemaker_api_key
settings._apply_env_vars(sagemaker_env)
wandb.setup(settings=settings)
settings.update(sagemaker_run, source=Source.SETUP)
with telemetry.context(obj=self._init_telemetry_obj) as tel:
tel.feature.sagemaker = True
with telemetry.context(obj=self._init_telemetry_obj) as tel:
if kwargs.get("config"):
tel.feature.set_init_config = True
if kwargs.get("name"):
tel.feature.set_init_name = True
if kwargs.get("id"):
tel.feature.set_init_id = True
if kwargs.get("tags"):
tel.feature.set_init_tags = True
# Remove parameters that are not part of settings
init_config = kwargs.pop("config", None) or dict()
# todo: remove this once officially deprecated
deprecated_kwargs = {
"config_include_keys": (
"Use `config=wandb.helper.parse_config(config_object, include=('key',))` instead."
),
"config_exclude_keys": (
"Use `config=wandb.helper.parse_config(config_object, exclude=('key',))` instead."
),
}
for deprecated_kwarg, msg in deprecated_kwargs.items():
if kwargs.get(deprecated_kwarg):
self.deprecated_features_used[deprecated_kwarg] = msg
init_config = parse_config(
init_config,
include=kwargs.pop("config_include_keys", None),
exclude=kwargs.pop("config_exclude_keys", None),
)
# merge config with sweep or sagemaker (or config file)
self.sweep_config = dict()
sweep_config = self._wl._sweep_config or dict()
self.config = dict()
self.init_artifact_config: Dict[str, Any] = dict()
for config_data in (
sagemaker_config,
self._wl._config,
init_config,
):
if not config_data:
continue
# split out artifacts, since when inserted into
# config they will trigger use_artifact
# but the run is not yet upserted
self._split_artifacts_from_config(config_data, self.config)
if sweep_config:
self._split_artifacts_from_config(sweep_config, self.sweep_config)
monitor_gym = kwargs.pop("monitor_gym", None)
if monitor_gym and len(wandb.patched["gym"]) == 0:
wandb.gym.monitor()
if wandb.patched["tensorboard"]:
with telemetry.context(obj=self._init_telemetry_obj) as tel:
tel.feature.tensorboard_patch = True
tensorboard = kwargs.pop("tensorboard", None)
sync_tensorboard = kwargs.pop("sync_tensorboard", None)
if tensorboard or sync_tensorboard and len(wandb.patched["tensorboard"]) == 0:
wandb.tensorboard.patch()
with telemetry.context(obj=self._init_telemetry_obj) as tel:
tel.feature.tensorboard_sync = True
magic = kwargs.get("magic")
if magic not in (None, False):
magic_install(kwargs)
# handle login related parameters as these are applied to global state
init_settings = {
key: kwargs[key]
for key in ["anonymous", "force", "mode", "resume"]
if kwargs.get(key) is not None
}
if init_settings:
settings.update(init_settings, source=Source.INIT)
if not settings._offline and not settings._noop:
wandb_login._login(
anonymous=kwargs.pop("anonymous", None),
force=kwargs.pop("force", None),
_disable_warning=True,
_silent=settings.quiet or settings.silent,
_entity=kwargs.get("entity") or settings.entity,
)
# apply updated global state after login was handled
settings._apply_settings(wandb.setup().settings)
# get status of code saving before applying user settings
save_code_pre_user_settings = settings.save_code
settings._apply_init(kwargs)
if not settings._offline and not settings._noop:
user_settings = self._wl._load_user_settings()
settings._apply_user(user_settings)
# ensure that user settings don't set saving to true
# if user explicitly set these to false in UI
if save_code_pre_user_settings is False:
settings.update({"save_code": False}, source=Source.INIT)
# TODO(jhr): should this be moved? probably.
settings._set_run_start_time(source=Source.INIT)
if not settings._noop:
self._log_setup(settings)
if settings._jupyter:
self._jupyter_setup(settings)
launch_config = _handle_launch_config(settings)
if launch_config:
self._split_artifacts_from_config(launch_config, self.launch_config)
self.settings = settings
# self.settings.freeze() | python | wandb/sdk/wandb_init.py | 127 | 327 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,043 | teardown | def teardown(self) -> None:
# TODO: currently this is only called on failed wandb.init attempts
# normally this happens on the run object
assert logger
logger.info("tearing down wandb.init")
for hook in self._teardown_hooks:
hook.call() | python | wandb/sdk/wandb_init.py | 329 | 335 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,044 | _split_artifacts_from_config | def _split_artifacts_from_config(
self, config_source: dict, config_target: dict
) -> None:
for k, v in config_source.items():
if _is_artifact_representation(v):
self.init_artifact_config[k] = v
else:
config_target.setdefault(k, v) | python | wandb/sdk/wandb_init.py | 337 | 344 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,045 | _enable_logging | def _enable_logging(self, log_fname: str, run_id: Optional[str] = None) -> None:
"""Enable logging to the global debug log.
This adds a run_id to the log, in case of multiple processes on the same machine.
Currently, there is no way to disable logging after it's enabled.
"""
handler = logging.FileHandler(log_fname)
handler.setLevel(logging.INFO)
class WBFilter(logging.Filter):
def filter(self, record: logging.LogRecord) -> bool:
record.run_id = run_id
return True
if run_id:
formatter = logging.Formatter(
"%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d "
"[%(run_id)s:%(filename)s:%(funcName)s():%(lineno)s] %(message)s"
)
else:
formatter = logging.Formatter(
"%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d "
"[%(filename)s:%(funcName)s():%(lineno)s] %(message)s"
)
handler.setFormatter(formatter)
if run_id:
handler.addFilter(WBFilter())
assert logger is not None
logger.propagate = False
logger.addHandler(handler)
# TODO: make me configurable
logger.setLevel(logging.DEBUG)
self._teardown_hooks.append(
TeardownHook(
lambda: (handler.close(), logger.removeHandler(handler)), # type: ignore
TeardownStage.LATE,
)
) | python | wandb/sdk/wandb_init.py | 346 | 384 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,046 | filter | def filter(self, record: logging.LogRecord) -> bool:
record.run_id = run_id
return True | python | wandb/sdk/wandb_init.py | 356 | 358 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,047 | _safe_symlink | def _safe_symlink(
self, base: str, target: str, name: str, delete: bool = False
) -> None:
# TODO(jhr): do this with relpaths, but i cant figure it out on no sleep
if not hasattr(os, "symlink"):
return
pid = os.getpid()
tmp_name = os.path.join(base, "%s.%d" % (name, pid))
if delete:
try:
os.remove(os.path.join(base, name))
except OSError:
pass
target = os.path.relpath(target, base)
try:
os.symlink(target, tmp_name)
os.rename(tmp_name, os.path.join(base, name))
except OSError:
pass | python | wandb/sdk/wandb_init.py | 386 | 406 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,048 | _pause_backend | def _pause_backend(self) -> None:
if self.backend is None:
return None
# Attempt to save the code on every execution
if self.notebook.save_ipynb(): # type: ignore
assert self.run is not None
res = self.run.log_code(root=None)
logger.info("saved code: %s", res) # type: ignore
if self.backend.interface is not None:
logger.info("pausing backend") # type: ignore
self.backend.interface.publish_pause() | python | wandb/sdk/wandb_init.py | 408 | 419 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,049 | _resume_backend | def _resume_backend(self) -> None:
if self.backend is not None and self.backend.interface is not None:
logger.info("resuming backend") # type: ignore
self.backend.interface.publish_resume() | python | wandb/sdk/wandb_init.py | 421 | 424 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,050 | _jupyter_teardown | def _jupyter_teardown(self) -> None:
"""Teardown hooks and display saving, called with wandb.finish."""
assert self.notebook
ipython = self.notebook.shell
self.notebook.save_history()
if self.notebook.save_ipynb():
assert self.run is not None
res = self.run.log_code(root=None)
logger.info("saved code and history: %s", res) # type: ignore
logger.info("cleaning up jupyter logic") # type: ignore
# because of how we bind our methods we manually find them to unregister
for hook in ipython.events.callbacks["pre_run_cell"]:
if "_resume_backend" in hook.__name__:
ipython.events.unregister("pre_run_cell", hook)
for hook in ipython.events.callbacks["post_run_cell"]:
if "_pause_backend" in hook.__name__:
ipython.events.unregister("post_run_cell", hook)
ipython.display_pub.publish = ipython.display_pub._orig_publish
del ipython.display_pub._orig_publish | python | wandb/sdk/wandb_init.py | 426 | 444 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,051 | _jupyter_setup | def _jupyter_setup(self, settings: Settings) -> None:
"""Add hooks, and session history saving."""
self.notebook = wandb.jupyter.Notebook(settings)
ipython = self.notebook.shell
# Monkey patch ipython publish to capture displayed outputs
if not hasattr(ipython.display_pub, "_orig_publish"):
logger.info("configuring jupyter hooks %s", self) # type: ignore
ipython.display_pub._orig_publish = ipython.display_pub.publish
# Registering resume and pause hooks
ipython.events.register("pre_run_cell", self._resume_backend)
ipython.events.register("post_run_cell", self._pause_backend)
self._teardown_hooks.append(
TeardownHook(self._jupyter_teardown, TeardownStage.EARLY)
)
def publish(data, metadata=None, **kwargs) -> None: # type: ignore
ipython.display_pub._orig_publish(data, metadata=metadata, **kwargs)
assert self.notebook is not None
self.notebook.save_display(
ipython.execution_count, {"data": data, "metadata": metadata}
)
ipython.display_pub.publish = publish | python | wandb/sdk/wandb_init.py | 446 | 470 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,052 | publish | def publish(data, metadata=None, **kwargs) -> None: # type: ignore
ipython.display_pub._orig_publish(data, metadata=metadata, **kwargs)
assert self.notebook is not None
self.notebook.save_display(
ipython.execution_count, {"data": data, "metadata": metadata}
) | python | wandb/sdk/wandb_init.py | 463 | 468 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,053 | _log_setup | def _log_setup(self, settings: Settings) -> None:
"""Set up logging from settings."""
filesystem.mkdir_exists_ok(os.path.dirname(settings.log_user))
filesystem.mkdir_exists_ok(os.path.dirname(settings.log_internal))
filesystem.mkdir_exists_ok(os.path.dirname(settings.sync_file))
filesystem.mkdir_exists_ok(settings.files_dir)
filesystem.mkdir_exists_ok(settings._tmp_code_dir)
if settings.symlink:
self._safe_symlink(
os.path.dirname(settings.sync_symlink_latest),
os.path.dirname(settings.sync_file),
os.path.basename(settings.sync_symlink_latest),
delete=True,
)
self._safe_symlink(
os.path.dirname(settings.log_symlink_user),
settings.log_user,
os.path.basename(settings.log_symlink_user),
delete=True,
)
self._safe_symlink(
os.path.dirname(settings.log_symlink_internal),
settings.log_internal,
os.path.basename(settings.log_symlink_internal),
delete=True,
)
_set_logger(logging.getLogger("wandb"))
self._enable_logging(settings.log_user)
assert self._wl
assert logger
self._wl._early_logger_flush(logger)
logger.info(f"Logging user logs to {settings.log_user}")
logger.info(f"Logging internal logs to {settings.log_internal}") | python | wandb/sdk/wandb_init.py | 472 | 508 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,054 | _make_run_disabled | def _make_run_disabled(self) -> RunDisabled:
drun = RunDisabled()
drun.config = wandb.wandb_sdk.wandb_config.Config()
drun.config.update(self.sweep_config)
drun.config.update(self.config)
drun.summary = SummaryDisabled()
drun.log = lambda data, *_, **__: drun.summary.update(data)
drun.finish = lambda *_, **__: module.unset_globals()
drun.step = 0
drun.resumed = False
drun.disabled = True
drun.id = runid.generate_id()
drun.name = "dummy-" + drun.id
drun.dir = tempfile.gettempdir()
module.set_global(
run=drun,
config=drun.config,
log=drun.log,
summary=drun.summary,
save=drun.save,
use_artifact=drun.use_artifact,
log_artifact=drun.log_artifact,
define_metric=drun.define_metric,
plot_table=drun.plot_table,
alert=drun.alert,
)
return drun | python | wandb/sdk/wandb_init.py | 510 | 536 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,055 | _on_progress_init | def _on_progress_init(self, handle: MailboxProgress) -> None:
assert self.printer
line = "Waiting for wandb.init()...\r"
percent_done = handle.percent_done
self.printer.progress_update(line, percent_done=percent_done) | python | wandb/sdk/wandb_init.py | 538 | 542 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,056 | init | def init(self) -> Union[Run, RunDisabled, None]: # noqa: C901
if logger is None:
raise RuntimeError("Logger not initialized")
logger.info("calling init triggers")
trigger.call("on_init", **self.kwargs) # type: ignore
assert self.settings is not None
assert self._wl is not None
assert self._reporter is not None
logger.info(
f"wandb.init called with sweep_config: {self.sweep_config}\nconfig: {self.config}"
)
if self.settings._noop:
return self._make_run_disabled()
if self.settings.reinit or (
self.settings._jupyter and self.settings.reinit is not False
):
if len(self._wl._global_run_stack) > 0:
if len(self._wl._global_run_stack) > 1:
wandb.termwarn(
"If you want to track multiple runs concurrently in wandb, "
"you should use multi-processing not threads"
)
latest_run = self._wl._global_run_stack[-1]
logger.info(
f"re-initializing run, found existing run on stack: {latest_run._run_id}"
)
jupyter = self.settings._jupyter and ipython.in_jupyter()
if jupyter and not self.settings.silent:
ipython.display_html(
f"Finishing last run (ID:{latest_run._run_id}) before initializing another..."
)
latest_run.finish()
if jupyter and not self.settings.silent:
ipython.display_html(
f"Successfully finished last run (ID:{latest_run._run_id}). Initializing new run:<br/>"
)
elif isinstance(wandb.run, Run):
manager = self._wl._get_manager()
# We shouldn't return a stale global run if we are in a new pid
if not manager or os.getpid() == wandb.run._init_pid:
logger.info("wandb.init() called when a run is still active")
with telemetry.context() as tel:
tel.feature.init_return_run = True
return wandb.run
logger.info("starting backend")
manager = self._wl._get_manager()
if manager:
logger.info("setting up manager")
manager._inform_init(settings=self.settings, run_id=self.settings.run_id)
mailbox = Mailbox()
backend = Backend(settings=self.settings, manager=manager, mailbox=mailbox)
backend.ensure_launched()
logger.info("backend started and connected")
# Make sure we are logged in
# wandb_login._login(_backend=backend, _settings=self.settings)
# resuming needs access to the server, check server_status()?
run = Run(
config=self.config,
settings=self.settings,
sweep_config=self.sweep_config,
launch_config=self.launch_config,
)
# Populate initial telemetry
with telemetry.context(run=run, obj=self._init_telemetry_obj) as tel:
tel.cli_version = wandb.__version__
tel.python_version = platform.python_version()
hf_version = _huggingface_version()
if hf_version:
tel.huggingface_version = hf_version
if self.settings._jupyter:
tel.env.jupyter = True
if self.settings._kaggle:
tel.env.kaggle = True
if self.settings._windows:
tel.env.windows = True
if self.settings.launch:
tel.feature.launch = True
if self.settings._async_upload_concurrency_limit:
tel.feature.async_uploads = True
for module_name in telemetry.list_telemetry_imports(only_imported=True):
setattr(tel.imports_init, module_name, True)
# probe the active start method
active_start_method: Optional[str] = None
if self.settings.start_method == "thread":
active_start_method = self.settings.start_method
else:
active_start_method = getattr(
backend._multiprocessing, "get_start_method", lambda: None
)()
if active_start_method == "spawn":
tel.env.start_spawn = True
elif active_start_method == "fork":
tel.env.start_fork = True
elif active_start_method == "forkserver":
tel.env.start_forkserver = True
elif active_start_method == "thread":
tel.env.start_thread = True
if os.environ.get("PEX"):
tel.env.pex = True
if os.environ.get(wandb.env._DISABLE_SERVICE):
tel.feature.service_disabled = True
if manager:
tel.feature.service = True
if self.settings._flow_control_disabled:
tel.feature.flow_control_disabled = True
if self.settings._flow_control_custom:
tel.feature.flow_control_custom = True
tel.env.maybe_mp = _maybe_mp_process(backend)
# todo: detected issues with settings.
if self.settings.__dict__["_Settings__preprocessing_warnings"]:
tel.issues.settings__preprocessing_warnings = True
if self.settings.__dict__["_Settings__validation_warnings"]:
tel.issues.settings__validation_warnings = True
if self.settings.__dict__["_Settings__unexpected_args"]:
tel.issues.settings__unexpected_args = True
if not self.settings.label_disable:
if self.notebook:
run._label_probe_notebook(self.notebook)
else:
run._label_probe_main()
for deprecated_feature, msg in self.deprecated_features_used.items():
warning_message = f"`{deprecated_feature}` is deprecated. {msg}"
deprecate(
field_name=getattr(Deprecated, "init__" + deprecated_feature),
warning_message=warning_message,
run=run,
)
logger.info("updated telemetry")
run._set_library(self._wl)
run._set_backend(backend)
run._set_reporter(self._reporter)
run._set_teardown_hooks(self._teardown_hooks)
backend._hack_set_run(run)
assert backend.interface
mailbox.enable_keepalive()
backend.interface.publish_header()
# Using GitRepo() blocks & can be slow, depending on user's current git setup.
# We don't want to block run initialization/start request, so populate run's git
# info beforehand.
if not self.settings.disable_git:
run._populate_git_info()
run_proto = backend.interface._make_run(run)
run_result: Optional["pb.RunUpdateResult"] = None
if self.settings._offline:
with telemetry.context(run=run) as tel:
tel.feature.offline = True
backend.interface.publish_run(run_proto)
run._set_run_obj_offline(run_proto)
if self.settings.resume:
wandb.termwarn(
"`resume` will be ignored since W&B syncing is set to `offline`. "
f"Starting a new run with run id {run.id}."
)
else:
error: Optional["wandb.errors.Error"] = None
timeout = self.settings.init_timeout
logger.info(f"communicating run to backend with {timeout} second timeout")
run_init_handle = backend.interface.deliver_run(run_proto)
result = run_init_handle.wait(
timeout=timeout,
on_progress=self._on_progress_init,
cancel=True,
)
if result:
run_result = result.run_result
if run_result is None:
error_message = (
f"Run initialization has timed out after {timeout} sec. "
f"\nPlease refer to the documentation for additional information: {wburls.get('doc_start_err')}"
)
# We're not certain whether the error we encountered is due to an issue
# with the server (a "CommError") or if it's a problem within the SDK (an "Error").
# This means that the error could be a result of the server being unresponsive,
# or it could be because we were unable to communicate with the wandb service.
error = CommError(error_message)
run_init_handle._cancel()
elif run_result.HasField("error"):
error = ProtobufErrorHandler.to_exception(run_result.error)
if error is not None:
logger.error(f"encountered error: {error}")
if not manager:
# Shutdown the backend and get rid of the logger
# we don't need to do console cleanup at this point
backend.cleanup()
self.teardown()
raise error
assert run_result is not None # for mypy
if not run_result.HasField("run"):
raise Error(
"It appears that something have gone wrong during the program execution as an unexpected missing field was encountered. "
"(run_result is missing the 'run' field)"
)
if run_result.run.resumed:
logger.info("run resumed")
with telemetry.context(run=run) as tel:
tel.feature.resumed = run_result.run.resumed
run._set_run_obj(run_result.run)
run._on_init()
logger.info("starting run threads in backend")
# initiate run (stats and metadata probing)
run_obj = run._run_obj or run._run_obj_offline
if manager:
manager._inform_start(settings=self.settings, run_id=self.settings.run_id)
assert backend.interface
assert run_obj
run_start_handle = backend.interface.deliver_run_start(run_obj)
# TODO: add progress to let user know we are doing something
run_start_result = run_start_handle.wait(timeout=30)
if run_start_result is None:
run_start_handle.abandon()
assert self._wl is not None
self._wl._global_run_stack.append(run)
self.run = run
run._handle_launch_artifact_overrides()
if (
self.settings.launch
and self.settings.launch_config_path
and os.path.exists(self.settings.launch_config_path)
):
run._save(self.settings.launch_config_path)
# put artifacts in run config here
# since doing so earlier will cause an error
# as the run is not upserted
for k, v in self.init_artifact_config.items():
run.config.update({k: v}, allow_val_change=True)
job_artifact = run._launch_artifact_mapping.get(
wandb.util.LAUNCH_JOB_ARTIFACT_SLOT_NAME
)
if job_artifact:
run.use_artifact(job_artifact)
self.backend = backend
assert self._reporter
self._reporter.set_context(run=run)
run._on_start()
logger.info("run started, returning control to user process")
return run | python | wandb/sdk/wandb_init.py | 544 | 825 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,057 | getcaller | def getcaller() -> None:
if not logger:
return None
src, line, func, stack = logger.findCaller(stack_info=True)
print("Problem at:", src, line, func) | python | wandb/sdk/wandb_init.py | 828 | 832 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,058 | _attach | def _attach(
attach_id: Optional[str] = None,
run_id: Optional[str] = None,
*,
run: Optional["Run"] = None,
) -> Union[Run, RunDisabled, None]:
"""Attach to a run currently executing in another process/thread.
Arguments:
attach_id: (str, optional) The id of the run or an attach identifier
that maps to a run.
run_id: (str, optional) The id of the run to attach to.
run: (Run, optional) The run instance to attach
"""
attach_id = attach_id or run_id
if not ((attach_id is None) ^ (run is None)):
raise UsageError("Either (`attach_id` or `run_id`) or `run` must be specified")
attach_id = attach_id or (run._attach_id if run else None)
if attach_id is None:
raise UsageError(
"Either `attach_id` or `run_id` must be specified or `run` must have `_attach_id`"
)
wandb._assert_is_user_process()
_wl = wandb_setup._setup()
assert _wl
_set_logger(_wl._get_logger())
if logger is None:
raise UsageError("logger is not initialized")
manager = _wl._get_manager()
response = manager._inform_attach(attach_id=attach_id) if manager else None
if response is None:
raise UsageError(f"Unable to attach to run {attach_id}")
settings: Settings = copy.copy(_wl._settings)
settings.update(
{
"run_id": attach_id,
"_start_time": response["_start_time"],
"_start_datetime": response["_start_datetime"],
},
source=Source.INIT,
)
# TODO: consolidate this codepath with wandb.init()
mailbox = Mailbox()
backend = Backend(settings=settings, manager=manager, mailbox=mailbox)
backend.ensure_launched()
logger.info("attach backend started and connected")
if run is None:
run = Run(settings=settings)
else:
run._init(settings=settings)
run._set_library(_wl)
run._set_backend(backend)
backend._hack_set_run(run)
assert backend.interface
mailbox.enable_keepalive()
attach_handle = backend.interface.deliver_attach(attach_id)
# TODO: add progress to let user know we are doing something
attach_result = attach_handle.wait(timeout=30)
if not attach_result:
attach_handle.abandon()
raise UsageError("Timeout attaching to run")
attach_response = attach_result.response.attach_response
if attach_response.error and attach_response.error.message:
raise UsageError(f"Failed to attach to run: {attach_response.error.message}")
run._set_run_obj(attach_response.run)
run._on_attach()
return run | python | wandb/sdk/wandb_init.py | 835 | 910 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,059 | init | def init(
job_type: Optional[str] = None,
dir: Union[str, pathlib.Path, None] = None,
config: Union[Dict, str, None] = None,
project: Optional[str] = None,
entity: Optional[str] = None,
reinit: Optional[bool] = None,
tags: Optional[Sequence] = None,
group: Optional[str] = None,
name: Optional[str] = None,
notes: Optional[str] = None,
magic: Optional[Union[dict, str, bool]] = None,
config_exclude_keys: Optional[List[str]] = None,
config_include_keys: Optional[List[str]] = None,
anonymous: Optional[str] = None,
mode: Optional[str] = None,
allow_val_change: Optional[bool] = None,
resume: Optional[Union[bool, str]] = None,
force: Optional[bool] = None,
tensorboard: Optional[bool] = None, # alias for sync_tensorboard
sync_tensorboard: Optional[bool] = None,
monitor_gym: Optional[bool] = None,
save_code: Optional[bool] = None,
id: Optional[str] = None,
settings: Union[Settings, Dict[str, Any], None] = None,
) -> Union[Run, RunDisabled, None]:
r"""Start a new run to track and log to W&B.
In an ML training pipeline, you could add `wandb.init()`
to the beginning of your training script as well as your evaluation
script, and each piece would be tracked as a run in W&B.
`wandb.init()` spawns a new background process to log data to a run, and it
also syncs data to wandb.ai by default, so you can see live visualizations.
Call `wandb.init()` to start a run before logging data with `wandb.log()`:
<!--yeadoc-test:init-method-log-->
```python
import wandb
wandb.init()
# ... calculate metrics, generate media
wandb.log({"accuracy": 0.9})
```
`wandb.init()` returns a run object, and you can also access the run object
via `wandb.run`:
<!--yeadoc-test:init-and-assert-global-->
```python
import wandb
run = wandb.init()
assert run is wandb.run
```
At the end of your script, we will automatically call `wandb.finish` to
finalize and cleanup the run. However, if you call `wandb.init` from a
child process, you must explicitly call `wandb.finish` at the end of the
child process.
For more on using `wandb.init()`, including detailed examples, check out our
[guide and FAQs](https://docs.wandb.ai/guides/track/launch).
Arguments:
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.
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 [your settings](https://wandb.ai/settings) under "default location
to create new projects".
config: (dict, argparse, absl.flags, str, optional)
This sets `wandb.config`, a dictionary-like object for saving inputs
to your job, like hyperparameters for a model or settings for a data
preprocessing job. The config will show up in a table in the UI that
you can use to group, filter, and sort runs. Keys should not contain
`.` in their names, and values should be under 10 MB.
If dict, argparse or absl.flags: will load the key value pairs into
the `wandb.config` object.
If str: will look for a yaml file by that name, and load config from
that file into the `wandb.config` object.
save_code: (bool, optional) Turn this on to save the main script or
notebook to W&B. This is valuable for improving experiment
reproducibility and to diff code across experiments in the UI. By
default this is off, but you can flip the default behavior to on
in [your settings page](https://wandb.ai/settings).
group: (str, optional) Specify a group to organize individual runs into
a larger experiment. For example, you might be doing cross
validation, or you might have multiple jobs that train and evaluate
a model against different test sets. Group gives you a way to
organize runs together into a larger whole, and you can toggle this
on and off in the UI. For more details, see our
[guide to grouping runs](https://docs.wandb.com/guides/runs/grouping).
job_type: (str, optional) Specify the type of run, which is useful when
you're grouping runs together into larger experiments using group.
For example, you might have multiple jobs in a group, with job types
like train and eval. Setting this makes it easy to filter and group
similar runs together in the UI so you can compare apples to apples.
tags: (list, optional) A list of strings, which will populate the list
of tags on this run in the UI. Tags are useful for organizing runs
together, or applying temporary labels like "baseline" or
"production". It's easy to add and remove tags in the UI, or filter
down to just runs with a specific tag.
name: (str, optional) A short display name for this run, which is how
you'll identify this run in the UI. By default, we generate a random
two-word name that lets you easily cross-reference runs from the
table to charts. Keeping these run names short makes the chart
legends and tables easier to read. If you're looking for a place to
save your hyperparameters, we recommend saving those in config.
notes: (str, optional) A longer description of the run, like a `-m` commit
message in git. This helps you remember what you were doing when you
ran this run.
dir: (str or pathlib.Path, optional) An absolute path to a directory where
metadata will be stored. When you call `download()` on an artifact,
this is the directory where downloaded files will be saved. By default,
this is the `./wandb` directory.
resume: (bool, str, optional) Sets the resuming behavior. Options:
`"allow"`, `"must"`, `"never"`, `"auto"` or `None`. Defaults to `None`.
Cases:
- `None` (default): If the new run has the same ID as a previous run,
this run overwrites that data.
- `"auto"` (or `True`): if the previous run on this machine crashed,
automatically resume it. Otherwise, start a new run.
- `"allow"`: if id is set with `init(id="UNIQUE_ID")` or
`WANDB_RUN_ID="UNIQUE_ID"` and it is identical to a previous run,
wandb will automatically resume the run with that id. Otherwise,
wandb will start a new run.
- `"never"`: if id is set with `init(id="UNIQUE_ID")` or
`WANDB_RUN_ID="UNIQUE_ID"` and it is identical to a previous run,
wandb will crash.
- `"must"`: if id is set with `init(id="UNIQUE_ID")` or
`WANDB_RUN_ID="UNIQUE_ID"` and it is identical to a previous run,
wandb will automatically resume the run with the id. Otherwise,
wandb will crash.
See [our guide to resuming runs](https://docs.wandb.com/guides/runs/resuming)
for more.
reinit: (bool, optional) Allow multiple `wandb.init()` calls in the same
process. (default: `False`)
magic: (bool, dict, or str, optional) The bool controls whether we try to
auto-instrument your script, capturing basic details of your run
without you having to add more wandb code. (default: `False`)
You can also pass a dict, json string, or yaml filename.
config_exclude_keys: (list, optional) string keys to exclude from
`wandb.config`.
config_include_keys: (list, optional) string keys to include in
`wandb.config`.
anonymous: (str, optional) Controls anonymous data logging. Options:
- `"never"` (default): requires you to link your W&B account before
tracking the run, so you don't accidentally create an anonymous
run.
- `"allow"`: lets a logged-in user track runs with their account, but
lets someone who is running the script without a W&B account see
the charts in the UI.
- `"must"`: sends the run to an anonymous account instead of to a
signed-up user account.
mode: (str, optional) Can be `"online"`, `"offline"` or `"disabled"`. Defaults to
online.
allow_val_change: (bool, optional) Whether to allow config values to
change after setting the keys once. By default, we throw an exception
if a config value is overwritten. If you want to track something
like a varying learning rate at multiple times during training, use
`wandb.log()` instead. (default: `False` in scripts, `True` in Jupyter)
force: (bool, optional) If `True`, this crashes the script if a user isn't
logged in to W&B. If `False`, this will let the script run in offline
mode if a user isn't logged in to W&B. (default: `False`)
sync_tensorboard: (bool, optional) Synchronize wandb logs from tensorboard or
tensorboardX and save the relevant events file. (default: `False`)
monitor_gym: (bool, optional) Automatically log videos of environment when
using OpenAI Gym. (default: `False`)
See [our guide to this integration](https://docs.wandb.com/guides/integrations/openai-gym).
id: (str, optional) A unique ID for this run, used for resuming. It must
be unique in the project, and if you delete a run you can't reuse
the ID. Use the `name` field for a short descriptive name, or `config`
for saving hyperparameters to compare across runs. The ID cannot
contain the following special characters: `/\#?%:`.
See [our guide to resuming runs](https://docs.wandb.com/guides/runs/resuming).
Examples:
### Set where the run is logged
You can change where the run is logged, just like changing
the organization, repository, and branch in git:
```python
import wandb
user = "geoff"
project = "capsules"
display_name = "experiment-2021-10-31"
wandb.init(entity=user, project=project, name=display_name)
```
### Add metadata about the run to the config
Pass a dictionary-style object as the `config` keyword argument to add
metadata, like hyperparameters, to your run.
<!--yeadoc-test:init-set-config-->
```python
import wandb
config = {"lr": 3e-4, "batch_size": 32}
config.update({"architecture": "resnet", "depth": 34})
wandb.init(config=config)
```
Raises:
Error: if some unknown or internal error happened during the run initialization.
AuthenticationError: if the user failed to provide valid credentials.
CommError: if there was a problem communicating with the WandB server.
UsageError: if the user provided invalid arguments.
KeyboardInterrupt: if user interrupts the run.
Returns:
A `Run` object.
"""
wandb._assert_is_user_process()
kwargs = dict(locals())
error_seen = None
except_exit = None
run: Optional[Union[Run, RunDisabled]] = None
try:
wi = _WandbInit()
wi.setup(kwargs)
assert wi.settings
except_exit = wi.settings._except_exit
try:
run = wi.init()
except_exit = wi.settings._except_exit
except (KeyboardInterrupt, Exception) as e:
if not isinstance(e, KeyboardInterrupt):
wandb._sentry.exception(e)
if not (
wandb.wandb_agent._is_running() and isinstance(e, KeyboardInterrupt)
):
getcaller()
assert logger
if wi.settings.problem == "fatal":
raise
if wi.settings.problem == "warn":
pass
# TODO(jhr): figure out how to make this RunDummy
run = None
except Error as e:
if logger is not None:
logger.exception(str(e))
raise e
except KeyboardInterrupt as e:
assert logger
logger.warning("interrupted", exc_info=e)
raise e
except Exception as e:
error_seen = e
traceback.print_exc()
assert logger
logger.error("error", exc_info=e)
# Need to build delay into this sentry capture because our exit hooks
# mess with sentry's ability to send out errors before the program ends.
wandb._sentry.exception(e)
# reraise(*sys.exc_info())
finally:
if error_seen:
if except_exit:
wandb.termerror("Abnormal program exit")
os._exit(1)
raise Error("An unexpected error occurred") from error_seen
return run | python | wandb/sdk/wandb_init.py | 913 | 1,184 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,060 | parse_config | def parse_config(params, exclude=None, include=None):
if exclude and include:
raise UsageError("Expected at most only one of exclude or include")
if isinstance(params, str):
params = config_util.dict_from_config_file(params, must_exist=True)
params = _to_dict(params)
if include:
params = {key: value for key, value in params.items() if key in include}
if exclude:
params = {key: value for key, value in params.items() if key not in exclude}
return params | python | wandb/sdk/wandb_helper.py | 9 | 19 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,061 | _to_dict | def _to_dict(params):
if isinstance(params, dict):
return params
# Handle some cases where params is not a dictionary
# by trying to convert it into a dictionary
meta = inspect.getmodule(params)
if meta:
is_tf_flags_module = (
isinstance(params, types.ModuleType)
and meta.__name__ == "tensorflow.python.platform.flags"
)
if is_tf_flags_module or meta.__name__ == "absl.flags":
params = params.FLAGS
meta = inspect.getmodule(params)
# newer tensorflow flags (post 1.4) uses absl.flags
if meta and meta.__name__ == "absl.flags._flagvalues":
params = {name: params[name].value for name in dir(params)}
elif not hasattr(params, "__dict__"):
raise TypeError("config must be a dict or have a __dict__ attribute.")
elif "__flags" in vars(params):
# for older tensorflow flags (pre 1.4)
if not "__parsed" not in vars(params):
params._parse_flags()
params = vars(params)["__flags"]
else:
# params is a Namespace object (argparse)
# or something else
params = vars(params)
# assume argparse Namespace
return params | python | wandb/sdk/wandb_helper.py | 22 | 54 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,062 | get_args | def get_args(obj: Any) -> Optional[Any]:
return obj.__args__ if hasattr(obj, "__args__") else None | python | wandb/sdk/wandb_settings.py | 55 | 56 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,063 | get_origin | def get_origin(obj: Any) -> Optional[Any]:
return obj.__origin__ if hasattr(obj, "__origin__") else None | python | wandb/sdk/wandb_settings.py | 58 | 59 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,064 | get_type_hints | def get_type_hints(obj: Any) -> Dict[str, Any]:
return dict(obj.__annotations__) if hasattr(obj, "__annotations__") else dict() | python | wandb/sdk/wandb_settings.py | 61 | 62 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,065 | _get_wandb_dir | def _get_wandb_dir(root_dir: str) -> str:
"""Get the full path to the wandb directory.
The setting exposed to users as `dir=` or `WANDB_DIR` is the `root_dir`.
We add the `__stage_dir__` to it to get the full `wandb_dir`
"""
# We use the hidden version if it already exists, otherwise non-hidden.
if os.path.exists(os.path.join(root_dir, ".wandb")):
__stage_dir__ = ".wandb" + os.sep
else:
__stage_dir__ = "wandb" + os.sep
path = os.path.join(root_dir, __stage_dir__)
if not os.access(root_dir or ".", os.W_OK):
wandb.termwarn(
f"Path {path} wasn't writable, using system temp directory.",
repeat=False,
)
path = os.path.join(tempfile.gettempdir(), __stage_dir__ or ("wandb" + os.sep))
return os.path.expanduser(path) | python | wandb/sdk/wandb_settings.py | 65 | 85 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,066 | _str_as_bool | def _str_as_bool(val: Union[str, bool]) -> bool:
"""Parse a string as a bool."""
if isinstance(val, bool):
return val
try:
ret_val = bool(strtobool(str(val)))
return ret_val
except (AttributeError, ValueError):
pass
# todo: remove this and only raise error once we are confident.
wandb.termwarn(
f"Could not parse value {val} as a bool. ",
repeat=False,
)
raise UsageError(f"Could not parse value {val} as a bool.") | python | wandb/sdk/wandb_settings.py | 89 | 104 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,067 | _str_as_dict | def _str_as_dict(val: Union[str, Dict[str, Any]]) -> Dict[str, Any]:
"""Parse a string as a dict."""
if isinstance(val, dict):
return val
try:
return dict(json.loads(val))
except (AttributeError, ValueError):
pass
# todo: remove this and only raise error once we are confident.
wandb.termwarn(
f"Could not parse value {val} as a dict. ",
repeat=False,
)
raise UsageError(f"Could not parse value {val} as a dict.") | python | wandb/sdk/wandb_settings.py | 107 | 121 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,068 | _str_as_tuple | def _str_as_tuple(val: Union[str, Sequence[str]]) -> Tuple[str, ...]:
"""Parse a (potentially comma-separated) string as a tuple."""
if isinstance(val, str):
return tuple(val.split(","))
return tuple(val) | python | wandb/sdk/wandb_settings.py | 124 | 128 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,069 | _redact_dict | def _redact_dict(
d: Dict[str, Any],
unsafe_keys: Union[Set[str], FrozenSet[str]] = frozenset({"api_key"}),
redact_str: str = "***REDACTED***",
) -> Dict[str, Any]:
"""Redact a dict of unsafe values specified by their key."""
if not d or unsafe_keys.isdisjoint(d):
return d
safe_dict = d.copy()
safe_dict.update({k: redact_str for k in unsafe_keys.intersection(d)})
return safe_dict | python | wandb/sdk/wandb_settings.py | 131 | 141 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,070 | _get_program | def _get_program() -> Optional[str]:
program = os.getenv(wandb.env.PROGRAM)
if program is not None:
return program
try:
import __main__
if __main__.__spec__ is None:
return __main__.__file__
# likely run as `python -m ...`
return f"-m {__main__.__spec__.name}"
except (ImportError, AttributeError):
return None | python | wandb/sdk/wandb_settings.py | 144 | 156 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,071 | _get_program_relpath_from_gitrepo | def _get_program_relpath_from_gitrepo(
program: str, _logger: Optional[_EarlyLogger] = None
) -> Optional[str]:
repo = GitRepo()
root = repo.root
if not root:
root = os.getcwd()
full_path_to_program = os.path.join(
root, os.path.relpath(os.getcwd(), root), program
)
if os.path.exists(full_path_to_program):
relative_path = os.path.relpath(full_path_to_program, start=root)
if "../" in relative_path:
if _logger is not None:
_logger.warning(f"Could not save program above cwd: {program}")
return None
return relative_path
if _logger is not None:
_logger.warning(f"Could not find program at {program}")
return None | python | wandb/sdk/wandb_settings.py | 159 | 179 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,072 | __init__ | def __init__( # pylint: disable=unused-argument
self,
name: str,
value: Optional[Any] = None,
preprocessor: Union[Callable, Sequence[Callable], None] = None,
# validators allow programming by contract
validator: Union[Callable, Sequence[Callable], None] = None,
# runtime converter (hook): properties can be e.g. tied to other properties
hook: Union[Callable, Sequence[Callable], None] = None,
# always apply hook even if value is None. can be used to replace @property's
auto_hook: bool = False,
is_policy: bool = False,
frozen: bool = False,
source: int = Source.BASE,
**kwargs: Any,
):
self.name = name
self._preprocessor = preprocessor
self._validator = validator
self._hook = hook
self._auto_hook = auto_hook
self._is_policy = is_policy
self._source = source
# todo: this is a temporary measure to collect stats on failed preprocessing and validation
self.__failed_preprocessing: bool = False
self.__failed_validation: bool = False
# preprocess and validate value
self._value = self._validate(self._preprocess(value))
self.__frozen = frozen | python | wandb/sdk/wandb_settings.py | 241 | 272 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,073 | value | def value(self) -> Any:
"""Apply the runtime modifier(s) (if any) and return the value."""
_value = self._value
if (_value is not None or self._auto_hook) and self._hook is not None:
_hook = [self._hook] if callable(self._hook) else self._hook
for h in _hook:
_value = h(_value)
return _value | python | wandb/sdk/wandb_settings.py | 275 | 282 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,074 | is_policy | def is_policy(self) -> bool:
return self._is_policy | python | wandb/sdk/wandb_settings.py | 285 | 286 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,075 | source | def source(self) -> int:
return self._source | python | wandb/sdk/wandb_settings.py | 289 | 290 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,076 | _preprocess | def _preprocess(self, value: Any) -> Any:
if value is not None and self._preprocessor is not None:
_preprocessor = (
[self._preprocessor]
if callable(self._preprocessor)
else self._preprocessor
)
for p in _preprocessor:
try:
value = p(value)
except (UsageError, ValueError):
wandb.termwarn(
f"Unable to preprocess value for property {self.name}: {value}. "
"This will raise an error in the future.",
repeat=False,
)
self.__failed_preprocessing = True
break
return value | python | wandb/sdk/wandb_settings.py | 292 | 310 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,077 | _validate | def _validate(self, value: Any) -> Any:
self.__failed_validation = False # todo: this is a temporary measure
if value is not None and self._validator is not None:
_validator = (
[self._validator] if callable(self._validator) else self._validator
)
for v in _validator:
if not v(value):
# todo: this is a temporary measure to bypass validation of certain settings.
# remove this once we are confident
if self.name in self.__strict_validate_settings:
raise ValueError(
f"Invalid value for property {self.name}: {value}"
)
else:
wandb.termwarn(
f"Invalid value for property {self.name}: {value}. "
"This will raise an error in the future.",
repeat=False,
)
self.__failed_validation = True
break
return value | python | wandb/sdk/wandb_settings.py | 312 | 334 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,078 | update | def update(self, value: Any, source: int = Source.OVERRIDE) -> None:
"""Update the value of the property."""
if self.__frozen:
raise TypeError("Property object is frozen")
# - always update value if source == Source.OVERRIDE
# - if not previously overridden:
# - update value if source is lower than or equal to current source and property is policy
# - update value if source is higher than or equal to current source and property is not policy
if (
(source == Source.OVERRIDE)
or (
self._is_policy
and self._source != Source.OVERRIDE
and source <= self._source
)
or (
not self._is_policy
and self._source != Source.OVERRIDE
and source >= self._source
)
):
# self.__dict__["_value"] = self._validate(self._preprocess(value))
self._value = self._validate(self._preprocess(value))
self._source = source | python | wandb/sdk/wandb_settings.py | 336 | 359 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,079 | __setattr__ | def __setattr__(self, key: str, value: Any) -> None:
if "_Property__frozen" in self.__dict__ and self.__frozen:
raise TypeError(f"Property object {self.name} is frozen")
if key == "value":
raise AttributeError("Use update() to update property value")
self.__dict__[key] = value | python | wandb/sdk/wandb_settings.py | 361 | 366 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,080 | __str__ | def __str__(self) -> str:
return f"{self.value!r}" if isinstance(self.value, str) else f"{self.value}" | python | wandb/sdk/wandb_settings.py | 368 | 369 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,081 | __repr__ | def __repr__(self) -> str:
return (
f"<Property {self.name}: value={self.value} "
f"_value={self._value} source={self._source} is_policy={self._is_policy}>"
)
# return f"<Property {self.name}: value={self.value}>"
# return self.__dict__.__repr__() | python | wandb/sdk/wandb_settings.py | 371 | 377 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,082 | _default_props | def _default_props(self) -> Dict[str, Dict[str, Any]]:
"""Initialize instance attributes (individual settings) as Property objects.
Helper method that is used in `__init__` together with the class attributes.
Note that key names must be the same as the class attribute names.
"""
props: Dict[str, Dict[str, Any]] = dict(
_async_upload_concurrency_limit={
"preprocessor": int,
"validator": self._validate__async_upload_concurrency_limit,
},
_disable_meta={"preprocessor": _str_as_bool},
_disable_service={
"value": False,
"preprocessor": _str_as_bool,
"is_policy": True,
},
_disable_stats={"preprocessor": _str_as_bool},
_disable_viewer={"preprocessor": _str_as_bool},
_extra_http_headers={"preprocessor": _str_as_dict},
_network_buffer={"preprocessor": int},
_colab={
"hook": lambda _: "google.colab" in sys.modules,
"auto_hook": True,
},
_console={"hook": lambda _: self._convert_console(), "auto_hook": True},
_internal_check_process={"value": 8},
_internal_queue_timeout={"value": 2},
_jupyter={
"hook": lambda _: str(_get_python_type()) != "python",
"auto_hook": True,
},
_kaggle={"hook": lambda _: util._is_likely_kaggle(), "auto_hook": True},
_noop={"hook": lambda _: self.mode == "disabled", "auto_hook": True},
_offline={
"hook": (
lambda _: True
if self.disabled or (self.mode in ("dryrun", "offline"))
else False
),
"auto_hook": True,
},
_flow_control_disabled={
"hook": lambda _: self._network_buffer == 0,
"auto_hook": True,
},
_flow_control_custom={
"hook": lambda _: bool(self._network_buffer),
"auto_hook": True,
},
_sync={"value": False},
_platform={"value": util.get_platform_name()},
_save_requirements={"value": True, "preprocessor": _str_as_bool},
_service_wait={
"value": 30,
"preprocessor": float,
"validator": self._validate__service_wait,
},
_stats_sample_rate_seconds={
"value": 2.0,
"preprocessor": float,
"validator": self._validate__stats_sample_rate_seconds,
},
_stats_samples_to_average={
"value": 15,
"preprocessor": int,
"validator": self._validate__stats_samples_to_average,
},
_stats_join_assets={"value": True, "preprocessor": _str_as_bool},
_stats_neuron_monitor_config_path={
"hook": lambda x: self._path_convert(x),
},
_stats_open_metrics_endpoints={
"preprocessor": _str_as_dict,
},
_stats_open_metrics_filters={
# capture all metrics on all endpoints by default
"value": {
".*": {},
},
"preprocessor": _str_as_dict,
},
_tmp_code_dir={
"value": "code",
"hook": lambda x: self._path_convert(self.tmp_dir, x),
},
_windows={
"hook": lambda _: platform.system() == "Windows",
"auto_hook": True,
},
anonymous={"validator": self._validate_anonymous},
api_key={"validator": self._validate_api_key},
base_url={
"value": "https://api.wandb.ai",
"preprocessor": lambda x: str(x).strip().rstrip("/"),
"validator": self._validate_base_url,
},
config_paths={"prepocessor": _str_as_tuple},
console={"value": "auto", "validator": self._validate_console},
deployment={
"hook": lambda _: "local" if self.is_local else "cloud",
"auto_hook": True,
},
disable_code={"preprocessor": _str_as_bool},
disable_hints={"preprocessor": _str_as_bool},
disable_git={"preprocessor": _str_as_bool},
disable_job_creation={"value": False, "preprocessor": _str_as_bool},
disabled={"value": False, "preprocessor": _str_as_bool},
files_dir={
"value": "files",
"hook": lambda x: self._path_convert(
self.wandb_dir, f"{self.run_mode}-{self.timespec}-{self.run_id}", x
),
},
force={"preprocessor": _str_as_bool},
git_remote={"value": "origin"},
heartbeat_seconds={"value": 30},
ignore_globs={
"value": tuple(),
"preprocessor": lambda x: tuple(x) if not isinstance(x, tuple) else x,
},
init_timeout={"value": 60, "preprocessor": lambda x: float(x)},
is_local={
"hook": (
lambda _: self.base_url != "https://api.wandb.ai"
if self.base_url is not None
else False
),
"auto_hook": True,
},
label_disable={"preprocessor": _str_as_bool},
launch={"preprocessor": _str_as_bool},
log_dir={
"value": "logs",
"hook": lambda x: self._path_convert(
self.wandb_dir, f"{self.run_mode}-{self.timespec}-{self.run_id}", x
),
},
log_internal={
"value": "debug-internal.log",
"hook": lambda x: self._path_convert(self.log_dir, x),
},
log_symlink_internal={
"value": "debug-internal.log",
"hook": lambda x: self._path_convert(self.wandb_dir, x),
},
log_symlink_user={
"value": "debug.log",
"hook": lambda x: self._path_convert(self.wandb_dir, x),
},
log_user={
"value": "debug.log",
"hook": lambda x: self._path_convert(self.log_dir, x),
},
login_timeout={"preprocessor": lambda x: float(x)},
mode={"value": "online", "validator": self._validate_mode},
problem={"value": "fatal", "validator": self._validate_problem},
project={"validator": self._validate_project},
project_url={"hook": lambda _: self._project_url(), "auto_hook": True},
quiet={"preprocessor": _str_as_bool},
reinit={"preprocessor": _str_as_bool},
relogin={"preprocessor": _str_as_bool},
resume_fname={
"value": "wandb-resume.json",
"hook": lambda x: self._path_convert(self.wandb_dir, x),
},
resumed={"value": "False", "preprocessor": _str_as_bool},
root_dir={
"preprocessor": lambda x: str(x),
"value": os.path.abspath(os.getcwd()),
},
run_id={
"validator": self._validate_run_id,
},
run_mode={
"hook": lambda _: "offline-run" if self._offline else "run",
"auto_hook": True,
},
run_tags={
"preprocessor": lambda x: tuple(x) if not isinstance(x, tuple) else x,
},
run_url={"hook": lambda _: self._run_url(), "auto_hook": True},
sagemaker_disable={"preprocessor": _str_as_bool},
save_code={"preprocessor": _str_as_bool},
settings_system={
"value": os.path.join("~", ".config", "wandb", "settings"),
"hook": lambda x: self._path_convert(x),
},
settings_workspace={
"value": "settings",
"hook": lambda x: self._path_convert(self.wandb_dir, x),
},
show_colors={"preprocessor": _str_as_bool},
show_emoji={"preprocessor": _str_as_bool},
show_errors={"value": "True", "preprocessor": _str_as_bool},
show_info={"value": "True", "preprocessor": _str_as_bool},
show_warnings={"value": "True", "preprocessor": _str_as_bool},
silent={"value": "False", "preprocessor": _str_as_bool},
start_method={"validator": self._validate_start_method},
strict={"preprocessor": _str_as_bool},
summary_timeout={"value": 60, "preprocessor": lambda x: int(x)},
summary_warnings={
"value": 5,
"preprocessor": lambda x: int(x),
"is_policy": True,
},
sweep_url={"hook": lambda _: self._sweep_url(), "auto_hook": True},
symlink={"preprocessor": _str_as_bool},
sync_dir={
"hook": [
lambda _: self._path_convert(
self.wandb_dir, f"{self.run_mode}-{self.timespec}-{self.run_id}"
)
],
"auto_hook": True,
},
sync_file={
"hook": lambda _: self._path_convert(
self.sync_dir, f"run-{self.run_id}.wandb"
),
"auto_hook": True,
},
sync_symlink_latest={
"value": "latest-run",
"hook": lambda x: self._path_convert(self.wandb_dir, x),
},
system_sample={"value": 15},
system_sample_seconds={"value": 2},
table_raise_on_max_row_limit_exceeded={
"value": False,
"preprocessor": _str_as_bool,
},
timespec={
"hook": (
lambda _: (
datetime.strftime(self._start_datetime, "%Y%m%d_%H%M%S")
if self._start_datetime
else None
)
),
"auto_hook": True,
},
tmp_dir={
"value": "tmp",
"hook": lambda x: (
self._path_convert(
self.wandb_dir,
f"{self.run_mode}-{self.timespec}-{self.run_id}",
x,
)
or tempfile.gettempdir()
),
},
wandb_dir={
"hook": lambda _: _get_wandb_dir(self.root_dir or ""),
"auto_hook": True,
},
)
return props | python | wandb/sdk/wandb_settings.py | 526 | 784 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,083 | _validator_factory | def _validator_factory(hint: Any) -> Callable[[Any], bool]:
"""Return a factory for type validators.
Given a type hint for a setting into a function that type checks the argument.
"""
origin, args = get_origin(hint), get_args(hint)
def helper(x: Any) -> bool:
if origin is None:
return isinstance(x, hint)
elif origin is Union:
return isinstance(x, args) if args is not None else True
else:
return (
isinstance(x, origin) and all(isinstance(y, args) for y in x)
if args is not None
else isinstance(x, origin)
)
return helper | python | wandb/sdk/wandb_settings.py | 788 | 807 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,084 | helper | def helper(x: Any) -> bool:
if origin is None:
return isinstance(x, hint)
elif origin is Union:
return isinstance(x, args) if args is not None else True
else:
return (
isinstance(x, origin) and all(isinstance(y, args) for y in x)
if args is not None
else isinstance(x, origin)
) | python | wandb/sdk/wandb_settings.py | 795 | 805 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,085 | _validate_mode | def _validate_mode(value: str) -> bool:
choices: Set[str] = {"dryrun", "run", "offline", "online", "disabled"}
if value not in choices:
raise UsageError(f"Settings field `mode`: {value!r} not in {choices}")
return True | python | wandb/sdk/wandb_settings.py | 810 | 814 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,086 | _validate_project | def _validate_project(value: Optional[str]) -> bool:
invalid_chars_list = list("/\\#?%:")
if value is not None:
if len(value) > 128:
raise UsageError(
f"Invalid project name {value!r}: exceeded 128 characters"
)
invalid_chars = {char for char in invalid_chars_list if char in value}
if invalid_chars:
raise UsageError(
f"Invalid project name {value!r}: "
f"cannot contain characters {','.join(invalid_chars_list)!r}, "
f"found {','.join(invalid_chars)!r}"
)
return True | python | wandb/sdk/wandb_settings.py | 817 | 831 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,087 | _validate_start_method | def _validate_start_method(value: str) -> bool:
available_methods = ["thread"]
if hasattr(multiprocessing, "get_all_start_methods"):
available_methods += multiprocessing.get_all_start_methods()
if value not in available_methods:
raise UsageError(
f"Settings field `start_method`: {value!r} not in {available_methods}"
)
return True | python | wandb/sdk/wandb_settings.py | 834 | 842 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,088 | _validate_console | def _validate_console(value: str) -> bool:
# choices = {"auto", "redirect", "off", "file", "iowrap", "notebook"}
choices: Set[str] = {
"auto",
"redirect",
"off",
"wrap",
# internal console states
"wrap_emu",
"wrap_raw",
}
if value not in choices:
# do not advertise internal console states
choices -= {"wrap_emu", "wrap_raw"}
raise UsageError(f"Settings field `console`: {value!r} not in {choices}")
return True | python | wandb/sdk/wandb_settings.py | 845 | 860 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,089 | _validate_problem | def _validate_problem(value: str) -> bool:
choices: Set[str] = {"fatal", "warn", "silent"}
if value not in choices:
raise UsageError(f"Settings field `problem`: {value!r} not in {choices}")
return True | python | wandb/sdk/wandb_settings.py | 863 | 867 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,090 | _validate_anonymous | def _validate_anonymous(value: str) -> bool:
choices: Set[str] = {"allow", "must", "never", "false", "true"}
if value not in choices:
raise UsageError(f"Settings field `anonymous`: {value!r} not in {choices}")
return True | python | wandb/sdk/wandb_settings.py | 870 | 874 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,091 | _validate_run_id | def _validate_run_id(value: str) -> bool:
# if len(value) > len(value.strip()):
# raise UsageError("Run ID cannot start or end with whitespace")
return bool(value.strip()) | python | wandb/sdk/wandb_settings.py | 877 | 880 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,092 | _validate_api_key | def _validate_api_key(value: str) -> bool:
if len(value) > len(value.strip()):
raise UsageError("API key cannot start or end with whitespace")
# todo: move this check to the post-init validation step
# if value.startswith("local") and not self.is_local:
# raise UsageError(
# "Attempting to use a local API key to connect to https://api.wandb.ai"
# )
# todo: move here the logic from sdk/lib/apikey.py
return True | python | wandb/sdk/wandb_settings.py | 883 | 894 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,093 | _validate_base_url | def _validate_base_url(value: Optional[str]) -> bool:
"""Validate the base url of the wandb server.
param value: URL to validate
Based on the Django URLValidator, but with a few additional checks.
Copyright (c) Django Software Foundation and individual contributors.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Django nor the names of its contributors may be used
to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
if value is None:
return True
ul = "\u00a1-\uffff" # Unicode letters range (must not be a raw string).
# IP patterns
ipv4_re = (
r"(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)"
r"(?:\.(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)){3}"
)
ipv6_re = r"\[[0-9a-f:.]+\]" # (simple regex, validated later)
# Host patterns
hostname_re = (
r"[a-z" + ul + r"0-9](?:[a-z" + ul + r"0-9-]{0,61}[a-z" + ul + r"0-9])?"
)
# Max length for domain name labels is 63 characters per RFC 1034 sec. 3.1
domain_re = r"(?:\.(?!-)[a-z" + ul + r"0-9-]{1,63}(?<!-))*"
tld_re = (
r"\." # dot
r"(?!-)" # can't start with a dash
r"(?:[a-z" + ul + "-]{2,63}" # domain label
r"|xn--[a-z0-9]{1,59})" # or punycode label
r"(?<!-)" # can't end with a dash
r"\.?" # may have a trailing dot
)
# host_re = "(" + hostname_re + domain_re + tld_re + "|localhost)"
# todo?: allow hostname to be just a hostname (no tld)?
host_re = "(" + hostname_re + domain_re + f"({tld_re})?" + "|localhost)"
regex = re.compile(
r"^(?:[a-z0-9.+-]*)://" # scheme is validated separately
r"(?:[^\s:@/]+(?::[^\s:@/]*)?@)?" # user:pass authentication
r"(?:" + ipv4_re + "|" + ipv6_re + "|" + host_re + ")"
r"(?::[0-9]{1,5})?" # port
r"(?:[/?#][^\s]*)?" # resource path
r"\Z",
re.IGNORECASE,
)
schemes = {"http", "https"}
unsafe_chars = frozenset("\t\r\n")
scheme = value.split("://")[0].lower()
split_url = urlsplit(value)
parsed_url = urlparse(value)
if re.match(r".*wandb\.ai[^\.]*$", value) and "api." not in value:
# user might guess app.wandb.ai or wandb.ai is the default cloud server
raise UsageError(
f"{value} is not a valid server address, did you mean https://api.wandb.ai?"
)
elif re.match(r".*wandb\.ai[^\.]*$", value) and scheme != "https":
raise UsageError("http is not secure, please use https://api.wandb.ai")
elif parsed_url.netloc == "":
raise UsageError(f"Invalid URL: {value}")
elif unsafe_chars.intersection(value):
raise UsageError("URL cannot contain unsafe characters")
elif scheme not in schemes:
raise UsageError("URL must start with `http(s)://`")
elif not regex.search(value):
raise UsageError(f"{value} is not a valid server address")
elif split_url.hostname is None or len(split_url.hostname) > 253:
raise UsageError("hostname is invalid")
return True | python | wandb/sdk/wandb_settings.py | 897 | 996 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,094 | _validate__service_wait | def _validate__service_wait(value: float) -> bool:
if value <= 0:
raise UsageError("_service_wait must be a positive number")
return True | python | wandb/sdk/wandb_settings.py | 999 | 1,002 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,095 | _validate__stats_sample_rate_seconds | def _validate__stats_sample_rate_seconds(value: float) -> bool:
if value < 0.1:
raise UsageError("_stats_sample_rate_seconds must be >= 0.1")
return True | python | wandb/sdk/wandb_settings.py | 1,005 | 1,008 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,096 | _validate__stats_samples_to_average | def _validate__stats_samples_to_average(value: int) -> bool:
if value < 1 or value > 30:
raise UsageError("_stats_samples_to_average must be between 1 and 30")
return True | python | wandb/sdk/wandb_settings.py | 1,011 | 1,014 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,097 | _validate__async_upload_concurrency_limit | def _validate__async_upload_concurrency_limit(value: int) -> bool:
if value <= 0:
raise UsageError("_async_upload_concurrency_limit must be positive")
try:
import resource # not always available on Windows
file_limit = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
except Exception:
# Couldn't get the open-file-limit for some reason,
# probably very platform-specific. Not a problem,
# we just won't use it to cap the concurrency.
pass
else:
if value > file_limit:
wandb.termwarn(
(
"_async_upload_concurrency_limit setting of"
f" {value} exceeds this process's limit"
f" on open files ({file_limit}); may cause file-upload failures."
" Try decreasing _async_upload_concurrency_limit,"
" or increasing your file limit with `ulimit -n`."
),
repeat=False,
)
return True | python | wandb/sdk/wandb_settings.py | 1,017 | 1,043 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,098 | _path_convert | def _path_convert(*args: str) -> str:
"""Join path and apply os.path.expanduser to it."""
return os.path.expanduser(os.path.join(*args)) | python | wandb/sdk/wandb_settings.py | 1,047 | 1,049 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,099 | _convert_console | def _convert_console(self) -> SettingsConsole:
convert_dict: Dict[str, SettingsConsole] = dict(
off=SettingsConsole.OFF,
wrap=SettingsConsole.WRAP,
wrap_raw=SettingsConsole.WRAP_RAW,
wrap_emu=SettingsConsole.WRAP_EMU,
redirect=SettingsConsole.REDIRECT,
)
console: str = str(self.console)
if console == "auto":
if (
self._jupyter
or (self.start_method == "thread")
or not self._disable_service
or self._windows
):
console = "wrap"
else:
console = "redirect"
convert: SettingsConsole = convert_dict[console]
return convert | python | wandb/sdk/wandb_settings.py | 1,051 | 1,071 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,100 | _get_url_query_string | def _get_url_query_string(self) -> str:
# TODO(settings) use `wandb_setting` (if self.anonymous != "true":)
if Api().settings().get("anonymous") != "true":
return ""
api_key = apikey.api_key(settings=self)
return f"?{urlencode({'apiKey': api_key})}" | python | wandb/sdk/wandb_settings.py | 1,073 | 1,080 | {
"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.