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 |
|---|---|---|---|---|---|---|---|
4,101 | get_base_setup | def get_base_setup(
launch_project: LaunchProject, py_version: str, py_major: str
) -> str:
"""Fill in the Dockerfile templates for stage 2 of build.
CPU version is built on python, GPU version is built on nvidia:cuda.
"""
python_base_image = f"python:{py_version}-buster"
if launch_project.cuda_base_image:
_logger.info(f"Using cuda base image: {launch_project.cuda_base_image}")
# cuda image doesn't come with python tooling
if py_major == "2":
python_packages = [
f"python{py_version}",
f"libpython{py_version}",
"python-pip",
"python-setuptools",
]
else:
python_packages = [
f"python{py_version}",
f"libpython{py_version}",
"python3-pip",
"python3-setuptools",
]
base_setup = CUDA_SETUP_TEMPLATE.format(
cuda_base_image=launch_project.cuda_base_image,
python_packages=" \\\n".join(python_packages),
py_version=py_version,
)
else:
python_packages = [
"python3-dev" if py_major == "3" else "python-dev",
"gcc",
] # gcc required for python < 3.7 for some reason
base_setup = PYTHON_SETUP_TEMPLATE.format(py_base_image=python_base_image)
return base_setup | python | wandb/sdk/launch/builder/build.py | 188 | 224 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,102 | get_env_vars_dict | def get_env_vars_dict(launch_project: LaunchProject, api: Api) -> Dict[str, str]:
"""Generate environment variables for the project.
Arguments:
launch_project: LaunchProject to generate environment variables for.
Returns:
Dictionary of environment variables.
"""
env_vars = {}
env_vars["WANDB_BASE_URL"] = api.settings("base_url")
env_vars["WANDB_API_KEY"] = api.api_key
env_vars["WANDB_PROJECT"] = launch_project.target_project
env_vars["WANDB_ENTITY"] = launch_project.target_entity
env_vars["WANDB_LAUNCH"] = "True"
env_vars["WANDB_RUN_ID"] = launch_project.run_id
if launch_project.docker_image:
env_vars["WANDB_DOCKER"] = launch_project.docker_image
if launch_project.name is not None:
env_vars["WANDB_NAME"] = launch_project.name
if "author" in launch_project.launch_spec:
env_vars["WANDB_USERNAME"] = launch_project.launch_spec["author"]
# TODO: handle env vars > 32760 characters
env_vars["WANDB_CONFIG"] = json.dumps(launch_project.override_config)
artifacts = {}
# if we're spinning up a launch process from a job
# we should tell the run to use that artifact
if launch_project.job:
artifacts = {wandb.util.LAUNCH_JOB_ARTIFACT_SLOT_NAME: launch_project.job}
env_vars["WANDB_ARTIFACTS"] = json.dumps(
{**artifacts, **launch_project.override_artifacts}
)
# check if the user provided an override entrypoint, otherwise use the default
if launch_project.override_entrypoint is not None:
env_vars["WANDB_ENTRYPOINT_COMMAND"] = join(
launch_project.override_entrypoint.command
)
if launch_project.override_args:
env_vars["WANDB_ARGS"] = " ".join(
compute_command_args(launch_project.override_args)
)
return env_vars | python | wandb/sdk/launch/builder/build.py | 227 | 270 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,103 | get_requirements_section | def get_requirements_section(launch_project: LaunchProject, builder_type: str) -> str:
if builder_type == "docker":
buildx_installed = docker.is_buildx_installed()
if not buildx_installed:
wandb.termwarn(
"Docker BuildX is not installed, for faster builds upgrade docker: https://github.com/docker/buildx#installing"
)
prefix = "RUN WANDB_DISABLE_CACHE=true"
elif builder_type == "kaniko":
prefix = "RUN WANDB_DISABLE_CACHE=true"
buildx_installed = False
if launch_project.deps_type == "pip":
requirements_files = []
if launch_project.project_dir is not None and os.path.exists(
os.path.join(launch_project.project_dir, "requirements.txt")
):
requirements_files += ["src/requirements.txt"]
pip_install_line = "pip install -r requirements.txt"
if launch_project.project_dir is not None and os.path.exists(
os.path.join(launch_project.project_dir, "requirements.frozen.txt")
):
# if we have frozen requirements stored, copy those over and have them take precedence
requirements_files += ["src/requirements.frozen.txt", "_wandb_bootstrap.py"]
pip_install_line = (
_parse_existing_requirements(launch_project)
+ "python _wandb_bootstrap.py"
)
if buildx_installed:
prefix = "RUN --mount=type=cache,mode=0777,target=/root/.cache/pip"
requirements_line = PIP_TEMPLATE.format(
buildx_optional_prefix=prefix,
requirements_files=" ".join(requirements_files),
pip_install=pip_install_line,
)
elif launch_project.deps_type == "conda":
if buildx_installed:
prefix = "RUN --mount=type=cache,mode=0777,target=/opt/conda/pkgs"
requirements_line = CONDA_TEMPLATE.format(buildx_optional_prefix=prefix)
else:
# this means no deps file was found
requirements_line = "RUN mkdir -p env/" # Docker fails otherwise
wandb.termwarn("No requirements file found. No packages will be installed.")
return requirements_line | python | wandb/sdk/launch/builder/build.py | 273 | 317 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,104 | get_user_setup | def get_user_setup(username: str, userid: int, runner_type: str) -> str:
if runner_type == "sagemaker":
# sagemaker must run as root
return "USER root"
user_create = USER_CREATE_TEMPLATE.format(uid=userid, user=username)
user_create += f"\nUSER {username}"
return user_create | python | wandb/sdk/launch/builder/build.py | 320 | 326 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,105 | get_entrypoint_setup | def get_entrypoint_setup(
launch_project: LaunchProject,
entry_point: EntryPoint,
workdir: str,
) -> str:
# this check will always pass, since this is only called in the build case where
# the project_dir is set
assert launch_project.project_dir is not None
with open(os.path.join(launch_project.project_dir, DEFAULT_ENTRYPOINT), "w") as fp:
fp.write(BASH_ENTRYPOINT)
return ENTRYPOINT_TEMPLATE.format(
workdir=workdir,
entrypoint=join(entry_point.command),
default_entrypoint=DEFAULT_ENTRYPOINT,
) | python | wandb/sdk/launch/builder/build.py | 329 | 343 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,106 | generate_dockerfile | def generate_dockerfile(
launch_project: LaunchProject,
entry_point: EntryPoint,
runner_type: str,
builder_type: str,
) -> str:
# get python versions truncated to major.minor to ensure image availability
if launch_project.python_version:
spl = launch_project.python_version.split(".")[:2]
py_version, py_major = (".".join(spl), spl[0])
else:
py_version, py_major = get_current_python_version()
# ----- stage 1: build -----
if launch_project.deps_type == "pip" or launch_project.deps_type is None:
python_build_image = "python:{}".format(
py_version
) # use full python image for package installation
elif launch_project.deps_type == "conda":
# neither of these images are receiving regular updates, latest should be pretty stable
python_build_image = (
"continuumio/miniconda3:latest"
if py_major == "3"
else "continuumio/miniconda:latest"
)
requirements_section = get_requirements_section(launch_project, builder_type)
# ----- stage 2: base -----
python_base_setup = get_base_setup(launch_project, py_version, py_major)
# set up user info
username, userid = get_docker_user(launch_project, runner_type)
user_setup = get_user_setup(username, userid, runner_type)
workdir = f"/home/{username}"
entrypoint_section = get_entrypoint_setup(launch_project, entry_point, workdir)
dockerfile_contents = DOCKERFILE_TEMPLATE.format(
py_build_image=python_build_image,
requirements_section=requirements_section,
base_setup=python_base_setup,
uid=userid,
user_setup=user_setup,
workdir=workdir,
entrypoint_setup=entrypoint_section,
)
return dockerfile_contents | python | wandb/sdk/launch/builder/build.py | 346 | 391 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,107 | construct_gcp_registry_uri | def construct_gcp_registry_uri(
gcp_repo: str, gcp_project: str, gcp_registry: str
) -> str:
return "/".join([gcp_registry, gcp_project, gcp_repo]) | python | wandb/sdk/launch/builder/build.py | 394 | 397 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,108 | _parse_existing_requirements | def _parse_existing_requirements(launch_project: LaunchProject) -> str:
requirements_line = ""
assert launch_project.project_dir is not None
base_requirements = os.path.join(launch_project.project_dir, "requirements.txt")
if os.path.exists(base_requirements):
include_only = set()
with open(base_requirements) as f:
iter = pkg_resources.parse_requirements(f)
while True:
try:
pkg = next(iter)
if hasattr(pkg, "name"):
name = pkg.name.lower()
else:
name = str(pkg)
include_only.add(shlex_quote(name))
except StopIteration:
break
# Different versions of pkg_resources throw different errors
# just catch them all and ignore packages we can't parse
except Exception as e:
_logger.warn(f"Unable to parse requirements.txt: {e}")
continue
requirements_line += "WANDB_ONLY_INCLUDE={} ".format(",".join(include_only))
return requirements_line | python | wandb/sdk/launch/builder/build.py | 400 | 424 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,109 | _create_docker_build_ctx | def _create_docker_build_ctx(
launch_project: LaunchProject,
dockerfile_contents: str,
) -> str:
"""Create a build context temp dir for a Dockerfile and project code."""
directory = tempfile.mkdtemp()
dst_path = os.path.join(directory, "src")
assert launch_project.project_dir is not None
shutil.copytree(
src=launch_project.project_dir,
dst=dst_path,
symlinks=True,
ignore=shutil.ignore_patterns("fsmonitor--daemon.ipc"),
)
shutil.copy(
os.path.join(os.path.dirname(__file__), "templates", "_wandb_bootstrap.py"),
os.path.join(directory),
)
if launch_project.python_version:
runtime_path = os.path.join(dst_path, "runtime.txt")
with open(runtime_path, "w") as fp:
fp.write(f"python-{launch_project.python_version}")
# TODO: we likely don't need to pass the whole git repo into the container
# with open(os.path.join(directory, ".dockerignore"), "w") as f:
# f.write("**/.git")
with open(os.path.join(directory, _GENERATED_DOCKERFILE_NAME), "w") as handle:
handle.write(dockerfile_contents)
return directory | python | wandb/sdk/launch/builder/build.py | 427 | 454 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,110 | join | def join(split_command: List[str]) -> str:
"""Return a shell-escaped string from *split_command*.
Also remove quotes from double quoted strings. Ex:
"'local container queue'" --> "local container queue"
"""
return " ".join(shlex.quote(arg.replace("'", "")) for arg in split_command) | python | wandb/sdk/launch/builder/build.py | 457 | 463 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,111 | construct_builder_args | def construct_builder_args(
launch_config: Optional[Dict] = None,
build_config: Optional[Dict] = None,
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
registry_config = None
if launch_config is not None:
build_config = launch_config.get("builder")
registry_config = launch_config.get("registry")
default_launch_config = None
if os.path.exists(os.path.expanduser(LAUNCH_CONFIG_FILE)):
with open(os.path.expanduser(LAUNCH_CONFIG_FILE)) as f:
default_launch_config = yaml.safe_load(f)
build_config, registry_config = resolve_build_and_registry_config(
default_launch_config, build_config, registry_config
)
return build_config, registry_config | python | wandb/sdk/launch/builder/build.py | 466 | 484 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,112 | build_image_with_builder | def build_image_with_builder(
builder: AbstractBuilder,
launch_project: LaunchProject,
entry_point: EntryPoint,
) -> Optional[str]:
"""Build image with testing and logging."""
wandb.termlog(f"{LOG_PREFIX}Building docker image from uri source")
image_uri: Optional[str] = builder.build_image(
launch_project,
entry_point,
)
return image_uri | python | wandb/sdk/launch/builder/build.py | 487 | 498 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,113 | build_image_from_project | def build_image_from_project(
launch_project: LaunchProject,
api: Api,
launch_config: Dict[str, Any],
) -> str:
"""Construct a docker image from a project and returns the URI of the image.
Arguments:
launch_project: The project to build an image from.
api: The API object to use for fetching the project.
launch_config: The launch config to use for building the image.
Returns:
The URI of the built image.
"""
assert launch_project.uri, "To build an image on queue a URI must be set."
launch_config = launch_config or {}
env_config = launch_config.get("environment", {})
if not isinstance(env_config, dict):
wrong_type = type(env_config).__name__
raise LaunchError(
f"Invalid environment config: {env_config} of type {wrong_type} "
"loaded from launch config. Expected dict."
)
environment = environment_from_config(env_config)
registry_config = launch_config.get("registry", {})
if not isinstance(registry_config, dict):
wrong_type = type(registry_config).__name__
raise LaunchError(
f"Invalid registry config: {registry_config} of type {wrong_type}"
" loaded from launch config. Expected dict."
)
registry = registry_from_config(registry_config, environment)
builder_config = launch_config.get("builder", {})
if not isinstance(builder_config, dict):
wrong_type = type(builder_config).__name__
raise LaunchError(
f"Invalid builder config: {builder_config} of type {wrong_type} "
"loaded from launch config. Expected dict."
)
builder = builder_from_config(builder_config, environment, registry)
if not builder:
raise LaunchError("Unable to build image. No builder found.")
launch_project = fetch_and_validate_project(launch_project, api)
entry_point: EntryPoint = launch_project.get_single_entry_point() or EntryPoint(
name=EntrypointDefaults.PYTHON[-1],
command=EntrypointDefaults.PYTHON,
)
wandb.termlog(f"{LOG_PREFIX}Building docker image from uri source")
image_uri = builder.build_image(launch_project, entry_point)
if not image_uri:
raise LaunchError("Error building image uri")
else:
return image_uri | python | wandb/sdk/launch/builder/build.py | 501 | 559 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,114 | image_tag_from_dockerfile_and_source | def image_tag_from_dockerfile_and_source(
launch_project: LaunchProject, dockerfile_contents: str
) -> str:
"""Hashes the source and dockerfile contents into a unique tag."""
image_source_string = launch_project.get_image_source_string()
unique_id_string = image_source_string + dockerfile_contents
image_tag = hashlib.sha256(unique_id_string.encode("utf-8")).hexdigest()[:8]
return image_tag | python | wandb/sdk/launch/builder/build.py | 562 | 569 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,115 | _wait_for_completion | def _wait_for_completion(
batch_client: client.BatchV1Api, job_name: str, deadline_secs: Optional[int] = None
) -> bool:
start_time = time.time()
while True:
job = batch_client.read_namespaced_job_status(job_name, "wandb")
if job.status.succeeded is not None and job.status.succeeded >= 1:
return True
elif job.status.failed is not None and job.status.failed >= 1:
wandb.termerror(f"{LOG_PREFIX}Build job {job.status.failed} failed {job}")
return False
wandb.termlog(f"{LOG_PREFIX}Waiting for build job to complete...")
if deadline_secs is not None and time.time() - start_time > deadline_secs:
return False
time.sleep(5) | python | wandb/sdk/launch/builder/kaniko_builder.py | 51 | 66 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,116 | __init__ | def __init__(
self,
environment: AbstractEnvironment,
registry: AbstractRegistry,
build_job_name: str = "wandb-launch-container-build",
build_context_store: str = "",
secret_name: str = "",
secret_key: str = "",
verify: bool = True,
):
"""Initialize a KanikoBuilder.
Arguments:
environment (AbstractEnvironment): The environment to use.
registry (AbstractRegistry): The registry to use.
build_job_name (str, optional): The name of the build job.
build_context_store (str, optional): The name of the build context store.
secret_name (str, optional): The name of the secret to use for the registry.
secret_key (str, optional): The key of the secret to use for the registry.
verify (bool, optional): Whether to verify the functionality of the builder.
Defaults to True.
"""
if build_context_store is None:
raise LaunchError(
"You are required to specify an external build "
"context store for Kaniko builds. Please specify a storage url "
"in the 'build-context-store' field of your builder config."
)
self.environment = environment
self.registry = registry
self.build_job_name = build_job_name
self.build_context_store = build_context_store.rstrip("/")
self.secret_name = secret_name
self.secret_key = secret_key
if verify:
self.verify() | python | wandb/sdk/launch/builder/kaniko_builder.py | 79 | 114 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,117 | from_config | def from_config(
cls,
config: dict,
environment: AbstractEnvironment,
registry: AbstractRegistry,
verify: bool = True,
login: bool = True,
) -> "AbstractBuilder":
"""Create a KanikoBuilder from a config dict.
Arguments:
config: A dict containing the builder config. Must contain a "type" key
with value "kaniko".
environment: The environment to use for the build.
registry: The registry to use for the build.
verify: Whether to verify the builder config.
Returns:
A KanikoBuilder instance.
"""
if config.get("type") != "kaniko":
raise LaunchError(
"Builder config must include 'type':'kaniko' to create a KanikoBuilder."
)
build_context_store = config.get("build-context-store")
if build_context_store is None:
raise LaunchError(
"You are required to specify an external build "
"context store for Kaniko builds. Please specify a "
"storage url in the 'build_context_store' field of your builder config."
)
build_job_name = config.get("build-job-name", "wandb-launch-container-build")
secret_name = config.get("secret-name", "")
secret_key = config.get("secret-key", "")
return cls(
environment,
registry,
build_context_store=build_context_store,
build_job_name=build_job_name,
secret_name=secret_name,
secret_key=secret_key,
verify=verify,
) | python | wandb/sdk/launch/builder/kaniko_builder.py | 117 | 159 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,118 | verify | def verify(self) -> None:
"""Verify that the builder config is valid.
Raises:
LaunchError: If the builder config is invalid.
"""
if self.environment is None:
raise LaunchError("No environment specified for Kaniko build.")
self.environment.verify_storage_uri(self.build_context_store) | python | wandb/sdk/launch/builder/kaniko_builder.py | 161 | 169 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,119 | login | def login(self) -> None:
"""Login to the registry."""
pass | python | wandb/sdk/launch/builder/kaniko_builder.py | 171 | 173 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,120 | _create_docker_ecr_config_map | def _create_docker_ecr_config_map(
self, job_name: str, corev1_client: client.CoreV1Api, repository: str
) -> None:
if self.registry is None:
raise LaunchError("No registry specified for Kaniko build.")
username, password = self.registry.get_username_password()
encoded = base64.b64encode(f"{username}:{password}".encode()).decode("utf-8")
ecr_config_map = client.V1ConfigMap(
api_version="v1",
kind="ConfigMap",
metadata=client.V1ObjectMeta(
name=f"docker-config-{job_name}",
namespace="wandb",
),
data={
"config.json": json.dumps(
{"auths": {f"{self.registry.get_repo_uri()}": {"auth": encoded}}}
)
},
immutable=True,
)
corev1_client.create_namespaced_config_map("wandb", ecr_config_map) | python | wandb/sdk/launch/builder/kaniko_builder.py | 175 | 196 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,121 | _delete_docker_ecr_config_map | def _delete_docker_ecr_config_map(
self, job_name: str, client: client.CoreV1Api
) -> None:
if self.secret_name:
client.delete_namespaced_config_map(f"docker-config-{job_name}", "wandb") | python | wandb/sdk/launch/builder/kaniko_builder.py | 198 | 202 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,122 | _upload_build_context | def _upload_build_context(self, run_id: str, context_path: str) -> str:
# creat a tar archive of the build context and upload it to s3
context_file = tempfile.NamedTemporaryFile(delete=False)
with tarfile.TarFile.open(fileobj=context_file, mode="w:gz") as context_tgz:
context_tgz.add(context_path, arcname=".")
context_file.close()
destination = f"{self.build_context_store}/{run_id}.tgz"
if self.environment is None:
raise LaunchError("No environment specified for Kaniko build.")
self.environment.upload_file(context_file.name, destination)
return destination | python | wandb/sdk/launch/builder/kaniko_builder.py | 204 | 214 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,123 | build_image | def build_image(
self,
launch_project: LaunchProject,
entrypoint: EntryPoint,
) -> str:
# TODO: this should probably throw an error if the registry is a local registry
if not self.registry:
raise LaunchError("No registry specified for Kaniko build.")
# kaniko builder doesn't seem to work with a custom user id, need more investigation
dockerfile_str = generate_dockerfile(
launch_project, entrypoint, launch_project.resource, "kaniko"
)
image_tag = image_tag_from_dockerfile_and_source(launch_project, dockerfile_str)
repo_uri = self.registry.get_repo_uri()
image_uri = repo_uri + ":" + image_tag
if not launch_project.build_required() and self.registry.check_image_exists(
image_uri
):
return image_uri
_logger.info(f"Building image {image_uri}...")
entry_cmd = " ".join(
get_entry_point_command(entrypoint, launch_project.override_args)
)
create_metadata_file(
launch_project,
image_uri,
sanitize_wandb_api_key(entry_cmd),
sanitize_wandb_api_key(dockerfile_str),
)
context_path = _create_docker_build_ctx(launch_project, dockerfile_str)
run_id = launch_project.run_id
_, api_client = get_kube_context_and_api_client(
kubernetes, launch_project.resource_args
)
build_job_name = f"{self.build_job_name}-{run_id}"
build_context = self._upload_build_context(run_id, context_path)
build_job = self._create_kaniko_job(
build_job_name,
repo_uri,
image_uri,
build_context,
)
wandb.termlog(f"{LOG_PREFIX}Created kaniko job {build_job_name}")
# TODO: use same client as kuberentes.py
batch_v1 = client.BatchV1Api(api_client)
core_v1 = client.CoreV1Api(api_client)
try:
# core_v1.create_namespaced_config_map("wandb", dockerfile_config_map)
if self.secret_name:
self._create_docker_ecr_config_map(build_job_name, core_v1, repo_uri)
batch_v1.create_namespaced_job("wandb", build_job)
# wait for double the job deadline since it might take time to schedule
if not _wait_for_completion(
batch_v1, build_job_name, 3 * _DEFAULT_BUILD_TIMEOUT_SECS
):
raise Exception(f"Failed to build image in kaniko for job {run_id}")
try:
logs = batch_v1.read_namespaced_job_log(build_job_name, "wandb")
warn_failed_packages_from_build_logs(logs, image_uri)
except Exception as e:
wandb.termwarn(
f"{LOG_PREFIX}Failed to get logs for kaniko job {build_job_name}: {e}"
)
except Exception as e:
wandb.termerror(
f"{LOG_PREFIX}Exception when creating Kubernetes resources: {e}\n"
)
raise e
finally:
wandb.termlog(f"{LOG_PREFIX}Cleaning up resources")
try:
# should we clean up the s3 build contexts? can set bucket level policy to auto deletion
# core_v1.delete_namespaced_config_map(config_map_name, "wandb")
if self.secret_name:
self._delete_docker_ecr_config_map(build_job_name, core_v1)
batch_v1.delete_namespaced_job(build_job_name, "wandb")
except Exception as e:
raise LaunchError(f"Exception during Kubernetes resource clean up {e}")
return image_uri | python | wandb/sdk/launch/builder/kaniko_builder.py | 216 | 304 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,124 | _create_kaniko_job | def _create_kaniko_job(
self,
job_name: str,
repository: str,
image_tag: str,
build_context_path: str,
) -> "client.V1Job":
env = []
volume_mounts = []
volumes = []
if bool(self.secret_name) != bool(self.secret_key):
raise LaunchError(
"Both secret_name and secret_key or neither must be specified "
"for kaniko build. You provided only one of them."
)
if isinstance(self.registry, ElasticContainerRegistry):
env += [
client.V1EnvVar(
name="AWS_REGION",
value=self.registry.environment.region,
)
]
if self.secret_name and self.secret_key:
volumes += [
client.V1Volume(
name="docker-config",
config_map=client.V1ConfigMapVolumeSource(
name=f"docker-config-{job_name}",
),
),
]
volume_mounts += [
client.V1VolumeMount(
name="docker-config", mount_path="/kaniko/.docker/"
),
]
# TODO: I don't like conditioning on the registry type here. As a
# future change I want the registry and environment classes to provide
# a list of environment variables and volume mounts that need to be
# added to the job. The environment class provides credentials for
# build context access, and the registry class provides credentials
# for pushing the image. This way we can have separate secrets for
# each and support build contexts and registries that require
# different credentials.
if isinstance(self.registry, ElasticContainerRegistry):
mount_path = "/root/.aws"
key = "credentials"
elif isinstance(self.registry, GoogleArtifactRegistry):
mount_path = "/kaniko/.config/gcloud"
key = "config.json"
env += [
client.V1EnvVar(
name="GOOGLE_APPLICATION_CREDENTIALS",
value="/kaniko/.config/gcloud/config.json",
)
]
else:
raise LaunchError(
f"Registry type {type(self.registry)} not supported by kaniko"
)
volume_mounts += [
client.V1VolumeMount(
name=self.secret_name,
mount_path=mount_path,
read_only=True,
)
]
volumes += [
client.V1Volume(
name=self.secret_name,
secret=client.V1SecretVolumeSource(
secret_name=self.secret_name,
items=[client.V1KeyToPath(key=self.secret_key, path=key)],
),
)
]
args = [
f"--context={build_context_path}",
"--dockerfile=Dockerfile.wandb-autogenerated",
f"--destination={image_tag}",
"--cache=true",
f"--cache-repo={repository}",
"--snapshotMode=redo",
"--compressed-caching=false",
]
container = client.V1Container(
name="wandb-container-build",
image="gcr.io/kaniko-project/executor:v1.8.0",
args=args,
volume_mounts=volume_mounts,
env=env if env else None,
)
# Create and configure a spec section
template = client.V1PodTemplateSpec(
metadata=client.V1ObjectMeta(labels={"wandb": "launch"}),
spec=client.V1PodSpec(
restart_policy="Never",
active_deadline_seconds=_DEFAULT_BUILD_TIMEOUT_SECS,
containers=[container],
volumes=volumes,
),
)
# Create the specification of job
spec = client.V1JobSpec(template=template, backoff_limit=1)
job = client.V1Job(
api_version="batch/v1",
kind="Job",
metadata=client.V1ObjectMeta(
name=job_name, namespace="wandb", labels={"wandb": "launch"}
),
spec=spec,
)
return job | python | wandb/sdk/launch/builder/kaniko_builder.py | 306 | 419 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,125 | __init__ | def __init__(
self,
environment: AbstractEnvironment,
registry: AbstractRegistry,
verify: bool = True,
login: bool = True,
):
"""Initialize a DockerBuilder.
Arguments:
environment (AbstractEnvironment): The environment to use.
registry (AbstractRegistry): The registry to use.
verify (bool, optional): Whether to verify the functionality of the builder.
login (bool, optional): Whether to login to the registry.
Raises:
LaunchError: If docker is not installed
"""
self.environment = environment # Docker builder doesn't actually use this.
self.registry = registry
if verify:
self.verify()
if login:
self.login() | python | wandb/sdk/launch/builder/docker_builder.py | 49 | 72 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,126 | from_config | def from_config(
cls,
config: Dict[str, Any],
environment: AbstractEnvironment,
registry: AbstractRegistry,
verify: bool = True,
) -> "DockerBuilder":
"""Create a DockerBuilder from a config.
Arguments:
config (Dict[str, Any]): The config.
registry (AbstractRegistry): The registry to use.
verify (bool, optional): Whether to verify the functionality of the builder.
login (bool, optional): Whether to login to the registry.
Returns:
DockerBuilder: The DockerBuilder.
"""
# TODO the config for the docker builder as of yet is empty
# but ultimately we should add things like target platform, base image, etc.
return cls(environment, registry) | python | wandb/sdk/launch/builder/docker_builder.py | 75 | 95 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,127 | verify | def verify(self) -> None:
"""Verify the builder."""
validate_docker_installation() | python | wandb/sdk/launch/builder/docker_builder.py | 97 | 99 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,128 | login | def login(self) -> None:
"""Login to the registry."""
if isinstance(self.registry, LocalRegistry):
_logger.info(f"{LOG_PREFIX}No registry configured, skipping login.")
else:
username, password = self.registry.get_username_password()
docker.login(username, password, self.registry.uri) | python | wandb/sdk/launch/builder/docker_builder.py | 101 | 107 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,129 | build_image | def build_image(
self,
launch_project: LaunchProject,
entrypoint: EntryPoint,
) -> str:
"""Build the image for the given project.
Arguments:
launch_project (LaunchProject): The project to build.
entrypoint (EntryPoint): The entrypoint to use.
"""
dockerfile_str = generate_dockerfile(
launch_project, entrypoint, launch_project.resource, "docker"
)
image_tag = image_tag_from_dockerfile_and_source(launch_project, dockerfile_str)
repository = None if not self.registry else self.registry.get_repo_uri()
# if repo is set, use the repo name as the image name
if repository:
image_uri = f"{repository}:{image_tag}"
# otherwise, base the image name off of the source
# which the launch_project checks in image_name
else:
image_uri = f"{launch_project.image_name}:{image_tag}"
if not launch_project.build_required() and self.registry.check_image_exists(
image_uri
):
return image_uri
_logger.info(
f"image {image_uri} does not already exist in repository, building."
)
entry_cmd = get_entry_point_command(entrypoint, launch_project.override_args)
create_metadata_file(
launch_project,
image_uri,
sanitize_wandb_api_key(" ".join(entry_cmd)),
dockerfile_str,
)
build_ctx_path = _create_docker_build_ctx(launch_project, dockerfile_str)
dockerfile = os.path.join(build_ctx_path, _GENERATED_DOCKERFILE_NAME)
try:
output = docker.build(
tags=[image_uri], file=dockerfile, context_path=build_ctx_path
)
warn_failed_packages_from_build_logs(output, image_uri)
except docker.DockerError as e:
raise LaunchDockerError(f"Error communicating with docker client: {e}")
try:
os.remove(build_ctx_path)
except Exception:
_msg = f"{LOG_PREFIX}Temporary docker context file {build_ctx_path} was not deleted."
_logger.info(_msg)
if repository:
reg, tag = image_uri.split(":")
wandb.termlog(f"{LOG_PREFIX}Pushing image {image_uri}")
push_resp = docker.push(reg, tag)
if push_resp is None:
raise LaunchError("Failed to push image to repository")
elif (
launch_project.resource == "sagemaker"
and f"The push refers to repository [{repository}]" not in push_resp
):
raise LaunchError(f"Unable to push image to ECR, response: {push_resp}")
return image_uri | python | wandb/sdk/launch/builder/docker_builder.py | 109 | 181 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,130 | __init__ | def __init__(
self,
builder_config: Dict[str, Any],
environment: AbstractEnvironment,
registry: AbstractRegistry,
) -> None:
"""Initialize a NoOpBuilder."""
pass | python | wandb/sdk/launch/builder/noop.py | 17 | 24 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,131 | from_config | def from_config(
cls,
config: dict,
environment: AbstractEnvironment,
registry: AbstractRegistry,
verify: bool = True,
) -> "AbstractBuilder":
"""Create a noop builder from a config."""
return cls(config, environment, registry) | python | wandb/sdk/launch/builder/noop.py | 27 | 35 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,132 | verify | def verify(self) -> None:
"""Verify the builder."""
raise LaunchError("Attempted to verify noop builder.") | python | wandb/sdk/launch/builder/noop.py | 37 | 39 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,133 | build_image | def build_image(
self,
launch_project: LaunchProject,
entrypoint: EntryPoint,
) -> str:
"""Build the image.
For this we raise a launch error since it can't build.
"""
raise LaunchError(
"Attempted build with noop builder. Specify a builder in your launch config at ~/.config/wandb/launch-config.yaml"
) | python | wandb/sdk/launch/builder/noop.py | 41 | 52 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,134 | install_deps | def install_deps(
deps: List[str],
failed: Optional[Set[str]] = None,
extra_index: Optional[str] = None,
opts: Optional[List[str]] = None,
) -> Optional[Set[str]]:
"""Install pip dependencies.
Arguments:
deps {List[str]} -- List of dependencies to install
failed (set, None): The libraries that failed to install
Returns:
deps (str[], None): The dependencies that failed to install
"""
try:
# Include only uri if @ is present
clean_deps = [d.split("@")[-1].strip() if "@" in d else d for d in deps]
index_args = ["--extra-index-url", extra_index] if extra_index else []
print("installing {}...".format(", ".join(clean_deps)))
opts = opts or []
args = ["pip", "install"] + opts + clean_deps + index_args
sys.stdout.flush()
subprocess.check_output(args, stderr=subprocess.STDOUT)
return failed
except subprocess.CalledProcessError as e:
if failed is None:
failed = set()
num_failed = len(failed)
for line in e.output.decode("utf8").splitlines():
if line.startswith("ERROR:"):
clean_dep = find_package_in_error_string(clean_deps, line)
if clean_dep is not None:
if clean_dep in deps:
failed.add(clean_dep)
else:
for d in deps:
if clean_dep in d:
failed.add(d.replace(" ", ""))
break
if len(set(clean_deps) - failed) == 0:
return failed
elif len(failed) > num_failed:
return install_deps(
list(set(clean_deps) - failed),
failed,
extra_index=extra_index,
opts=opts,
)
else:
return failed | python | wandb/sdk/launch/builder/templates/_wandb_bootstrap.py | 26 | 76 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,135 | main | def main() -> None:
"""Install deps in requirements.frozen.txt."""
extra_index = None
torch_reqs = []
if os.path.exists("requirements.frozen.txt"):
with open("requirements.frozen.txt") as f:
print("Installing frozen dependencies...")
reqs = []
failed: Set[str] = set()
for req in f:
if (
len(ONLY_INCLUDE) == 0
or req in ONLY_INCLUDE
or req.split("=")[0].lower() in ONLY_INCLUDE
):
# can't pip install wandb==0.*.*.dev1 through pip. Lets just install wandb for now
if req.startswith("wandb==") and "dev1" in req:
req = "wandb"
match = re.match(
r"torch(vision|audio)?==\d+\.\d+\.\d+(\+(?:cu[\d]{2,3})|(?:cpu))?",
req,
)
if match:
variant = match.group(2)
if variant:
extra_index = (
f"https://download.pytorch.org/whl/{variant[1:]}"
)
torch_reqs.append(req.strip().replace(" ", ""))
else:
reqs.append(req.strip().replace(" ", ""))
else:
print(f"Ignoring requirement: {req} from frozen requirements")
if len(reqs) >= CORES:
deps_failed = install_deps(reqs, opts=OPTS)
reqs = []
if deps_failed is not None:
failed = failed.union(deps_failed)
if len(reqs) > 0:
deps_failed = install_deps(reqs, opts=OPTS)
if deps_failed is not None:
failed = failed.union(deps_failed)
with open("_wandb_bootstrap_errors.json", "w") as f:
f.write(json.dumps({"pip": list(failed)}))
if len(failed) > 0:
sys.stderr.write(
FAILED_PACKAGES_PREFIX + ",".join(failed) + FAILED_PACKAGES_POSTFIX
)
sys.stderr.flush()
install_deps(torch_reqs, extra_index=extra_index)
else:
print("No frozen requirements found") | python | wandb/sdk/launch/builder/templates/_wandb_bootstrap.py | 79 | 130 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,136 | find_package_in_error_string | def find_package_in_error_string(deps: List[str], line: str) -> Optional[str]:
# if the last word in the error string is in the list of deps, return it
last_word = line.split(" ")[-1]
if last_word in deps:
return last_word
# if the last word is not in the list of deps, check all words
# TODO: this could report the wrong package if the error string
# contains a reference to another package in the deps
# before the package that failed to install
for word in line.split(" "):
if word in deps:
return word
# if we can't find the package, return None
return None | python | wandb/sdk/launch/builder/templates/_wandb_bootstrap.py | 136 | 149 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,137 | _find_available | def _find_available(
current_version: str,
) -> Optional[Tuple[str, bool, bool, bool, Optional[str]]]:
from pkg_resources import parse_version
pypi_url = f"https://pypi.org/pypi/{wandb._wandb_module}/json"
yanked_dict = {}
try:
# raise Exception("test")
async_requests_get = wandb.util.async_call(requests.get, timeout=5)
data, thread = async_requests_get(pypi_url, timeout=3)
if not data or isinstance(data, Exception):
return None
data = data.json()
latest_version = data["info"]["version"]
release_list = data["releases"].keys()
for version, fields in data["releases"].items():
for item in fields:
yanked = item.get("yanked")
yanked_reason = item.get("yanked_reason")
if yanked:
yanked_dict[version] = yanked_reason
except Exception:
# Any issues whatsoever, just skip the latest version check.
return None
# Return if no update is available
pip_prerelease = False
deleted = False
yanked = False
yanked_reason = None
parsed_current_version = parse_version(current_version)
# Check if current version has been yanked or deleted
# NOTE: we will not return yanked or deleted if there is nothing to upgrade to
if current_version in release_list:
yanked = current_version in yanked_dict
yanked_reason = yanked_dict.get(current_version)
else:
deleted = True
# Check pre-releases
if parse_version(latest_version) <= parsed_current_version:
# pre-releases are not included in latest_version
# so if we are currently running a pre-release we check more
if not parsed_current_version.is_prerelease:
return None
# Candidates are pre-releases with the same base_version
release_list = map(parse_version, release_list)
release_list = filter(lambda v: v.is_prerelease, release_list)
release_list = filter(
lambda v: v.base_version == parsed_current_version.base_version,
release_list,
)
release_list = sorted(release_list)
if not release_list:
return None
parsed_latest_version = release_list[-1]
if parsed_latest_version <= parsed_current_version:
return None
latest_version = str(parsed_latest_version)
pip_prerelease = True
return latest_version, pip_prerelease, deleted, yanked, yanked_reason | python | wandb/sdk/internal/update.py | 8 | 73 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,138 | check_available | def check_available(current_version: str) -> Optional[Dict[str, Optional[str]]]:
package_info = _find_available(current_version)
if not package_info:
return None
wandb_module_name = wandb._wandb_module
latest_version, pip_prerelease, deleted, yanked, yanked_reason = package_info
upgrade_message = (
"%s version %s is available! To upgrade, please run:\n"
" $ pip install %s --upgrade%s"
% (
wandb_module_name,
latest_version,
wandb_module_name,
" --pre" if pip_prerelease else "",
)
)
delete_message = None
if deleted:
delete_message = "{} version {} has been retired! Please upgrade.".format(
wandb_module_name,
current_version,
)
yank_message = None
if yanked:
reason_message = "(%s) " % yanked_reason if yanked_reason else ""
yank_message = "{} version {} has been recalled! {}Please upgrade.".format(
wandb_module_name,
current_version,
reason_message,
)
# A new version is available!
return {
"upgrade_message": upgrade_message,
"yank_message": yank_message,
"delete_message": delete_message,
} | python | wandb/sdk/internal/update.py | 76 | 114 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,139 | _framework_priority | def _framework_priority() -> Generator[Tuple[str, str], None, None]:
yield from [
("lightgbm", "lightgbm"),
("catboost", "catboost"),
("xgboost", "xgboost"),
("transformers_huggingface", "huggingface"), # backwards compatibility
("transformers", "huggingface"),
("pytorch_ignite", "ignite"), # backwards compatibility
("ignite", "ignite"),
("pytorch_lightning", "lightning"),
("fastai", "fastai"),
("torch", "torch"),
("keras", "keras"),
("tensorflow", "tensorflow"),
("sklearn", "sklearn"),
] | python | wandb/sdk/internal/sender.py | 92 | 107 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,140 | _manifest_json_from_proto | def _manifest_json_from_proto(manifest: "ArtifactManifest") -> Dict:
if manifest.version == 1:
contents = {
content.path: {
"digest": content.digest,
"birthArtifactID": content.birth_artifact_id
if content.birth_artifact_id
else None,
"ref": content.ref if content.ref else None,
"size": content.size if content.size is not None else None,
"local_path": content.local_path if content.local_path else None,
"extra": {
extra.key: json.loads(extra.value_json) for extra in content.extra
},
}
for content in manifest.contents
}
else:
raise ValueError(f"unknown artifact manifest version: {manifest.version}")
return {
"version": manifest.version,
"storagePolicy": manifest.storage_policy,
"storagePolicyConfig": {
config.key: json.loads(config.value_json)
for config in manifest.storage_policy_config
},
"contents": contents,
} | python | wandb/sdk/internal/sender.py | 110 | 138 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,141 | __init__ | def __init__(self) -> None:
self.resumed = False
self.step = 0
self.history = 0
self.events = 0
self.output = 0
self.runtime = 0
# wandb_runtime is the canonical runtime (stored in summary._wandb.runtime)
self.wandb_runtime = None
self.summary = None
self.config = None | python | wandb/sdk/internal/sender.py | 152 | 162 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,142 | __str__ | def __str__(self) -> str:
obj = ",".join(map(lambda it: f"{it[0]}={it[1]}", vars(self).items()))
return f"ResumeState({obj})" | python | wandb/sdk/internal/sender.py | 164 | 166 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,143 | __init__ | def __init__(self, stream: str, sm: "SendManager"):
self._stopped = threading.Event()
self._queue = queue.Queue()
self._emulator = redirect.TerminalEmulator()
self._writer_thr = threading.Thread(
target=sm._output_raw_writer_thread,
kwargs=dict(stream=stream),
daemon=True,
name=f"OutRawWr-{stream}",
)
self._reader_thr = threading.Thread(
target=sm._output_raw_reader_thread,
kwargs=dict(stream=stream),
daemon=True,
name=f"OutRawRd-{stream}",
) | python | wandb/sdk/internal/sender.py | 176 | 191 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,144 | start | def start(self) -> None:
self._writer_thr.start()
self._reader_thr.start() | python | wandb/sdk/internal/sender.py | 193 | 195 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,145 | __init__ | def __init__(
self,
settings: SettingsStatic,
record_q: "Queue[Record]",
result_q: "Queue[Result]",
interface: InterfaceQueue,
context_keeper: context.ContextKeeper,
) -> None:
self._settings = settings
self._record_q = record_q
self._result_q = result_q
self._interface = interface
self._context_keeper = context_keeper
self._ds = None
self._send_record_num = 0
self._send_end_offset = 0
self._fs = None
self._pusher = None
self._dir_watcher = None
# State updated by login
self._entity = None
self._flags = None
# State updated by wandb.init
self._run = None
self._project = None
# keep track of config from key/val updates
self._consolidated_config: DictNoValues = cast(DictNoValues, dict())
self._start_time: float = 0
self._telemetry_obj = telemetry.TelemetryRecord()
self._config_metric_pbdict_list: List[Dict[int, Any]] = []
self._metadata_summary: Dict[str, Any] = defaultdict()
self._cached_summary: Dict[str, Any] = dict()
self._config_metric_index_dict: Dict[str, int] = {}
self._config_metric_dict: Dict[str, wandb_internal_pb2.MetricRecord] = {}
self._cached_server_info = dict()
self._cached_viewer = dict()
self._server_messages = []
# State updated by resuming
self._resume_state = ResumeState()
# State added when run_exit is initiated and complete
self._record_exit = None
self._exit_result = None
self._api = internal_api.Api(
default_settings=settings, retry_callback=self.retry_callback
)
self._api_settings = dict()
# queue filled by retry_callback
self._retry_q: "Queue[HttpResponse]" = queue.Queue()
# do we need to debounce?
self._config_needs_debounce: bool = False
# TODO(jhr): do something better, why do we need to send full lines?
self._partial_output = dict()
self._exit_code = 0
# internal vars for handing raw console output
self._output_raw_streams = dict()
self._output_raw_file = None
# job builder
self._job_builder = JobBuilder(settings)
time_now = time.monotonic()
self._debounce_config_time = time_now
self._debounce_status_time = time_now | python | wandb/sdk/internal/sender.py | 231 | 307 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,146 | setup | def setup(cls, root_dir: str, resume: Union[None, bool, str]) -> "SendManager":
"""Set up a standalone SendManager.
Currently, we're using this primarily for `sync.py`.
"""
files_dir = os.path.join(root_dir, "files")
# TODO(settings) replace with wandb.Settings
sd: SettingsDict = dict(
files_dir=files_dir,
root_dir=root_dir,
_start_time=0,
git_remote=None,
resume=resume,
program=None,
ignore_globs=(),
run_id=None,
entity=None,
project=None,
run_group=None,
job_type=None,
run_tags=None,
run_name=None,
run_notes=None,
save_code=None,
email=None,
silent=None,
_offline=None,
_sync=True,
_live_policy_rate_limit=None,
_live_policy_wait_time=None,
disable_job_creation=False,
_async_upload_concurrency_limit=None,
)
settings = SettingsStatic(sd)
record_q: "Queue[Record]" = queue.Queue()
result_q: "Queue[Result]" = queue.Queue()
publish_interface = InterfaceQueue(record_q=record_q)
context_keeper = context.ContextKeeper()
return SendManager(
settings=settings,
record_q=record_q,
result_q=result_q,
interface=publish_interface,
context_keeper=context_keeper,
) | python | wandb/sdk/internal/sender.py | 310 | 354 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,147 | __len__ | def __len__(self) -> int:
return self._record_q.qsize() | python | wandb/sdk/internal/sender.py | 356 | 357 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,148 | retry_callback | def retry_callback(self, status: int, response_text: str) -> None:
response = wandb_internal_pb2.HttpResponse()
response.http_status_code = status
response.http_response_text = response_text
self._retry_q.put(response) | python | wandb/sdk/internal/sender.py | 359 | 363 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,149 | send | def send(self, record: "Record") -> None:
self._update_record_num(record.num)
self._update_end_offset(record.control.end_offset)
record_type = record.WhichOneof("record_type")
assert record_type
handler_str = "send_" + record_type
send_handler = getattr(self, handler_str, None)
# Don't log output to reduce log noise
if record_type not in {"output", "request", "output_raw"}:
logger.debug(f"send: {record_type}")
assert send_handler, f"unknown send handler: {handler_str}"
context_id = context.context_id_from_record(record)
api_context = self._context_keeper.get(context_id)
try:
self._api.set_local_context(api_context)
send_handler(record)
except ContextCancelledError:
logger.debug(f"Record cancelled: {record_type}")
self._context_keeper.release(context_id)
finally:
self._api.clear_local_context() | python | wandb/sdk/internal/sender.py | 365 | 387 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,150 | send_preempting | def send_preempting(self, record: "Record") -> None:
if self._fs:
self._fs.enqueue_preempting() | python | wandb/sdk/internal/sender.py | 389 | 391 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,151 | send_request_sender_mark | def send_request_sender_mark(self, record: "Record") -> None:
self._maybe_report_status(always=True) | python | wandb/sdk/internal/sender.py | 393 | 394 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,152 | send_request | def send_request(self, record: "Record") -> None:
request_type = record.request.WhichOneof("request_type")
assert request_type
handler_str = "send_request_" + request_type
send_handler = getattr(self, handler_str, None)
if request_type != "network_status":
logger.debug(f"send_request: {request_type}")
assert send_handler, f"unknown handle: {handler_str}"
send_handler(record) | python | wandb/sdk/internal/sender.py | 396 | 404 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,153 | _respond_result | def _respond_result(self, result: "Result") -> None:
tracelog.log_message_queue(result, self._result_q)
context_id = context.context_id_from_result(result)
self._context_keeper.release(context_id)
self._result_q.put(result) | python | wandb/sdk/internal/sender.py | 406 | 410 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,154 | _flatten | def _flatten(self, dictionary: Dict) -> None:
if type(dictionary) == dict:
for k, v in list(dictionary.items()):
if type(v) == dict:
self._flatten(v)
dictionary.pop(k)
for k2, v2 in v.items():
dictionary[k + "." + k2] = v2 | python | wandb/sdk/internal/sender.py | 412 | 419 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,155 | _update_record_num | def _update_record_num(self, record_num: int) -> None:
if not record_num:
return
# Currently how we handle offline mode and syncing is not
# compatible with this assertion due to how the exit record
# is (mis)handled:
# - using "always_send" in offline mode to trigger defer
# state machine
# - skipping the exit record in `wandb sync` mode so that
# it is always executed as the last record
if not self._settings._offline and not self._settings._sync:
assert record_num == self._send_record_num + 1
self._send_record_num = record_num | python | wandb/sdk/internal/sender.py | 421 | 433 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,156 | _update_end_offset | def _update_end_offset(self, end_offset: int) -> None:
if not end_offset:
return
self._send_end_offset = end_offset | python | wandb/sdk/internal/sender.py | 435 | 438 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,157 | send_request_sender_read | def send_request_sender_read(self, record: "Record") -> None:
if self._ds is None:
self._ds = datastore.DataStore()
self._ds.open_for_scan(self._settings.sync_file)
# TODO(cancel_paused): implement cancel_set logic
# The idea is that there is an active request to cancel a
# message that is being read from the transaction log below
start_offset = record.request.sender_read.start_offset
final_offset = record.request.sender_read.final_offset
self._ds.seek(start_offset)
current_end_offset = 0
while current_end_offset < final_offset:
data = self._ds.scan_data()
assert data
current_end_offset = self._ds.get_offset()
send_record = wandb_internal_pb2.Record()
send_record.ParseFromString(data)
self._update_end_offset(current_end_offset)
self.send(send_record)
# make sure we perform deferred operations
self.debounce()
# make sure that we always update writer for every sended read request
self._maybe_report_status(always=True) | python | wandb/sdk/internal/sender.py | 440 | 468 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,158 | send_request_check_version | def send_request_check_version(self, record: "Record") -> None:
assert record.control.req_resp or record.control.mailbox_slot
result = proto_util._result_from_record(record)
current_version = (
record.request.check_version.current_version or wandb.__version__
)
messages = update.check_available(current_version)
if messages:
upgrade_message = messages.get("upgrade_message")
if upgrade_message:
result.response.check_version_response.upgrade_message = upgrade_message
yank_message = messages.get("yank_message")
if yank_message:
result.response.check_version_response.yank_message = yank_message
delete_message = messages.get("delete_message")
if delete_message:
result.response.check_version_response.delete_message = delete_message
self._respond_result(result) | python | wandb/sdk/internal/sender.py | 470 | 487 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,159 | _send_request_attach | def _send_request_attach(
self,
req: wandb_internal_pb2.AttachRequest,
resp: wandb_internal_pb2.AttachResponse,
) -> None:
attach_id = req.attach_id
assert attach_id
assert self._run
resp.run.CopyFrom(self._run) | python | wandb/sdk/internal/sender.py | 489 | 497 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,160 | send_request_attach | def send_request_attach(self, record: "Record") -> None:
assert record.control.req_resp or record.control.mailbox_slot
result = proto_util._result_from_record(record)
self._send_request_attach(
record.request.attach, result.response.attach_response
)
self._respond_result(result) | python | wandb/sdk/internal/sender.py | 499 | 505 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,161 | send_request_stop_status | def send_request_stop_status(self, record: "Record") -> None:
result = proto_util._result_from_record(record)
status_resp = result.response.stop_status_response
status_resp.run_should_stop = False
if self._entity and self._project and self._run and self._run.run_id:
try:
status_resp.run_should_stop = self._api.check_stop_requested(
self._project, self._entity, self._run.run_id
)
except Exception as e:
logger.warning("Failed to check stop requested status: %s", e)
self._respond_result(result) | python | wandb/sdk/internal/sender.py | 507 | 518 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,162 | _maybe_update_config | def _maybe_update_config(self, always: bool = False) -> None:
time_now = time.monotonic()
if (
not always
and time_now < self._debounce_config_time + self.UPDATE_CONFIG_TIME
):
return
if self._config_needs_debounce:
self._debounce_config()
self._debounce_config_time = time_now | python | wandb/sdk/internal/sender.py | 520 | 529 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,163 | _maybe_report_status | def _maybe_report_status(self, always: bool = False) -> None:
time_now = time.monotonic()
if (
not always
and time_now < self._debounce_status_time + self.UPDATE_STATUS_TIME
):
return
self._debounce_status_time = time_now
status_report = wandb_internal_pb2.StatusReportRequest(
record_num=self._send_record_num,
sent_offset=self._send_end_offset,
)
status_time = time.time()
status_report.sync_time.FromMicroseconds(int(status_time * 1e6))
record = self._interface._make_request(status_report=status_report)
self._interface._publish(record) | python | wandb/sdk/internal/sender.py | 531 | 547 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,164 | debounce | def debounce(self, final: bool = False) -> None:
self._maybe_report_status(always=final)
self._maybe_update_config(always=final) | python | wandb/sdk/internal/sender.py | 549 | 551 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,165 | _debounce_config | def _debounce_config(self) -> None:
config_value_dict = self._config_format(self._consolidated_config)
# TODO(jhr): check result of upsert_run?
if self._run:
self._api.upsert_run(
name=self._run.run_id, config=config_value_dict, **self._api_settings # type: ignore
)
self._config_save(config_value_dict)
self._config_needs_debounce = False | python | wandb/sdk/internal/sender.py | 553 | 561 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,166 | send_request_network_status | def send_request_network_status(self, record: "Record") -> None:
result = proto_util._result_from_record(record)
status_resp = result.response.network_status_response
while True:
try:
status_resp.network_responses.append(self._retry_q.get_nowait())
except queue.Empty:
break
except Exception as e:
logger.warning(f"Error emptying retry queue: {e}")
self._respond_result(result) | python | wandb/sdk/internal/sender.py | 563 | 573 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,167 | send_request_login | def send_request_login(self, record: "Record") -> None:
# TODO: do something with api_key or anonymous?
# TODO: return an error if we aren't logged in?
self._api.reauth()
viewer = self.get_viewer_info()
server_info = self.get_server_info()
# self._login_flags = json.loads(viewer.get("flags", "{}"))
# self._login_entity = viewer.get("entity")
if server_info:
logger.info(f"Login server info: {server_info}")
self._entity = viewer.get("entity")
if record.control.req_resp:
result = proto_util._result_from_record(record)
if self._entity:
result.response.login_response.active_entity = self._entity
self._respond_result(result) | python | wandb/sdk/internal/sender.py | 575 | 590 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,168 | send_exit | def send_exit(self, record: "Record") -> None:
# track where the exit came from
self._record_exit = record
run_exit = record.exit
self._exit_code = run_exit.exit_code
logger.info("handling exit code: %s", run_exit.exit_code)
runtime = run_exit.runtime
logger.info("handling runtime: %s", run_exit.runtime)
self._metadata_summary["runtime"] = runtime
self._update_summary()
# We need to give the request queue a chance to empty between states
# so use handle_request_defer as a state machine.
logger.info("send defer")
self._interface.publish_defer() | python | wandb/sdk/internal/sender.py | 592 | 607 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,169 | send_final | def send_final(self, record: "Record") -> None:
pass | python | wandb/sdk/internal/sender.py | 609 | 610 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,170 | _flush_run | def _flush_run(self) -> None:
pass | python | wandb/sdk/internal/sender.py | 612 | 613 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,171 | send_request_status_report | def send_request_status_report(self, record: "Record") -> None:
# todo? this is just a noop to please wandb sync
pass | python | wandb/sdk/internal/sender.py | 615 | 617 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,172 | send_request_defer | def send_request_defer(self, record: "Record") -> None: # noqa: C901
defer = record.request.defer
state = defer.state
logger.info(f"handle sender defer: {state}")
def transition_state() -> None:
state = defer.state + 1
logger.info(f"send defer: {state}")
self._interface.publish_defer(state)
done = False
if state == defer.BEGIN:
transition_state()
elif state == defer.FLUSH_RUN:
self._flush_run()
transition_state()
elif state == defer.FLUSH_STATS:
# NOTE: this is handled in handler.py:handle_request_defer()
transition_state()
elif state == defer.FLUSH_PARTIAL_HISTORY:
# NOTE: this is handled in handler.py:handle_request_defer()
transition_state()
elif state == defer.FLUSH_TB:
# NOTE: this is handled in handler.py:handle_request_defer()
transition_state()
elif state == defer.FLUSH_SUM:
# NOTE: this is handled in handler.py:handle_request_defer()
transition_state()
elif state == defer.FLUSH_DEBOUNCER:
self.debounce(final=True)
transition_state()
elif state == defer.FLUSH_OUTPUT:
self._output_raw_finish()
transition_state()
elif state == defer.FLUSH_JOB:
self._flush_job()
transition_state()
elif state == defer.FLUSH_DIR:
if self._dir_watcher:
self._dir_watcher.finish()
self._dir_watcher = None
transition_state()
elif state == defer.FLUSH_FP:
if self._pusher:
# FilePusher generates some events for FileStreamApi, so we
# need to wait for pusher to finish before going to the next
# state to ensure that filestream gets all the events that we
# want before telling it to finish up
self._pusher.finish(transition_state)
else:
transition_state()
elif state == defer.JOIN_FP:
if self._pusher:
self._pusher.join()
transition_state()
elif state == defer.FLUSH_FS:
if self._fs:
# TODO(jhr): now is a good time to output pending output lines
self._fs.finish(self._exit_code)
self._fs = None
transition_state()
elif state == defer.FLUSH_FINAL:
self._interface.publish_final()
self._interface.publish_footer()
transition_state()
elif state == defer.END:
done = True
else:
raise AssertionError("unknown state")
if not done:
return
exit_result = wandb_internal_pb2.RunExitResult()
# mark exit done in case we are polling on exit
self._exit_result = exit_result
# Report response to mailbox
if self._record_exit and self._record_exit.control.mailbox_slot:
result = proto_util._result_from_record(self._record_exit)
result.exit_result.CopyFrom(exit_result)
self._respond_result(result) | python | wandb/sdk/internal/sender.py | 619 | 701 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,173 | transition_state | def transition_state() -> None:
state = defer.state + 1
logger.info(f"send defer: {state}")
self._interface.publish_defer(state) | python | wandb/sdk/internal/sender.py | 624 | 627 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,174 | send_request_poll_exit | def send_request_poll_exit(self, record: "Record") -> None:
if not record.control.req_resp and not record.control.mailbox_slot:
return
result = proto_util._result_from_record(record)
if self._pusher:
_alive, status = self._pusher.get_status()
file_counts = self._pusher.file_counts_by_category()
resp = result.response.poll_exit_response
resp.pusher_stats.uploaded_bytes = status.uploaded_bytes
resp.pusher_stats.total_bytes = status.total_bytes
resp.pusher_stats.deduped_bytes = status.deduped_bytes
resp.file_counts.wandb_count = file_counts.wandb
resp.file_counts.media_count = file_counts.media
resp.file_counts.artifact_count = file_counts.artifact
resp.file_counts.other_count = file_counts.other
if self._exit_result:
result.response.poll_exit_response.done = True
result.response.poll_exit_response.exit_result.CopyFrom(self._exit_result)
self._respond_result(result) | python | wandb/sdk/internal/sender.py | 703 | 725 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,175 | send_request_server_info | def send_request_server_info(self, record: "Record") -> None:
assert record.control.req_resp or record.control.mailbox_slot
result = proto_util._result_from_record(record)
result.response.server_info_response.local_info.CopyFrom(self.get_local_info())
for message in self._server_messages:
# guard agains the case the message level returns malformed from server
message_level = str(message.get("messageLevel"))
message_level_sanitized = int(
printer.INFO if not message_level.isdigit() else message_level
)
result.response.server_info_response.server_messages.item.append(
wandb_internal_pb2.ServerMessage(
utf_text=message.get("utfText", ""),
plain_text=message.get("plainText", ""),
html_text=message.get("htmlText", ""),
type=message.get("messageType", ""),
level=message_level_sanitized,
)
)
self._respond_result(result) | python | wandb/sdk/internal/sender.py | 727 | 747 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,176 | _maybe_setup_resume | def _maybe_setup_resume(
self, run: "RunRecord"
) -> Optional["wandb_internal_pb2.ErrorInfo"]:
"""Queries the backend for a run; fail if the settings are incompatible."""
if not self._settings.resume:
return None
# TODO: This causes a race, we need to make the upsert atomically
# only create or update depending on the resume config
# we use the runs entity if set, otherwise fallback to users entity
# todo: ensure entity is not None as self._entity is Optional[str]
entity = run.entity or self._entity
logger.info(
"checking resume status for %s/%s/%s", entity, run.project, run.run_id
)
resume_status = self._api.run_resume_status(
entity=entity, project_name=run.project, name=run.run_id # type: ignore
)
if not resume_status:
if self._settings.resume == "must":
error = wandb_internal_pb2.ErrorInfo()
error.code = wandb_internal_pb2.ErrorInfo.ErrorCode.USAGE
error.message = (
"You provided an invalid value for the `resume` argument."
f" The value 'must' is not a valid option for resuming a run ({run.run_id}) that does not exist."
" Please check your inputs and try again with a valid run ID."
" If you are trying to start a new run, please omit the `resume` argument or use `resume='allow'`."
)
return error
return None
#
# handle cases where we have resume_status
#
if self._settings.resume == "never":
error = wandb_internal_pb2.ErrorInfo()
error.code = wandb_internal_pb2.ErrorInfo.ErrorCode.USAGE
error.message = (
"You provided an invalid value for the `resume` argument."
f" The value 'never' is not a valid option for resuming a run ({run.run_id}) that already exists."
" Please check your inputs and try again with a valid value for the `resume` argument."
)
return error
history = {}
events = {}
config = {}
summary = {}
try:
events_rt = 0
history_rt = 0
history = json.loads(resume_status["historyTail"])
if history:
history = json.loads(history[-1])
history_rt = history.get("_runtime", 0)
events = json.loads(resume_status["eventsTail"])
if events:
events = json.loads(events[-1])
events_rt = events.get("_runtime", 0)
config = json.loads(resume_status["config"] or "{}")
summary = json.loads(resume_status["summaryMetrics"] or "{}")
new_runtime = summary.get("_wandb", {}).get("runtime", None)
if new_runtime is not None:
self._resume_state.wandb_runtime = new_runtime
except (IndexError, ValueError) as e:
logger.error("unable to load resume tails", exc_info=e)
if self._settings.resume == "must":
error = wandb_internal_pb2.ErrorInfo()
error.code = wandb_internal_pb2.ErrorInfo.ErrorCode.USAGE
error.message = "resume='must' but could not resume (%s) " % run.run_id
return error
# TODO: Do we need to restore config / summary?
# System metrics runtime is usually greater than history
self._resume_state.runtime = max(events_rt, history_rt)
self._resume_state.step = history.get("_step", -1) + 1 if history else 0
self._resume_state.history = resume_status["historyLineCount"]
self._resume_state.events = resume_status["eventsLineCount"]
self._resume_state.output = resume_status["logLineCount"]
self._resume_state.config = config
self._resume_state.summary = summary
self._resume_state.resumed = True
logger.info("configured resuming with: %s" % self._resume_state)
return None | python | wandb/sdk/internal/sender.py | 749 | 834 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,177 | _telemetry_get_framework | def _telemetry_get_framework(self) -> str:
"""Get telemetry data for internal config structure."""
# detect framework by checking what is loaded
imports: telemetry.TelemetryImports
if self._telemetry_obj.HasField("imports_finish"):
imports = self._telemetry_obj.imports_finish
elif self._telemetry_obj.HasField("imports_init"):
imports = self._telemetry_obj.imports_init
else:
return ""
framework = next(
(n for f, n in _framework_priority() if getattr(imports, f, False)), ""
)
return framework | python | wandb/sdk/internal/sender.py | 836 | 849 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,178 | _config_telemetry_update | def _config_telemetry_update(self, config_dict: Dict[str, Any]) -> None:
"""Add legacy telemetry to config object."""
wandb_key = "_wandb"
config_dict.setdefault(wandb_key, dict())
s: str
b: bool
s = self._telemetry_obj.python_version
if s:
config_dict[wandb_key]["python_version"] = s
s = self._telemetry_obj.cli_version
if s:
config_dict[wandb_key]["cli_version"] = s
s = self._telemetry_get_framework()
if s:
config_dict[wandb_key]["framework"] = s
s = self._telemetry_obj.huggingface_version
if s:
config_dict[wandb_key]["huggingface_version"] = s
b = self._telemetry_obj.env.jupyter
config_dict[wandb_key]["is_jupyter_run"] = b
b = self._telemetry_obj.env.kaggle
config_dict[wandb_key]["is_kaggle_kernel"] = b
config_dict[wandb_key]["start_time"] = self._start_time
t: Dict[int, Any] = proto_util.proto_encode_to_dict(self._telemetry_obj)
config_dict[wandb_key]["t"] = t | python | wandb/sdk/internal/sender.py | 851 | 877 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,179 | _config_metric_update | def _config_metric_update(self, config_dict: Dict[str, Any]) -> None:
"""Add default xaxis to config."""
if not self._config_metric_pbdict_list:
return
wandb_key = "_wandb"
config_dict.setdefault(wandb_key, dict())
config_dict[wandb_key]["m"] = self._config_metric_pbdict_list | python | wandb/sdk/internal/sender.py | 879 | 885 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,180 | _config_format | def _config_format(self, config_data: Optional[DictNoValues]) -> DictWithValues:
"""Format dict into value dict with telemetry info."""
config_dict: Dict[str, Any] = config_data.copy() if config_data else dict()
self._config_telemetry_update(config_dict)
self._config_metric_update(config_dict)
config_value_dict: DictWithValues = config_util.dict_add_value_dict(config_dict)
return config_value_dict | python | wandb/sdk/internal/sender.py | 887 | 893 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,181 | _config_save | def _config_save(self, config_value_dict: DictWithValues) -> None:
config_path = os.path.join(self._settings.files_dir, "config.yaml")
config_util.save_config_file_from_dict(config_path, config_value_dict) | python | wandb/sdk/internal/sender.py | 895 | 897 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,182 | _sync_spell | def _sync_spell(self) -> None:
"""Sync this run with spell."""
if not self._run:
return
try:
env = os.environ
self._interface.publish_config(
key=("_wandb", "spell_url"), val=env.get("SPELL_RUN_URL")
)
url = "{}/{}/{}/runs/{}".format(
self._api.app_url, self._run.entity, self._run.project, self._run.run_id
)
requests.put(
env.get("SPELL_API_URL", "https://api.spell.run") + "/wandb_url",
json={"access_token": env.get("WANDB_ACCESS_TOKEN"), "url": url},
timeout=2,
)
except requests.RequestException:
pass
# TODO: do something if sync spell is not successful? | python | wandb/sdk/internal/sender.py | 899 | 918 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,183 | send_run | def send_run(self, record: "Record", file_dir: Optional[str] = None) -> None:
run = record.run
error = None
is_wandb_init = self._run is None
# save start time of a run
self._start_time = run.start_time.ToMicroseconds() / 1e6
# update telemetry
if run.telemetry:
self._telemetry_obj.MergeFrom(run.telemetry)
if self._settings._sync:
self._telemetry_obj.feature.sync = True
# build config dict
config_value_dict: Optional[DictWithValues] = None
if run.config:
config_util.update_from_proto(self._consolidated_config, run.config)
config_value_dict = self._config_format(self._consolidated_config)
self._config_save(config_value_dict)
if is_wandb_init:
# Ensure we have a project to query for status
if run.project == "":
run.project = util.auto_project_name(self._settings.program)
# Only check resume status on `wandb.init`
error = self._maybe_setup_resume(run)
if error is not None:
if record.control.req_resp or record.control.mailbox_slot:
result = proto_util._result_from_record(record)
result.run_result.run.CopyFrom(run)
result.run_result.error.CopyFrom(error)
self._respond_result(result)
else:
logger.error("Got error in async mode: %s", error.message)
return
# Save the resumed config
if self._resume_state.config is not None:
# TODO: should we merge this with resumed config?
config_override = self._consolidated_config
config_dict = self._resume_state.config
config_dict = config_util.dict_strip_value_dict(config_dict)
config_dict.update(config_override)
self._consolidated_config.update(config_dict)
config_value_dict = self._config_format(self._consolidated_config)
self._config_save(config_value_dict)
# handle empty config
# TODO(jhr): consolidate the 4 ways config is built:
# (passed config, empty config, resume config, send_config)
if not config_value_dict:
config_value_dict = self._config_format(None)
self._config_save(config_value_dict)
try:
self._init_run(run, config_value_dict)
except (CommError, UsageError) as e:
logger.error(e, exc_info=True)
if record.control.req_resp or record.control.mailbox_slot:
result = proto_util._result_from_record(record)
result.run_result.run.CopyFrom(run)
error = ProtobufErrorHandler.from_exception(e)
result.run_result.error.CopyFrom(error)
self._respond_result(result)
return
assert self._run # self._run is configured in _init_run()
if record.control.req_resp or record.control.mailbox_slot:
result = proto_util._result_from_record(record)
# TODO: we could do self._interface.publish_defer(resp) to notify
# the handler not to actually perform server updates for this uuid
# because the user process will send a summary update when we resume
result.run_result.run.CopyFrom(self._run)
self._respond_result(result)
# Only spin up our threads on the first run message
if is_wandb_init:
self._start_run_threads(file_dir)
else:
logger.info("updated run: %s", self._run.run_id) | python | wandb/sdk/internal/sender.py | 920 | 1,002 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,184 | _init_run | def _init_run(
self,
run: "RunRecord",
config_dict: Optional[DictWithValues],
) -> None:
# We subtract the previous runs runtime when resuming
start_time = (
run.start_time.ToMicroseconds() / 1e6
) - self._resume_state.runtime
# TODO: we don't check inserted currently, ultimately we should make
# the upsert know the resume state and fail transactionally
server_run, inserted, server_messages = self._api.upsert_run(
name=run.run_id,
entity=run.entity or None,
project=run.project or None,
group=run.run_group or None,
job_type=run.job_type or None,
display_name=run.display_name or None,
notes=run.notes or None,
tags=run.tags[:] or None,
config=config_dict or None,
sweep_name=run.sweep_id or None,
host=run.host or None,
program_path=self._settings.program or None,
repo=run.git.remote_url or None,
commit=run.git.commit or None,
)
# TODO: we don't want to create jobs in sweeps, since the
# executable doesn't appear to be consistent
if hasattr(self._settings, "sweep_id") and self._settings.sweep_id:
self._job_builder.disable = True
self._server_messages = server_messages or []
self._run = run
if self._resume_state.resumed:
self._run.resumed = True
if self._resume_state.wandb_runtime is not None:
self._run.runtime = self._resume_state.wandb_runtime
else:
# If the user is not resuming, and we didn't insert on upsert_run then
# it is likely that we are overwriting the run which we might want to
# prevent in the future. This could be a false signal since an upsert_run
# message which gets retried in the network could also show up as not
# inserted.
if not inserted:
# no need to flush this, it will get updated eventually
self._telemetry_obj.feature.maybe_run_overwrite = True
self._run.starting_step = self._resume_state.step
self._run.start_time.FromMicroseconds(int(start_time * 1e6))
self._run.config.CopyFrom(self._interface._make_config(config_dict))
if self._resume_state.summary is not None:
self._run.summary.CopyFrom(
self._interface._make_summary_from_dict(self._resume_state.summary)
)
storage_id = server_run.get("id")
if storage_id:
self._run.storage_id = storage_id
id = server_run.get("name")
if id:
self._api.set_current_run_id(id)
display_name = server_run.get("displayName")
if display_name:
self._run.display_name = display_name
project = server_run.get("project")
# TODO: remove self._api.set_settings, and make self._project a property?
if project:
project_name = project.get("name")
if project_name:
self._run.project = project_name
self._project = project_name
self._api_settings["project"] = project_name
self._api.set_setting("project", project_name)
entity = project.get("entity")
if entity:
entity_name = entity.get("name")
if entity_name:
self._run.entity = entity_name
self._entity = entity_name
self._api_settings["entity"] = entity_name
self._api.set_setting("entity", entity_name)
sweep_id = server_run.get("sweepName")
if sweep_id:
self._run.sweep_id = sweep_id
if os.getenv("SPELL_RUN_URL"):
self._sync_spell() | python | wandb/sdk/internal/sender.py | 1,004 | 1,088 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,185 | _start_run_threads | def _start_run_threads(self, file_dir: Optional[str] = None) -> None:
assert self._run # self._run is configured by caller
self._fs = file_stream.FileStreamApi(
self._api,
self._run.run_id,
self._run.start_time.ToMicroseconds() / 1e6,
settings=self._api_settings,
)
# Ensure the streaming polices have the proper offsets
self._fs.set_file_policy("wandb-summary.json", file_stream.SummaryFilePolicy())
self._fs.set_file_policy(
"wandb-history.jsonl",
file_stream.JsonlFilePolicy(start_chunk_id=self._resume_state.history),
)
self._fs.set_file_policy(
"wandb-events.jsonl",
file_stream.JsonlFilePolicy(start_chunk_id=self._resume_state.events),
)
self._fs.set_file_policy(
"output.log",
file_stream.CRDedupeFilePolicy(start_chunk_id=self._resume_state.output),
)
# hack to merge run_settings and self._settings object together
# so that fields like entity or project are available to be attached to Sentry events.
run_settings = message_to_dict(self._run)
self._settings = SettingsStatic({**dict(self._settings), **run_settings})
wandb._sentry.configure_scope(settings=self._settings)
self._fs.start()
self._pusher = FilePusher(self._api, self._fs, settings=self._settings)
self._dir_watcher = DirWatcher(
cast(Settings, self._settings), self._pusher, file_dir
)
logger.info(
"run started: %s with start time %s",
self._run.run_id,
self._run.start_time.ToMicroseconds() / 1e6,
) | python | wandb/sdk/internal/sender.py | 1,090 | 1,128 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,186 | _save_history | def _save_history(self, history_dict: Dict[str, Any]) -> None:
if self._fs:
self._fs.push(filenames.HISTORY_FNAME, json.dumps(history_dict)) | python | wandb/sdk/internal/sender.py | 1,130 | 1,132 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,187 | send_history | def send_history(self, record: "Record") -> None:
history = record.history
history_dict = proto_util.dict_from_proto_list(history.item)
self._save_history(history_dict) | python | wandb/sdk/internal/sender.py | 1,134 | 1,137 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,188 | _update_summary_record | def _update_summary_record(self, summary: "SummaryRecord") -> None:
summary_dict = proto_util.dict_from_proto_list(summary.update)
self._cached_summary = summary_dict
self._update_summary() | python | wandb/sdk/internal/sender.py | 1,139 | 1,142 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,189 | send_summary | def send_summary(self, record: "Record") -> None:
self._update_summary_record(record.summary) | python | wandb/sdk/internal/sender.py | 1,144 | 1,145 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,190 | send_request_summary_record | def send_request_summary_record(self, record: "Record") -> None:
self._update_summary_record(record.request.summary_record.summary) | python | wandb/sdk/internal/sender.py | 1,147 | 1,148 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,191 | _update_summary | def _update_summary(self) -> None:
summary_dict = self._cached_summary.copy()
summary_dict.pop("_wandb", None)
if self._metadata_summary:
summary_dict["_wandb"] = self._metadata_summary
json_summary = json.dumps(summary_dict)
if self._fs:
self._fs.push(filenames.SUMMARY_FNAME, json_summary)
# TODO(jhr): we should only write this at the end of the script
summary_path = os.path.join(self._settings.files_dir, filenames.SUMMARY_FNAME)
with open(summary_path, "w") as f:
f.write(json_summary)
self._save_file(interface.GlobStr(filenames.SUMMARY_FNAME)) | python | wandb/sdk/internal/sender.py | 1,150 | 1,162 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,192 | send_stats | def send_stats(self, record: "Record") -> None:
stats = record.stats
if stats.stats_type != wandb_internal_pb2.StatsRecord.StatsType.SYSTEM:
return
if not self._fs:
return
if not self._run:
return
now_us = stats.timestamp.ToMicroseconds()
start_us = self._run.start_time.ToMicroseconds()
d = dict()
for item in stats.item:
d[item.key] = json.loads(item.value_json)
row: Dict[str, Any] = dict(system=d)
self._flatten(row)
row["_wandb"] = True
row["_timestamp"] = now_us / 1e6
row["_runtime"] = (now_us - start_us) / 1e6
self._fs.push(filenames.EVENTS_FNAME, json.dumps(row))
# TODO(jhr): check fs.push results? | python | wandb/sdk/internal/sender.py | 1,164 | 1,183 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,193 | _output_raw_finish | def _output_raw_finish(self) -> None:
for stream, output_raw in self._output_raw_streams.items():
output_raw._stopped.set()
# shut down threads
output_raw._writer_thr.join(timeout=5)
if output_raw._writer_thr.is_alive():
logger.info("processing output...")
output_raw._writer_thr.join()
output_raw._reader_thr.join()
# flush output buffers and files
self._output_raw_flush(stream)
self._output_raw_streams = {}
if self._output_raw_file:
self._output_raw_file.close()
self._output_raw_file = None | python | wandb/sdk/internal/sender.py | 1,185 | 1,201 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,194 | _output_raw_writer_thread | def _output_raw_writer_thread(self, stream: "StreamLiterals") -> None:
while True:
output_raw = self._output_raw_streams[stream]
if output_raw._queue.empty():
if output_raw._stopped.is_set():
return
time.sleep(0.5)
continue
data = []
while not output_raw._queue.empty():
data.append(output_raw._queue.get())
if output_raw._stopped.is_set() and sum(map(len, data)) > 100000:
logger.warning("Terminal output too large. Logging without processing.")
self._output_raw_flush(stream)
for line in data:
self._output_raw_flush(stream, line)
# TODO: lets mark that this happened in telemetry
return
try:
output_raw._emulator.write("".join(data))
except Exception as e:
logger.warning(f"problem writing to output_raw emulator: {e}") | python | wandb/sdk/internal/sender.py | 1,203 | 1,224 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,195 | _output_raw_reader_thread | def _output_raw_reader_thread(self, stream: "StreamLiterals") -> None:
output_raw = self._output_raw_streams[stream]
while not (output_raw._stopped.is_set() and output_raw._queue.empty()):
self._output_raw_flush(stream)
time.sleep(_OUTPUT_MIN_CALLBACK_INTERVAL) | python | wandb/sdk/internal/sender.py | 1,226 | 1,230 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,196 | _output_raw_flush | def _output_raw_flush(
self, stream: "StreamLiterals", data: Optional[str] = None
) -> None:
if data is None:
output_raw = self._output_raw_streams[stream]
try:
data = output_raw._emulator.read()
except Exception as e:
logger.warning(f"problem reading from output_raw emulator: {e}")
if data:
self._send_output_line(stream, data)
if self._output_raw_file:
self._output_raw_file.write(data.encode("utf-8")) | python | wandb/sdk/internal/sender.py | 1,232 | 1,244 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,197 | send_output | def send_output(self, record: "Record") -> None:
if not self._fs:
return
out = record.output
stream: "StreamLiterals" = "stdout"
if out.output_type == wandb_internal_pb2.OutputRecord.OutputType.STDERR:
stream = "stderr"
line = out.line
self._send_output_line(stream, line) | python | wandb/sdk/internal/sender.py | 1,246 | 1,254 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,198 | send_output_raw | def send_output_raw(self, record: "Record") -> None:
if not self._fs:
return
out = record.output_raw
stream: "StreamLiterals" = "stdout"
if out.output_type == wandb_internal_pb2.OutputRawRecord.OutputType.STDERR:
stream = "stderr"
line = out.line
output_raw = self._output_raw_streams.get(stream)
if not output_raw:
output_raw = _OutputRawStream(stream=stream, sm=self)
self._output_raw_streams[stream] = output_raw
# open the console output file shared between both streams
if not self._output_raw_file:
output_log_path = os.path.join(
self._settings.files_dir, filenames.OUTPUT_FNAME
)
output_raw_file = None
try:
output_raw_file = filesystem.CRDedupedFile(
open(output_log_path, "wb")
)
except OSError as e:
logger.warning(f"could not open output_raw_file: {e}")
if output_raw_file:
self._output_raw_file = output_raw_file
output_raw.start()
output_raw._queue.put(line) | python | wandb/sdk/internal/sender.py | 1,256 | 1,286 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,199 | _send_output_line | def _send_output_line(self, stream: "StreamLiterals", line: str) -> None:
"""Combined writer for raw and non raw output lines.
This is combined because they are both post emulator.
"""
prepend = ""
if stream == "stderr":
prepend = "ERROR "
if not line.endswith("\n"):
self._partial_output.setdefault(stream, "")
if line.startswith("\r"):
# TODO: maybe we shouldnt just drop this, what if there was some \ns in the partial
# that should probably be the check instead of not line.endswith(\n")
# logger.info(f"Dropping data {self._partial_output[stream]}")
self._partial_output[stream] = ""
self._partial_output[stream] += line
# TODO(jhr): how do we make sure this gets flushed?
# we might need this for other stuff like telemetry
else:
# TODO(jhr): use time from timestamp proto
# TODO(jhr): do we need to make sure we write full lines?
# seems to be some issues with line breaks
cur_time = time.time()
timestamp = datetime.utcfromtimestamp(cur_time).isoformat() + " "
prev_str = self._partial_output.get(stream, "")
line = f"{prepend}{timestamp}{prev_str}{line}"
if self._fs:
self._fs.push(filenames.OUTPUT_FNAME, line)
self._partial_output[stream] = "" | python | wandb/sdk/internal/sender.py | 1,288 | 1,316 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
4,200 | _update_config | def _update_config(self) -> None:
self._config_needs_debounce = True | python | wandb/sdk/internal/sender.py | 1,318 | 1,319 | {
"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.