id
int64
1
6.07M
name
stringlengths
1
295
code
stringlengths
12
426k
language
stringclasses
1 value
source_file
stringlengths
5
202
start_line
int64
1
158k
end_line
int64
1
158k
repo
dict
3,901
fetch_project_diff
def fetch_project_diff( entity: str, project: str, run_name: str, api: Api ) -> Optional[str]: """Fetches project diff from wandb servers.""" _logger.info("Searching for diff.patch") patch = None try: (_, _, patch, _) = api.run_config(project, run_name, entity) except CommError: pass return patch
python
wandb/sdk/launch/utils.py
419
429
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,902
apply_patch
def apply_patch(patch_string: str, dst_dir: str) -> None: """Applies a patch file to a directory.""" _logger.info("Applying diff.patch") with open(os.path.join(dst_dir, "diff.patch"), "w") as fp: fp.write(patch_string) try: subprocess.check_call( [ "patch", "-s", f"--directory={dst_dir}", "-p1", "-i", "diff.patch", ] ) except subprocess.CalledProcessError: raise wandb.Error("Failed to apply diff.patch associated with run.")
python
wandb/sdk/launch/utils.py
432
449
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,903
_make_refspec_from_version
def _make_refspec_from_version(version: Optional[str]) -> List[str]: """Create a refspec that checks for the existence of origin/main and the version.""" if version: return [f"+{version}"] return [ "+refs/heads/main*:refs/remotes/origin/main*", "+refs/heads/master*:refs/remotes/origin/master*", ]
python
wandb/sdk/launch/utils.py
452
460
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,904
_fetch_git_repo
def _fetch_git_repo(dst_dir: str, uri: str, version: Optional[str]) -> str: """Clones the git repo at ``uri`` into ``dst_dir``. checks out commit ``version`` (or defaults to the head commit of the repository's master branch if version is unspecified). Assumes authentication parameters are specified by the environment, e.g. by a Git credential helper. """ # We defer importing git until the last moment, because the import requires that the git # executable is available on the PATH, so we only want to fail if we actually need it. import git # type: ignore _logger.info("Fetching git repo") repo = git.Repo.init(dst_dir) origin = repo.create_remote("origin", uri) refspec = _make_refspec_from_version(version) origin.fetch(refspec=refspec, depth=1) if version is not None: try: repo.git.checkout(version) except git.exc.GitCommandError as e: raise LaunchError( f"Unable to checkout version '{version}' of git repo {uri}" "- please ensure that the version exists in the repo. " f"Error: {e}" ) from e else: if getattr(repo, "references", None) is not None: branches = [ref.name for ref in repo.references] else: branches = [] # Check if main is in origin, else set branch to master if "main" in branches or "origin/main" in branches: version = "main" else: version = "master" try: repo.create_head(version, origin.refs[version]) repo.heads[version].checkout() wandb.termlog( f"{LOG_PREFIX}No git branch passed, defaulted to branch: {version}" ) except (AttributeError, IndexError) as e: raise LaunchError( f"Unable to checkout default version '{version}' of git repo {uri} " "- to specify a git version use: --git-version \n" f"Error: {e}" ) from e repo.submodule_update(init=True, recursive=True) return version
python
wandb/sdk/launch/utils.py
463
514
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,905
merge_parameters
def merge_parameters( higher_priority_params: Dict[str, Any], lower_priority_params: Dict[str, Any] ) -> Dict[str, Any]: """Merge the contents of two dicts, keeping values from higher_priority_params if there are conflicts.""" return {**lower_priority_params, **higher_priority_params}
python
wandb/sdk/launch/utils.py
517
521
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,906
convert_jupyter_notebook_to_script
def convert_jupyter_notebook_to_script(fname: str, project_dir: str) -> str: nbconvert = wandb.util.get_module( "nbconvert", "nbformat and nbconvert are required to use launch with notebooks" ) nbformat = wandb.util.get_module( "nbformat", "nbformat and nbconvert are required to use launch with notebooks" ) _logger.info("Converting notebook to script") new_name = fname.rstrip(".ipynb") + ".py" with open(os.path.join(project_dir, fname)) as fh: nb = nbformat.reads(fh.read(), nbformat.NO_CONVERT) exporter = nbconvert.PythonExporter() source, meta = exporter.from_notebook_node(nb) with open(os.path.join(project_dir, new_name), "w+") as fh: fh.writelines(source) return new_name
python
wandb/sdk/launch/utils.py
524
542
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,907
check_and_download_code_artifacts
def check_and_download_code_artifacts( entity: str, project: str, run_name: str, internal_api: Api, project_dir: str ) -> Optional["PublicArtifact"]: _logger.info("Checking for code artifacts") public_api = wandb.PublicApi( overrides={"base_url": internal_api.settings("base_url")} ) run = public_api.run(f"{entity}/{project}/{run_name}") run_artifacts = run.logged_artifacts() for artifact in run_artifacts: if hasattr(artifact, "type") and artifact.type == "code": artifact.download(project_dir) return artifact # type: ignore return None
python
wandb/sdk/launch/utils.py
545
561
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,908
to_camel_case
def to_camel_case(maybe_snake_str: str) -> str: if "_" not in maybe_snake_str: return maybe_snake_str components = maybe_snake_str.split("_") return "".join(x.title() if x else "_" for x in components)
python
wandb/sdk/launch/utils.py
564
568
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,909
run_shell
def run_shell(args: List[str]) -> Tuple[str, str]: out = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return out.stdout.decode("utf-8").strip(), out.stderr.decode("utf-8").strip()
python
wandb/sdk/launch/utils.py
571
573
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,910
validate_build_and_registry_configs
def validate_build_and_registry_configs( build_config: Dict[str, Any], registry_config: Dict[str, Any] ) -> None: build_config_credentials = build_config.get("credentials", {}) registry_config_credentials = registry_config.get("credentials", {}) if ( build_config_credentials and registry_config_credentials and build_config_credentials != registry_config_credentials ): raise LaunchError("registry and build config credential mismatch")
python
wandb/sdk/launch/utils.py
576
586
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,911
get_kube_context_and_api_client
def get_kube_context_and_api_client( kubernetes: Any, resource_args: Dict[str, Any], ) -> Tuple[Any, Any]: config_file = resource_args.get("config_file", None) context = None if config_file is not None or os.path.exists(os.path.expanduser("~/.kube/config")): # context only exist in the non-incluster case all_contexts, active_context = kubernetes.config.list_kube_config_contexts( config_file ) context = None if resource_args.get("context"): context_name = resource_args["context"] for c in all_contexts: if c["name"] == context_name: context = c break raise LaunchError(f"Specified context {context_name} was not found.") else: context = active_context # TODO: We should not really be performing this check if the user is not # using EKS but I don't see an obvious way to make an eks specific code path # right here. util.get_module( "awscli", "awscli is required to load a kubernetes context " "from eks. Please run `pip install wandb[launch]` to install it.", ) kubernetes.config.load_kube_config(config_file, context["name"]) api_client = kubernetes.config.new_client_from_config( config_file, context=context["name"] ) return context, api_client else: kubernetes.config.load_incluster_config() api_client = kubernetes.client.api_client.ApiClient() return context, api_client
python
wandb/sdk/launch/utils.py
589
627
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,912
resolve_build_and_registry_config
def resolve_build_and_registry_config( default_launch_config: Optional[Dict[str, Any]], build_config: Optional[Dict[str, Any]], registry_config: Optional[Dict[str, Any]], ) -> Tuple[Dict[str, Any], Dict[str, Any]]: resolved_build_config: Dict[str, Any] = {} if build_config is None and default_launch_config is not None: resolved_build_config = default_launch_config.get("builder", {}) elif build_config is not None: resolved_build_config = build_config resolved_registry_config: Dict[str, Any] = {} if registry_config is None and default_launch_config is not None: resolved_registry_config = default_launch_config.get("registry", {}) elif registry_config is not None: resolved_registry_config = registry_config validate_build_and_registry_configs(resolved_build_config, resolved_registry_config) return resolved_build_config, resolved_registry_config
python
wandb/sdk/launch/utils.py
630
646
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,913
check_logged_in
def check_logged_in(api: Api) -> bool: """Check if a user is logged in. Raises an error if the viewer doesn't load (likely a broken API key). Expected time cost is 0.1-0.2 seconds. """ res = api.api.viewer() if not res: raise LaunchError( "Could not connect with current API-key. " "Please relogin using `wandb login --relogin`" " and try again (see `wandb login --help` for more options)" ) return True
python
wandb/sdk/launch/utils.py
649
663
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,914
make_name_dns_safe
def make_name_dns_safe(name: str) -> str: resp = name.replace("_", "-").lower() resp = re.sub(r"[^a-z\.\-]", "", resp) # Actual length limit is 253, but we want to leave room for the generated suffix resp = resp[:200] return resp
python
wandb/sdk/launch/utils.py
666
671
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,915
warn_failed_packages_from_build_logs
def warn_failed_packages_from_build_logs(log: str, image_uri: str) -> None: match = FAILED_PACKAGES_REGEX.search(log) if match: wandb.termwarn( f"Failed to install the following packages: {match.group(1)} for image: {image_uri}. Will attempt to launch image without them." )
python
wandb/sdk/launch/utils.py
674
679
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,916
docker_image_exists
def docker_image_exists(docker_image: str, should_raise: bool = False) -> bool: """Check if a specific image is already available. Optionally raises an exception if the image is not found. """ _logger.info("Checking if base image exists...") try: docker.run(["docker", "image", "inspect", docker_image]) return True except (docker.DockerError, ValueError) as e: if should_raise: raise e _logger.info("Base image not found. Generating new base image") return False
python
wandb/sdk/launch/utils.py
682
695
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,917
pull_docker_image
def pull_docker_image(docker_image: str) -> None: """Pull the requested docker image.""" if docker_image_exists(docker_image): # don't pull images if they exist already, eg if they are local images return try: docker.run(["docker", "pull", docker_image]) except docker.DockerError as e: raise LaunchError(f"Docker server returned error: {e}")
python
wandb/sdk/launch/utils.py
698
706
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,918
environment_from_config
def environment_from_config(config: Optional[Dict[str, Any]]) -> AbstractEnvironment: """Create an environment from a config. This helper function is used to create an environment from a config. The config should have a "type" key that specifies the type of environment to create. The remaining keys are passed to the environment's from_config method. If the config is None or empty, a LocalEnvironment is returned. Arguments: config (Dict[str, Any]): The config. Returns: Environment: The environment constructed. """ if not config: from .environment.local_environment import LocalEnvironment return LocalEnvironment() # This is the default, dummy environment. env_type = config.get("type") if not env_type: raise LaunchError( "Could not create environment from config. Environment type not specified!" ) if env_type == "aws": from .environment.aws_environment import AwsEnvironment return AwsEnvironment.from_config(config) if env_type == "gcp": from .environment.gcp_environment import GcpEnvironment return GcpEnvironment.from_config(config) raise LaunchError( f"Could not create environment from config. Invalid type: {env_type}" )
python
wandb/sdk/launch/loader.py
22
55
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,919
registry_from_config
def registry_from_config( config: Optional[Dict[str, Any]], environment: AbstractEnvironment ) -> AbstractRegistry: """Create a registry from a config. This helper function is used to create a registry from a config. The config should have a "type" key that specifies the type of registry to create. The remaining keys are passed to the registry's from_config method. If the config is None or empty, a LocalRegistry is returned. Arguments: config (Dict[str, Any]): The registry config. environment (Environment): The environment of the registry. Returns: The registry if config is not None, otherwise None. Raises: LaunchError: If the registry is not configured correctly. """ if not config: from .registry.local_registry import LocalRegistry return LocalRegistry() # This is the default, dummy registry. registry_type = config.get("type") if registry_type is None: from .registry.local_registry import LocalRegistry return LocalRegistry() # This is the default, dummy registry. if registry_type == "ecr": from .environment.aws_environment import AwsEnvironment if not isinstance(environment, AwsEnvironment): raise LaunchError( "Could not create ECR registry. " "Environment must be an instance of AWSEnvironment." ) from .registry.elastic_container_registry import ElasticContainerRegistry return ElasticContainerRegistry.from_config(config, environment) if registry_type == "gcr": from .environment.gcp_environment import GcpEnvironment if not isinstance(environment, GcpEnvironment): raise LaunchError( "Could not create GCR registry. " "Environment must be an instance of GCPEnvironment." ) from .registry.google_artifact_registry import GoogleArtifactRegistry return GoogleArtifactRegistry.from_config(config, environment) raise LaunchError( f"Could not create registry from config. Invalid registry type: {registry_type}" )
python
wandb/sdk/launch/loader.py
58
111
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,920
builder_from_config
def builder_from_config( config: Optional[Dict[str, Any]], environment: AbstractEnvironment, registry: AbstractRegistry, ) -> AbstractBuilder: """Create a builder from a config. This helper function is used to create a builder from a config. The config should have a "type" key that specifies the type of builder to import and create. The remaining keys are passed to the builder's from_config method. If the config is None or empty, a DockerBuilder is returned. Arguments: config (Dict[str, Any]): The builder config. registry (Registry): The registry of the builder. Returns: The builder. Raises: LaunchError: If the builder is not configured correctly. """ if not config: from .builder.docker_builder import DockerBuilder return DockerBuilder.from_config( {}, environment, registry ) # This is the default builder. builder_type = config.get("type") if builder_type is None: raise LaunchError( "Could not create builder from config. Builder type not specified" ) if builder_type == "docker": from .builder.docker_builder import DockerBuilder return DockerBuilder.from_config(config, environment, registry) if builder_type == "kaniko": if isinstance(registry, LocalRegistry): raise LaunchError( "Could not create Kaniko builder. " "Registry must be a remote registry." ) from .builder.kaniko_builder import KanikoBuilder return KanikoBuilder.from_config(config, environment, registry) if builder_type == "noop": from .builder.noop import NoOpBuilder return NoOpBuilder.from_config(config, environment, registry) raise LaunchError( f"Could not create builder from config. Invalid builder type: {builder_type}" )
python
wandb/sdk/launch/loader.py
114
167
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,921
runner_from_config
def runner_from_config( runner_name: str, api: Api, runner_config: Dict[str, Any], environment: AbstractEnvironment, ) -> AbstractRunner: """Create a runner from a config. This helper function is used to create a runner from a config. The config should have a "type" key that specifies the type of runner to import and create. The remaining keys are passed to the runner's from_config method. If the config is None or empty, a LocalContainerRunner is returned. Arguments: runner_name (str): The name of the backend. api (Api): The API. runner_config (Dict[str, Any]): The backend config. Returns: The runner. Raises: LaunchError: If the runner is not configured correctly. """ if not runner_name or runner_name in ["local-container", "local"]: from .runner.local_container import LocalContainerRunner return LocalContainerRunner(api, runner_config, environment) if runner_name == "local-process": from .runner.local_process import LocalProcessRunner return LocalProcessRunner(api, runner_config) if runner_name == "sagemaker": from .environment.aws_environment import AwsEnvironment if not isinstance(environment, AwsEnvironment): raise LaunchError( "Could not create Sagemaker runner. " "Environment must be an instance of AwsEnvironment." ) from .runner.sagemaker_runner import SageMakerRunner return SageMakerRunner(api, runner_config, environment) if runner_name in ["vertex", "gcp-vertex"]: from .environment.gcp_environment import GcpEnvironment if not isinstance(environment, GcpEnvironment): raise LaunchError( "Could not create Vertex runner. " "Environment must be an instance of GcpEnvironment." ) from .runner.vertex_runner import VertexRunner return VertexRunner(api, runner_config, environment) if runner_name == "kubernetes": from .runner.kubernetes_runner import KubernetesRunner return KubernetesRunner(api, runner_config, environment) raise LaunchError( f"Could not create runner from config. Invalid runner name: {runner_name}" )
python
wandb/sdk/launch/loader.py
170
230
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,922
_parse_netloc
def _parse_netloc(netloc: str) -> Tuple[Optional[str], Optional[str], str]: """Parse netloc into username, password, and host. github.com => None, None, "@github.com" username@github.com => "username", None, "github.com" username:password@github.com => "username", "password", "github.com" """ parts = netloc.split("@", 1) if len(parts) == 1: return None, None, parts[0] auth, host = parts parts = auth.split(":", 1) if len(parts) == 1: return parts[0], None, host return parts[0], parts[1], host
python
wandb/sdk/launch/github_reference.py
25
39
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,923
update_ref
def update_ref(self, ref: Optional[str]) -> None: if ref: # We no longer know what this refers to self.ref_type = None self.ref = ref
python
wandb/sdk/launch/github_reference.py
65
69
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,924
url_host
def url_host(self) -> str: assert self.host auth = self.username or "" if self.password: auth += f":{self.password}" if auth: auth += "@" return f"{PREFIX_HTTPS}{auth}{self.host}"
python
wandb/sdk/launch/github_reference.py
71
78
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,925
url_organization
def url_organization(self) -> str: assert self.organization return f"{self.url_host()}/{self.organization}"
python
wandb/sdk/launch/github_reference.py
80
82
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,926
url_repo
def url_repo(self) -> str: assert self.repo return f"{self.url_organization()}/{self.repo}"
python
wandb/sdk/launch/github_reference.py
84
86
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,927
repo_ssh
def repo_ssh(self) -> str: return f"{PREFIX_SSH}{self.host}:{self.organization}/{self.repo}{SUFFIX_GIT}"
python
wandb/sdk/launch/github_reference.py
88
89
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,928
url
def url(self) -> str: url = self.url_repo() if self.view: url += f"/{self.view}" if self.ref: url += f"/{self.ref}" if self.directory: url += f"/{self.directory}" if self.file: url += f"/{self.file}" elif self.path: url += f"/{self.path}" return url
python
wandb/sdk/launch/github_reference.py
91
103
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,929
parse
def parse(uri: str) -> Optional["GitHubReference"]: """Attempt to parse a string as a GitHub URL.""" # Special case: git@github.com:wandb/wandb.git ref = GitHubReference() if uri.startswith(PREFIX_SSH): index = uri.find(":", len(PREFIX_SSH)) if index > 0: ref.host = uri[len(PREFIX_SSH) : index] parts = uri[index + 1 :].split("/", 1) if len(parts) < 2 or not parts[1].endswith(SUFFIX_GIT): return None ref.organization = parts[0] ref.repo = parts[1][: -len(SUFFIX_GIT)] return ref else: # Could not parse host name return None parsed = urlparse(uri) if parsed.scheme != "https": return None ref.username, ref.password, ref.host = _parse_netloc(parsed.netloc) parts = parsed.path.split("/") if len(parts) > 1: if parts[1] == "orgs" and len(parts) > 2: ref.organization = parts[2] else: ref.organization = parts[1] if len(parts) > 2: repo = parts[2] if repo.endswith(SUFFIX_GIT): repo = repo[: -len(SUFFIX_GIT)] ref.repo = repo ref.view = parts[3] if len(parts) > 3 else None ref.path = "/".join(parts[4:]) return ref
python
wandb/sdk/launch/github_reference.py
106
142
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,930
fetch
def fetch(self, dst_dir: str) -> None: """Fetch the repo into dst_dir and refine githubref based on what we learn.""" # We defer importing git until the last moment, because the import requires that the git # executable is available on the PATH, so we only want to fail if we actually need it. import git # type: ignore repo = git.Repo.init(dst_dir) origin = repo.create_remote("origin", self.url_repo()) # We fetch the origin so that we have branch and tag references origin.fetch(depth=1) # Guess if this is a commit commit = None first_segment = self.ref or (self.path.split("/")[0] if self.path else "") if GIT_COMMIT_REGEX.fullmatch(first_segment): try: commit = repo.commit(first_segment) self.ref_type = ReferenceType.COMMIT self.ref = first_segment if self.path: self.path = self.path[len(first_segment) + 1 :] head = repo.create_head(first_segment, commit) head.checkout() except ValueError: # Apparently it just looked like a commit pass # If not a commit, check to see if path indicates a branch name branch = None check_branch = self.ref or self.path if not commit and check_branch: for ref in repo.references: if hasattr(ref, "tag"): # Skip tag references. # Using hasattr instead of isinstance because it works better with mocks. continue refname = ref.name if refname.startswith("origin/"): # Trim off "origin/" refname = refname[7:] if check_branch.startswith(refname): self.ref_type = ReferenceType.BRANCH self.ref = branch = refname if self.path: self.path = self.path[len(refname) + 1 :] head = repo.create_head(branch, origin.refs[branch]) head.checkout() break # Must be on default branch. Try to figure out what that is. # TODO: Is there a better way to do this? default_branch = None if not commit and not branch: for ref in repo.references: if hasattr(ref, "tag"): # Skip tag references continue refname = ref.name if refname.startswith("origin/"): # Trim off "origin/" refname = refname[7:] if refname == "main": default_branch = "main" break if refname == "master": default_branch = "master" # Keep looking in case we also have a main, which we let take precedence # (While the references appear to be sorted, not clear if that's guaranteed.) if not default_branch: raise LaunchError( f"Unable to determine branch or commit to checkout from {self.url()}" ) self.default_branch = default_branch head = repo.create_head(default_branch, origin.refs[default_branch]) head.checkout() # Now that we've checked something out, try to extract directory and file from what remains self._update_path(dst_dir)
python
wandb/sdk/launch/github_reference.py
144
219
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,931
_update_path
def _update_path(self, dst_dir: str) -> None: """Set directory and file fields based on what remains in path.""" if not self.path: return path = Path(dst_dir, self.path) if path.is_file(): self.directory = str(path.parent.absolute()) self.file = path.name self.path = None elif path.is_dir(): self.directory = self.path self.path = None
python
wandb/sdk/launch/github_reference.py
221
232
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,932
__init__
def __init__(self, state: "State" = "unknown", data=None): # type: ignore self.state = state self.data = data or {}
python
wandb/sdk/launch/runner/abstract.py
32
34
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,933
__repr__
def __repr__(self) -> "State": return self.state
python
wandb/sdk/launch/runner/abstract.py
36
37
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,934
__init__
def __init__(self) -> None: self._status = Status()
python
wandb/sdk/launch/runner/abstract.py
52
53
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,935
status
def status(self) -> Status: return self._status
python
wandb/sdk/launch/runner/abstract.py
56
57
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,936
_run_cmd
def _run_cmd( self, cmd: List[str], output_only: Optional[bool] = False ) -> Optional[Union["subprocess.Popen[bytes]", bytes]]: """Run the command and returns a popen object or the stdout of the command. Arguments: cmd: The command to run output_only: If true just return the stdout bytes """ try: env = os.environ popen = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE) if output_only: popen.wait() if popen.stdout is not None: return popen.stdout.read() return popen except subprocess.CalledProcessError as e: wandb.termerror(f"Command failed: {e}") return None
python
wandb/sdk/launch/runner/abstract.py
59
78
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,937
wait
def wait(self) -> bool: """Wait for the run to finish, returning True if the run succeeded and false otherwise. Note that in some cases, we may wait until the remote job completes rather than until the W&B run completes. """ pass
python
wandb/sdk/launch/runner/abstract.py
81
86
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,938
get_status
def get_status(self) -> Status: """Get status of the run.""" pass
python
wandb/sdk/launch/runner/abstract.py
89
91
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,939
cancel
def cancel(self) -> None: """Cancel the run (interrupts the command subprocess, cancels the run, etc). Cancels the run and waits for it to terminate. The W&B run status may not be set correctly upon run cancellation. """ pass
python
wandb/sdk/launch/runner/abstract.py
94
100
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,940
id
def id(self) -> str: pass
python
wandb/sdk/launch/runner/abstract.py
104
105
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,941
__init__
def __init__(self, api: Api, backend_config: Dict[str, Any]) -> None: self._settings = Settings() self._api = api self.backend_config = backend_config self._cwd = os.getcwd() self._namespace = runid.generate_id()
python
wandb/sdk/launch/runner/abstract.py
116
121
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,942
find_executable
def find_executable( self, cmd: str ) -> Any: # should return a string, but mypy doesn't trust find_executable """Cross platform utility for checking if a program is available.""" return find_executable(cmd)
python
wandb/sdk/launch/runner/abstract.py
123
127
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,943
api_key
def api_key(self) -> Any: return self._api.api_key
python
wandb/sdk/launch/runner/abstract.py
130
131
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,944
verify
def verify(self) -> bool: """This is called on first boot to verify the needed commands, and permissions are available. For now just call `wandb.termerror` and `sys.exit(1)` """ if self._api.api_key is None: wandb.termerror( "Couldn't find W&B api key, run wandb login or set WANDB_API_KEY" ) sys.exit(1) return True
python
wandb/sdk/launch/runner/abstract.py
133
143
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,945
run
def run( self, launch_project: LaunchProject, builder: AbstractBuilder, ) -> Optional[AbstractRun]: """Submit an LaunchProject to be run. Returns a SubmittedRun object to track the execution Arguments: launch_project: Object of _project_spec.LaunchProject class representing a wandb launch project Returns: A :py:class:`wandb.sdk.launch.runners.SubmittedRun`. This function is expected to run the project asynchronously, i.e. it should trigger project execution and then immediately return a `SubmittedRun` to track execution status. """ pass
python
wandb/sdk/launch/runner/abstract.py
146
162
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,946
__init__
def __init__(self, training_job_name: str, client: "boto3.Client") -> None: super().__init__() self.client = client self.training_job_name = training_job_name self._status = Status("running")
python
wandb/sdk/launch/runner/sagemaker_runner.py
26
30
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,947
id
def id(self) -> str: return f"sagemaker-{self.training_job_name}"
python
wandb/sdk/launch/runner/sagemaker_runner.py
33
34
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,948
wait
def wait(self) -> bool: while True: status_state = self.get_status().state wandb.termlog( f"{LOG_PREFIX}Training job {self.training_job_name} status: {status_state}" ) if status_state in ["stopped", "failed", "finished"]: break time.sleep(5) return status_state == "finished"
python
wandb/sdk/launch/runner/sagemaker_runner.py
36
45
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,949
cancel
def cancel(self) -> None: # Interrupt child process if it hasn't already exited status = self.get_status() if status.state == "running": self.client.stop_training_job(TrainingJobName=self.training_job_name) self.wait()
python
wandb/sdk/launch/runner/sagemaker_runner.py
47
52
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,950
get_status
def get_status(self) -> Status: job_status = self.client.describe_training_job( TrainingJobName=self.training_job_name )["TrainingJobStatus"] if job_status == "Completed" or job_status == "Stopped": self._status = Status("finished") elif job_status == "Failed": self._status = Status("failed") elif job_status == "Stopping": self._status = Status("stopping") elif job_status == "InProgress": self._status = Status("running") return self._status
python
wandb/sdk/launch/runner/sagemaker_runner.py
54
66
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,951
__init__
def __init__( self, api: Api, backend_config: Dict[str, Any], environment: AwsEnvironment ) -> None: """Initialize the SagemakerRunner. Arguments: api (Api): The API instance. backend_config (Dict[str, Any]): The backend configuration. environment (AwsEnvironment): The AWS environment. Raises: LaunchError: If the runner cannot be initialized. """ super().__init__(api, backend_config) self.environment = environment
python
wandb/sdk/launch/runner/sagemaker_runner.py
72
86
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,952
run
def run( self, launch_project: LaunchProject, builder: Optional[AbstractBuilder], ) -> Optional[AbstractRun]: """Run a project on Amazon Sagemaker. Arguments: launch_project (LaunchProject): The project to run. builder (AbstractBuilder): The builder to use. Returns: Optional[AbstractRun]: The run instance. Raises: LaunchError: If the launch is unsuccessful. """ _logger.info("using AWSSagemakerRunner") given_sagemaker_args = launch_project.resource_args.get("sagemaker") if given_sagemaker_args is None: raise LaunchError( "No sagemaker args specified. Specify sagemaker args in resource_args" ) default_output_path = self.backend_config.get("runner", {}).get( "s3_output_path" ) if default_output_path is not None and not default_output_path.startswith( "s3://" ): default_output_path = f"s3://{default_output_path}" session = self.environment.get_session() client = session.client("sts") caller_id = client.get_caller_identity() account_id = caller_id["Account"] _logger.info(f"Using account ID {account_id}") role_arn = get_role_arn(given_sagemaker_args, self.backend_config, account_id) entry_point = launch_project.get_single_entry_point() # Create a sagemaker client to launch the job. sagemaker_client = session.client("sagemaker") # if the user provided the image they want to use, use that, but warn it won't have swappable artifacts if ( given_sagemaker_args.get("AlgorithmSpecification", {}).get("TrainingImage") is not None ): sagemaker_args = build_sagemaker_args( launch_project, self._api, role_arn, given_sagemaker_args.get("AlgorithmSpecification", {}).get( "TrainingImage" ), default_output_path, ) _logger.info( f"Launching sagemaker job on user supplied image with args: {sagemaker_args}" ) run = launch_sagemaker_job(launch_project, sagemaker_args, sagemaker_client) if self.backend_config[PROJECT_SYNCHRONOUS]: run.wait() return run if launch_project.docker_image: image = launch_project.docker_image else: assert entry_point is not None assert builder is not None # build our own image _logger.info("Building docker image...") image = builder.build_image( launch_project, entry_point, ) _logger.info(f"Docker image built with uri {image}") _logger.info("Connecting to sagemaker client") command_args = get_entry_point_command( entry_point, launch_project.override_args ) if command_args: command_str = " ".join(command_args) wandb.termlog( f"{LOG_PREFIX}Launching run on sagemaker with entrypoint: {command_str}" ) else: wandb.termlog( f"{LOG_PREFIX}Launching run on sagemaker with user-provided entrypoint in image" ) sagemaker_args = build_sagemaker_args( launch_project, self._api, role_arn, image, default_output_path ) _logger.info(f"Launching sagemaker job with args: {sagemaker_args}") run = launch_sagemaker_job(launch_project, sagemaker_args, sagemaker_client) if self.backend_config[PROJECT_SYNCHRONOUS]: run.wait() return run
python
wandb/sdk/launch/runner/sagemaker_runner.py
88
187
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,953
merge_aws_tag_with_algorithm_specification
def merge_aws_tag_with_algorithm_specification( algorithm_specification: Optional[Dict[str, Any]], aws_tag: Optional[str] ) -> Dict[str, Any]: """Create an AWS AlgorithmSpecification. AWS Sagemaker algorithms require a training image and an input mode. If the user does not specify the specification themselves, define the spec minimally using these two fields. Otherwise, if they specify the AlgorithmSpecification set the training image if it is not set. """ if algorithm_specification is None: return { "TrainingImage": aws_tag, "TrainingInputMode": "File", } elif algorithm_specification.get("TrainingImage") is None: algorithm_specification["TrainingImage"] = aws_tag if algorithm_specification["TrainingImage"] is None: raise LaunchError("Failed determine tag for training image") return algorithm_specification
python
wandb/sdk/launch/runner/sagemaker_runner.py
190
209
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,954
build_sagemaker_args
def build_sagemaker_args( launch_project: LaunchProject, api: Api, role_arn: str, aws_tag: Optional[str] = None, default_output_path: Optional[str] = None, ) -> Dict[str, Any]: sagemaker_args: Dict[str, Any] = {} given_sagemaker_args: Optional[Dict[str, Any]] = launch_project.resource_args.get( "sagemaker" ) if given_sagemaker_args is None: raise LaunchError( "No sagemaker args specified. Specify sagemaker args in resource_args" ) if ( given_sagemaker_args.get("OutputDataConfig") is None and default_output_path is not None ): sagemaker_args["OutputDataConfig"] = {"S3OutputPath": default_output_path} else: sagemaker_args["OutputDataConfig"] = given_sagemaker_args.get( "OutputDataConfig" ) if sagemaker_args.get("OutputDataConfig") is None: raise LaunchError( "Sagemaker launcher requires an OutputDataConfig Sagemaker resource argument" ) training_job_name = cast( str, (given_sagemaker_args.get("TrainingJobName") or launch_project.run_id) ) sagemaker_args["TrainingJobName"] = training_job_name sagemaker_args[ "AlgorithmSpecification" ] = merge_aws_tag_with_algorithm_specification( given_sagemaker_args.get( "AlgorithmSpecification", given_sagemaker_args.get("algorithm_specification"), ), aws_tag, ) sagemaker_args["RoleArn"] = role_arn camel_case_args = { to_camel_case(key): item for key, item in given_sagemaker_args.items() } sagemaker_args = { **camel_case_args, **sagemaker_args, } if sagemaker_args.get("ResourceConfig") is None: raise LaunchError( "Sagemaker launcher requires a ResourceConfig Sagemaker resource argument" ) if sagemaker_args.get("StoppingCondition") is None: raise LaunchError( "Sagemaker launcher requires a StoppingCondition Sagemaker resource argument" ) given_env = given_sagemaker_args.get( "Environment", sagemaker_args.get("environment", {}) ) calced_env = get_env_vars_dict(launch_project, api) total_env = {**calced_env, **given_env} sagemaker_args["Environment"] = total_env # remove args that were passed in for launch but not passed to sagemaker sagemaker_args.pop("EcrRepoName", None) sagemaker_args.pop("region", None) sagemaker_args.pop("profile", None) # clear the args that are None so they are not passed filtered_args = {k: v for k, v in sagemaker_args.items() if v is not None} return filtered_args
python
wandb/sdk/launch/runner/sagemaker_runner.py
212
292
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,955
launch_sagemaker_job
def launch_sagemaker_job( launch_project: LaunchProject, sagemaker_args: Dict[str, Any], sagemaker_client: "boto3.Client", ) -> SagemakerSubmittedRun: training_job_name = sagemaker_args.get("TrainingJobName") or launch_project.run_id resp = sagemaker_client.create_training_job(**sagemaker_args) if resp.get("TrainingJobArn") is None: raise LaunchError("Unable to create training job") run = SagemakerSubmittedRun(training_job_name, sagemaker_client) wandb.termlog( f"{LOG_PREFIX}Run job submitted with arn: {resp.get('TrainingJobArn')}" ) url = "https://{region}.console.aws.amazon.com/sagemaker/home?region={region}#/jobs/{job_name}".format( region=sagemaker_client.meta.region_name, job_name=training_job_name ) wandb.termlog(f"{LOG_PREFIX}See training job status at: {url}") return run
python
wandb/sdk/launch/runner/sagemaker_runner.py
295
314
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,956
get_role_arn
def get_role_arn( sagemaker_args: Dict[str, Any], backend_config: Dict[str, Any], account_id: str ) -> str: """Get the role arn from the sagemaker args or the backend config.""" role_arn = sagemaker_args.get("RoleArn") or sagemaker_args.get("role_arn") if role_arn is None: role_arn = backend_config.get("runner", {}).get("role_arn") if role_arn is None or not isinstance(role_arn, str): raise LaunchError( "AWS sagemaker require a string RoleArn set this by adding a `RoleArn` key to the sagemaker" "field of resource_args" ) if role_arn.startswith("arn:aws:iam::"): return role_arn return f"arn:aws:iam::{account_id}:role/{role_arn}"
python
wandb/sdk/launch/runner/sagemaker_runner.py
317
332
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,957
__init__
def __init__(self, command_proc: "subprocess.Popen[bytes]") -> None: super().__init__() self.command_proc = command_proc
python
wandb/sdk/launch/runner/local_container.py
32
34
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,958
id
def id(self) -> str: return str(self.command_proc.pid)
python
wandb/sdk/launch/runner/local_container.py
37
38
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,959
wait
def wait(self) -> bool: return self.command_proc.wait() == 0
python
wandb/sdk/launch/runner/local_container.py
40
41
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,960
cancel
def cancel(self) -> None: # Interrupt child process if it hasn't already exited if self.command_proc.poll() is None: # Kill the the process tree rooted at the child if it's the leader of its own process # group, otherwise just kill the child try: if self.command_proc.pid == os.getpgid(self.command_proc.pid): os.killpg(self.command_proc.pid, signal.SIGTERM) else: self.command_proc.terminate() except OSError: # The child process may have exited before we attempted to terminate it, so we # ignore OSErrors raised during child process termination _msg = f"{LOG_PREFIX}Failed to terminate child process PID {self.command_proc.pid}" _logger.debug(_msg) self.command_proc.wait()
python
wandb/sdk/launch/runner/local_container.py
43
58
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,961
get_status
def get_status(self) -> Status: exit_code = self.command_proc.poll() if exit_code is None: return Status("running") if exit_code == 0: return Status("finished") return Status("failed")
python
wandb/sdk/launch/runner/local_container.py
60
66
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,962
__init__
def __init__( self, api: wandb.apis.internal.Api, backend_config: Dict[str, Any], environment: AbstractEnvironment, ) -> None: super().__init__(api, backend_config) self.environment = environment
python
wandb/sdk/launch/runner/local_container.py
72
79
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,963
run
def run( self, launch_project: LaunchProject, builder: Optional[AbstractBuilder], ) -> Optional[AbstractRun]: synchronous: bool = self.backend_config[PROJECT_SYNCHRONOUS] docker_args: Dict[str, Any] = launch_project.resource_args.get( "local-container", {} ) if _is_wandb_local_uri(self._api.settings("base_url")): if sys.platform == "win32": docker_args["net"] = "host" else: docker_args["network"] = "host" if sys.platform == "linux" or sys.platform == "linux2": docker_args["add-host"] = "host.docker.internal:host-gateway" entry_point = launch_project.get_single_entry_point() env_vars = get_env_vars_dict(launch_project, self._api) # When running against local port, need to swap to local docker host if ( _is_wandb_local_uri(self._api.settings("base_url")) and sys.platform == "darwin" ): _, _, port = self._api.settings("base_url").split(":") env_vars["WANDB_BASE_URL"] = f"http://host.docker.internal:{port}" elif _is_wandb_dev_uri(self._api.settings("base_url")): env_vars["WANDB_BASE_URL"] = "http://host.docker.internal:9002" if launch_project.docker_image: # user has provided their own docker image image_uri = launch_project.image_name if not docker_image_exists(image_uri): pull_docker_image(image_uri) entry_cmd = [] if entry_point is not None: entry_cmd = entry_point.command override_args = compute_command_args(launch_project.override_args) command_str = " ".join( get_docker_command( image_uri, env_vars, entry_cmd=entry_cmd, docker_args=docker_args, additional_args=override_args, ) ).strip() else: assert entry_point is not None _logger.info("Building docker image...") assert builder is not None image_uri = builder.build_image( launch_project, entry_point, ) _logger.info(f"Docker image built with uri {image_uri}") # entry_cmd and additional_args are empty here because # if launch built the container they've been accounted # in the dockerfile and env vars respectively command_str = " ".join( get_docker_command( image_uri, env_vars, docker_args=docker_args, ) ).strip() sanitized_cmd_str = sanitize_wandb_api_key(command_str) _msg = f"{LOG_PREFIX}Launching run in docker with command: {sanitized_cmd_str}" wandb.termlog(_msg) run = _run_entry_point(command_str, launch_project.project_dir) if synchronous: run.wait() return run
python
wandb/sdk/launch/runner/local_container.py
81
156
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,964
_run_entry_point
def _run_entry_point(command: str, work_dir: Optional[str]) -> AbstractRun: """Run an entry point command in a subprocess. Arguments: command: Entry point command to run work_dir: Working directory in which to run the command Returns: An instance of `LocalSubmittedRun` """ if work_dir is None: work_dir = os.getcwd() env = os.environ.copy() if os.name == "nt": # we are running on windows process = subprocess.Popen( ["cmd", "/c", command], close_fds=True, cwd=work_dir, env=env ) else: process = subprocess.Popen( ["bash", "-c", command], close_fds=True, cwd=work_dir, env=env, ) return LocalSubmittedRun(process)
python
wandb/sdk/launch/runner/local_container.py
159
185
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,965
get_docker_command
def get_docker_command( image: str, env_vars: Dict[str, str], entry_cmd: Optional[List[str]] = None, docker_args: Optional[Dict[str, Any]] = None, additional_args: Optional[List[str]] = None, ) -> List[str]: """Construct the docker command using the image and docker args. Arguments: image: a Docker image to be run env_vars: a dictionary of environment variables for the command entry_cmd: the entry point command to run docker_args: a dictionary of additional docker args for the command """ docker_path = "docker" cmd: List[Any] = [docker_path, "run", "--rm"] # hacky handling of env vars, needs to be improved for env_key, env_value in env_vars.items(): cmd += ["-e", f"{shlex.quote(env_key)}={shlex.quote(env_value)}"] if docker_args: for name, value in docker_args.items(): if len(name) == 1: prefix = "-" + shlex.quote(name) else: prefix = "--" + shlex.quote(name) if isinstance(value, list): for v in value: cmd += [prefix, shlex.quote(str(v))] elif isinstance(value, bool) and value: cmd += [prefix] else: cmd += [prefix, shlex.quote(str(value))] if entry_cmd: cmd += ["--entrypoint", entry_cmd[0]] cmd += [shlex.quote(image)] if entry_cmd and len(entry_cmd) > 1: cmd += entry_cmd[1:] if additional_args: cmd += additional_args return cmd
python
wandb/sdk/launch/runner/local_container.py
188
231
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,966
join
def join(split_command: List[str]) -> str: """Return a shell-escaped string from *split_command*.""" return " ".join(shlex.quote(arg) for arg in split_command)
python
wandb/sdk/launch/runner/local_container.py
234
236
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,967
__init__
def __init__( self, batch_api: "BatchV1Api", core_api: "CoreV1Api", name: str, pod_names: List[str], namespace: Optional[str] = "default", secret: Optional["V1Secret"] = None, ) -> None: self.batch_api = batch_api self.core_api = core_api self.name = name self.namespace = namespace self.job = self.batch_api.read_namespaced_job( name=self.name, namespace=self.namespace ) self._fail_count = 0 self.pod_names = pod_names self.secret = secret
python
wandb/sdk/launch/runner/kubernetes_runner.py
47
65
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,968
id
def id(self) -> str: return self.name
python
wandb/sdk/launch/runner/kubernetes_runner.py
68
69
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,969
get_job
def get_job(self) -> "V1Job": return self.batch_api.read_namespaced_job( name=self.name, namespace=self.namespace )
python
wandb/sdk/launch/runner/kubernetes_runner.py
71
74
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,970
wait
def wait(self) -> bool: while True: status = self.get_status() wandb.termlog(f"{LOG_PREFIX}Job {self.name} status: {status}") if status.state != "running": break time.sleep(5) return ( status.state == "finished" ) # todo: not sure if this (copied from aws runner) is the right approach? should we return false on failure
python
wandb/sdk/launch/runner/kubernetes_runner.py
76
85
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,971
get_status
def get_status(self) -> Status: job_response = self.batch_api.read_namespaced_job_status( name=self.name, namespace=self.namespace ) status = job_response.status pod = self.core_api.read_namespaced_pod( name=self.pod_names[0], namespace=self.namespace ) if pod.status.phase in ["Pending", "Unknown"]: now = time.time() if self._fail_count == 0: self._fail_first_msg_time = now self._fail_last_msg_time = 0.0 self._fail_count += 1 if now - self._fail_last_msg_time > FAIL_MESSAGE_INTERVAL: wandb.termlog( f"{LOG_PREFIX}Pod has not started yet for job: {self.name}. Will wait up to {round(10 - (now - self._fail_first_msg_time)/60)} minutes." ) self._fail_last_msg_time = now if self._fail_count > MAX_KUBERNETES_RETRIES: raise LaunchError(f"Failed to start job {self.name}") # todo: we only handle the 1 pod case. see https://kubernetes.io/docs/concepts/workloads/controllers/job/#parallel-jobs for multipod handling return_status = None if status.succeeded == 1: return_status = Status("finished") elif status.failed is not None and status.failed >= 1: return_status = Status("failed") elif status.active == 1: return Status("running") elif status.conditions is not None and status.conditions[0].type == "Suspended": return_status = Status("stopped") else: return_status = Status("unknown") if ( return_status.state in ["stopped", "failed", "finished"] and self.secret is not None ): try: self.core_api.delete_namespaced_secret( self.secret.metadata.name, self.namespace ) except Exception as e: wandb.termerror( f"Error deleting secret {self.secret.metadata.name}: {str(e)}" ) return return_status
python
wandb/sdk/launch/runner/kubernetes_runner.py
87
133
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,972
suspend
def suspend(self) -> None: self.job.spec.suspend = True self.batch_api.patch_namespaced_job( name=self.name, namespace=self.namespace, body=self.job ) timeout = TIMEOUT job_response = self.batch_api.read_namespaced_job_status( name=self.name, namespace=self.namespace ) while job_response.status.conditions is None and timeout > 0: time.sleep(1) timeout -= 1 job_response = self.batch_api.read_namespaced_job_status( name=self.name, namespace=self.namespace ) if timeout == 0 or job_response.status.conditions[0].type != "Suspended": raise LaunchError( "Failed to suspend job {}. Check Kubernetes dashboard for more info.".format( self.name ) )
python
wandb/sdk/launch/runner/kubernetes_runner.py
135
156
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,973
cancel
def cancel(self) -> None: self.suspend() self.batch_api.delete_namespaced_job(name=self.name, namespace=self.namespace)
python
wandb/sdk/launch/runner/kubernetes_runner.py
158
160
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,974
__init__
def __init__( self, api: Api, backend_config: Dict[str, Any], environment: AbstractEnvironment ) -> None: super().__init__(api, backend_config) self.environment = environment
python
wandb/sdk/launch/runner/kubernetes_runner.py
164
168
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,975
populate_job_spec
def populate_job_spec( self, job_spec: Dict[str, Any], resource_args: Dict[str, Any] ) -> None: job_spec["backoffLimit"] = resource_args.get("backoff_limit", 0) if resource_args.get("completions"): job_spec["completions"] = resource_args.get("completions") if resource_args.get("parallelism"): job_spec["parallelism"] = resource_args.get("parallelism") if resource_args.get("suspend"): job_spec["suspend"] = resource_args.get("suspend")
python
wandb/sdk/launch/runner/kubernetes_runner.py
170
179
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,976
populate_pod_spec
def populate_pod_spec( self, pod_spec: Dict[str, Any], resource_args: Dict[str, Any] ) -> None: pod_spec["restartPolicy"] = resource_args.get("restart_policy", "Never") if resource_args.get("preemption_policy"): pod_spec["preemptionPolicy"] = resource_args.get("preemption_policy") if resource_args.get("node_name"): pod_spec["nodeName"] = resource_args.get("node_name") if resource_args.get("node_selector"): pod_spec["nodeSelector"] = resource_args.get("node_selector") if resource_args.get("tolerations"): pod_spec["tolerations"] = resource_args.get("tolerations") if resource_args.get("security_context"): pod_spec["securityContext"] = resource_args.get("security_context") if resource_args.get("volumes") is not None: vols = resource_args.get("volumes") if not isinstance(vols, list): raise LaunchError("volumes must be a list of volume specifications") pod_spec["volumes"] = vols
python
wandb/sdk/launch/runner/kubernetes_runner.py
181
199
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,977
populate_container_resources
def populate_container_resources( self, containers: List[Dict[str, Any]], resource_args: Dict[str, Any] ) -> None: if resource_args.get("container_name"): if len(containers) > 1: raise LaunchError( "Container name override not supported for multiple containers. Specify in yaml file supplied via job_spec." ) containers[0]["name"] = resource_args["container_name"] else: for i, cont in enumerate(containers): cont["name"] = cont.get("name", "launch" + str(i)) multi_container_override = len(containers) > 1 for cont in containers: container_resources = cont.get("resources", {}) if resource_args.get("resource_requests"): container_resources["requests"] = resource_args.get("resource_requests") if resource_args.get("resource_limits"): container_resources["limits"] = resource_args.get("resource_limits") if container_resources: multi_container_override &= ( cont.get("resources") != container_resources ) # if multiple containers and we changed something cont["resources"] = container_resources if resource_args.get("volume_mounts") is not None: vol_mounts = resource_args.get("volume_mounts") if not isinstance(vol_mounts, list): raise LaunchError( "volume mounts must be a list of volume mount specifications" ) cont["volumeMounts"] = vol_mounts cont["security_context"] = { "allowPrivilegeEscalation": False, "capabilities": {"drop": ["ALL"]}, "seccompProfile": {"type": "RuntimeDefault"}, } if multi_container_override: wandb.termwarn( "{LOG_PREFIX}Container overrides (e.g. resource limits) were provided with multiple containers specified: overrides will be applied to all containers." )
python
wandb/sdk/launch/runner/kubernetes_runner.py
201
241
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,978
wait_job_launch
def wait_job_launch( self, job_name: str, namespace: str, core_api: "CoreV1Api" ) -> List[str]: pods = core_api.list_namespaced_pod( label_selector=f"job-name={job_name}", namespace=namespace ) timeout = TIMEOUT while len(pods.items) == 0 and timeout > 0: time.sleep(1) timeout -= 1 pods = core_api.list_namespaced_pod( label_selector=f"job-name={job_name}", namespace=namespace ) if timeout == 0: raise LaunchError( "No pods found for job {}. Check dashboard to see if job was launched successfully.".format( job_name ) ) pod_names = [pi.metadata.name for pi in pods.items] wandb.termlog( f"{LOG_PREFIX}Job {job_name} created on pod(s) {', '.join(pod_names)}. See logs with e.g. `kubectl logs {pod_names[0]} -n {namespace}`." ) return pod_names
python
wandb/sdk/launch/runner/kubernetes_runner.py
243
268
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,979
get_namespace
def get_namespace(self, resource_args: Dict[str, Any]) -> Optional[str]: return self.backend_config.get("runner", {}).get( "namespace" ) or resource_args.get("namespace")
python
wandb/sdk/launch/runner/kubernetes_runner.py
270
273
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,980
run
def run( self, launch_project: LaunchProject, builder: Optional[AbstractBuilder], ) -> Optional[AbstractRun]: # noqa: C901 kubernetes = get_module( # noqa: F811 "kubernetes", required="Kubernetes runner requires the kubernetes package. Please" " install it with `pip install wandb[launch]`.", ) resource_args = launch_project.resource_args.get("kubernetes", {}) if not resource_args: wandb.termlog( f"{LOG_PREFIX}Note: no resource args specified. Add a Kubernetes yaml spec or other options in a json file with --resource-args <json>." ) _logger.info(f"Running Kubernetes job with resource args: {resource_args}") context, api_client = get_kube_context_and_api_client(kubernetes, resource_args) batch_api = kubernetes.client.BatchV1Api(api_client) core_api = kubernetes.client.CoreV1Api(api_client) # allow users to specify template or entire spec if resource_args.get("job_spec"): job_dict = load_json_yaml_dict(resource_args["job_spec"]) else: # begin constructing job sped job_dict = {"apiVersion": "batch/v1", "kind": "Job"} # extract job spec component parts for convenience job_metadata = job_dict.get("metadata", {}) job_spec = job_dict.get("spec", {}) pod_template = job_spec.get("template", {}) pod_metadata = pod_template.get("metadata", {}) pod_spec = pod_template.get("spec", {}) containers = pod_spec.get("containers", [{}]) job_status = job_dict.get("status", {}) # begin pulling resource arg overrides. all of these are optional # allow top-level namespace override, otherwise take namespace specified at the job level, or default in current context default_namespace = ( context["context"].get("namespace", "default") if context else "default" ) namespace = self.get_namespace(resource_args) or default_namespace # name precedence: resource args override > name in spec file > generated name job_metadata["name"] = resource_args.get("job_name", job_metadata.get("name")) if not job_metadata.get("name"): job_metadata["generateName"] = make_name_dns_safe( f"launch-{launch_project.target_entity}-{launch_project.target_project}-" ) if resource_args.get("job_labels"): job_metadata["labels"] = resource_args.get("job_labels") self.populate_job_spec(job_spec, resource_args) self.populate_pod_spec(pod_spec, resource_args) self.populate_container_resources(containers, resource_args) # cmd entry_point = launch_project.get_single_entry_point() # env vars env_vars = get_env_vars_dict(launch_project, self._api) secret = None # only need to do this if user is providing image, on build, our image sets an entrypoint entry_cmd = get_entry_point_command(entry_point, launch_project.override_args) if launch_project.docker_image and entry_cmd: # if user hardcodes cmd into their image, we don't need to run on top of that for cont in containers: cont["command"] = entry_cmd if launch_project.docker_image: if len(containers) > 1: raise LaunchError( "Multiple container configurations should be specified in a yaml file supplied via job_spec." ) # dont specify run id if user provided image, could have multiple runs containers[0]["image"] = launch_project.docker_image image_uri = launch_project.docker_image # TODO: handle secret pulling image from registry elif not any(["image" in cont for cont in containers]): if len(containers) > 1: raise LaunchError( "Launch only builds one container at a time. Multiple container configurations should be pre-built and specified in a yaml file supplied via job_spec." ) assert entry_point is not None assert builder is not None image_uri = builder.build_image(launch_project, entry_point) # in the non instance case we need to make an imagePullSecret # so the new job can pull the image if not builder.registry: raise LaunchError( "No registry specified. Please specify a registry in your wandb/settings file or pass a registry to the builder." ) secret = maybe_create_imagepull_secret( core_api, builder.registry, launch_project.run_id, namespace ) containers[0]["image"] = image_uri # reassemble spec given_env_vars = resource_args.get("env", []) kubernetes_style_env_vars = [ {"name": k, "value": v} for k, v in env_vars.items() ] _logger.info( f"Using environment variables: {given_env_vars + kubernetes_style_env_vars}" ) for cont in containers: cont["env"] = given_env_vars + kubernetes_style_env_vars pod_spec["containers"] = containers pod_template["spec"] = pod_spec pod_template["metadata"] = pod_metadata if secret is not None: pod_spec["imagePullSecrets"] = [ {"name": f"regcred-{launch_project.run_id}"} ] job_spec["template"] = pod_template job_dict["spec"] = job_spec job_dict["metadata"] = job_metadata job_dict["status"] = job_status _logger.info(f"Creating Kubernetes job from: {job_dict}") job_response = kubernetes.utils.create_from_yaml( api_client, yaml_objects=[job_dict], namespace=namespace )[0][ 0 ] # create_from_yaml returns a nested list of k8s objects job_name = job_response.metadata.labels["job-name"] pod_names = self.wait_job_launch(job_name, namespace, core_api) submitted_job = KubernetesSubmittedRun( batch_api, core_api, job_name, pod_names, namespace, secret ) if self.backend_config[PROJECT_SYNCHRONOUS]: submitted_job.wait() return submitted_job
python
wandb/sdk/launch/runner/kubernetes_runner.py
275
417
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,981
maybe_create_imagepull_secret
def maybe_create_imagepull_secret( core_api: "CoreV1Api", registry: AbstractRegistry, run_id: str, namespace: str, ) -> Optional["V1Secret"]: secret = None if isinstance(registry, LocalRegistry): # Secret not required return None uname, token = registry.get_username_password() creds_info = { "auths": { registry.uri: { "auth": base64.b64encode(f"{uname}:{token}".encode()).decode(), # need an email but the use is deprecated "email": "deprecated@wandblaunch.com", } } } secret_data = { ".dockerconfigjson": base64.b64encode(json.dumps(creds_info).encode()).decode() } secret = client.V1Secret( data=secret_data, metadata=client.V1ObjectMeta(name=f"regcred-{run_id}", namespace=namespace), kind="Secret", type="kubernetes.io/dockerconfigjson", ) try: return core_api.create_namespaced_secret(namespace, secret) except Exception as e: raise LaunchError(f"Exception when creating Kubernetes secret: {str(e)}\n")
python
wandb/sdk/launch/runner/kubernetes_runner.py
420
452
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,982
run
def run( # type: ignore self, launch_project: LaunchProject, *args, **kwargs, ) -> Optional[AbstractRun]: if args is not None: _msg = f"{LOG_PREFIX}LocalProcessRunner.run received unused args {args}" _logger.warning(_msg) if kwargs is not None: _msg = f"{LOG_PREFIX}LocalProcessRunner.run received unused kwargs {kwargs}" _logger.warning(_msg) synchronous: bool = self.backend_config[PROJECT_SYNCHRONOUS] entry_point = launch_project.get_single_entry_point() cmd: List[Any] = [] if launch_project.project_dir is None: raise LaunchError("Launch LocalProcessRunner received empty project dir") # Check to make sure local python dependencies match run's requirement.txt if launch_project.uri and _is_wandb_uri(launch_project.uri): source_entity, source_project, run_name = parse_wandb_uri( launch_project.uri ) run_requirements_file = download_wandb_python_deps( source_entity, source_project, run_name, self._api, launch_project.project_dir, ) validate_wandb_python_deps( run_requirements_file, launch_project.project_dir, ) elif launch_project.job: assert launch_project._job_artifact is not None try: validate_wandb_python_deps( "requirements.frozen.txt", launch_project.project_dir, ) except Exception: wandb.termwarn("Unable to validate python dependencies") env_vars = get_env_vars_dict(launch_project, self._api) for env_key, env_value in env_vars.items(): cmd += [f"{shlex.quote(env_key)}={shlex.quote(env_value)}"] entry_cmd = get_entry_point_command(entry_point, launch_project.override_args) cmd += entry_cmd command_str = " ".join(cmd).strip() _msg = f"{LOG_PREFIX}Launching run as a local-process with command {sanitize_wandb_api_key(command_str)}" wandb.termlog(_msg) run = _run_entry_point(command_str, launch_project.project_dir) if synchronous: run.wait() return run
python
wandb/sdk/launch/runner/local_process.py
34
93
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,983
__init__
def __init__(self, job: Any) -> None: self._job = job
python
wandb/sdk/launch/runner/vertex_runner.py
29
30
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,984
id
def id(self) -> str: # numeric ID of the custom training job return self._job.name # type: ignore
python
wandb/sdk/launch/runner/vertex_runner.py
33
35
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,985
name
def name(self) -> str: return self._job.display_name # type: ignore
python
wandb/sdk/launch/runner/vertex_runner.py
38
39
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,986
gcp_region
def gcp_region(self) -> str: return self._job.location # type: ignore
python
wandb/sdk/launch/runner/vertex_runner.py
42
43
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,987
gcp_project
def gcp_project(self) -> str: return self._job.project # type: ignore
python
wandb/sdk/launch/runner/vertex_runner.py
46
47
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,988
get_page_link
def get_page_link(self) -> str: return "{console_uri}/vertex-ai/locations/{region}/training/{job_id}?project={project}".format( console_uri=GCP_CONSOLE_URI, region=self.gcp_region, job_id=self.id, project=self.gcp_project, )
python
wandb/sdk/launch/runner/vertex_runner.py
49
55
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,989
wait
def wait(self) -> bool: self._job.wait() return self.get_status().state == "finished"
python
wandb/sdk/launch/runner/vertex_runner.py
57
59
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,990
get_status
def get_status(self) -> Status: job_state = str(self._job.state) # extract from type PipelineState if job_state == "JobState.JOB_STATE_SUCCEEDED": return Status("finished") if job_state == "JobState.JOB_STATE_FAILED": return Status("failed") if job_state == "JobState.JOB_STATE_RUNNING": return Status("running") if job_state == "JobState.JOB_STATE_PENDING": return Status("starting") return Status("unknown")
python
wandb/sdk/launch/runner/vertex_runner.py
61
71
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,991
cancel
def cancel(self) -> None: self._job.cancel()
python
wandb/sdk/launch/runner/vertex_runner.py
73
74
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,992
__init__
def __init__( self, api: Api, backend_config: Dict[str, Any], environment: GcpEnvironment ) -> None: """Initialize a VertexRunner instance.""" super().__init__(api, backend_config) self.environment = environment
python
wandb/sdk/launch/runner/vertex_runner.py
80
85
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,993
run
def run( self, launch_project: LaunchProject, builder: Optional[AbstractBuilder], ) -> Optional[AbstractRun]: """Run a Vertex job.""" aiplatform = get_module( # noqa: F811 "google.cloud.aiplatform", "VertexRunner requires google.cloud.aiplatform to be installed", ) resource_args = launch_project.resource_args.get("vertex") if not resource_args: resource_args = launch_project.resource_args.get("gcp-vertex") if not resource_args: raise LaunchError( "No Vertex resource args specified. Specify args via --resource-args with a JSON file or string under top-level key gcp_vertex" ) gcp_staging_bucket = resource_args.get("staging_bucket") if not gcp_staging_bucket: raise LaunchError( "Vertex requires a staging bucket for training and dependency packages in the same region as compute. Specify a bucket under key staging_bucket." ) gcp_machine_type = resource_args.get("machine_type") or "n1-standard-4" gcp_accelerator_type = ( resource_args.get("accelerator_type") or "ACCELERATOR_TYPE_UNSPECIFIED" ) gcp_accelerator_count = int(resource_args.get("accelerator_count") or 0) timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S") gcp_training_job_name = resource_args.get( "job_name" ) or "{project}_{time}".format( project=launch_project.target_project, time=timestamp ) service_account = resource_args.get("service_account") tensorboard = resource_args.get("tensorboard") aiplatform.init( project=self.environment.project, location=self.environment.region, staging_bucket=gcp_staging_bucket, ) synchronous: bool = self.backend_config[PROJECT_SYNCHRONOUS] entry_point = launch_project.get_single_entry_point() if launch_project.docker_image: image_uri = launch_project.docker_image else: assert entry_point is not None assert builder is not None image_uri = builder.build_image( launch_project, entry_point, ) # TODO: how to handle this? entry_cmd = get_entry_point_command(entry_point, launch_project.override_args) worker_pool_specs = [ { "machine_spec": { "machine_type": gcp_machine_type, "accelerator_type": gcp_accelerator_type, "accelerator_count": gcp_accelerator_count, }, "replica_count": 1, "container_spec": { "image_uri": image_uri, "command": entry_cmd, "env": [ {"name": k, "value": v} for k, v in get_env_vars_dict(launch_project, self._api).items() ], }, } ] job = aiplatform.CustomJob( display_name=gcp_training_job_name, worker_pool_specs=worker_pool_specs ) wandb.termlog( f"{LOG_PREFIX}Running training job {gcp_training_job_name} on {gcp_machine_type}." ) if synchronous: job.run(service_account=service_account, tensorboard=tensorboard, sync=True) else: job.submit( service_account=service_account, tensorboard=tensorboard, ) submitted_run = VertexSubmittedRun(job) while not getattr(job._gca_resource, "name", None): # give time for the gcp job object to be created and named, this should only loop a couple times max time.sleep(1) wandb.termlog( f"{LOG_PREFIX}View your job status and logs at {submitted_run.get_page_link()}." ) return submitted_run
python
wandb/sdk/launch/runner/vertex_runner.py
87
188
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,994
get_gcp_config
def get_gcp_config(config: str = "default") -> Any: return yaml.safe_load( run_shell( ["gcloud", "config", "configurations", "describe", shlex.quote(config)] )[0] )
python
wandb/sdk/launch/runner/vertex_runner.py
191
196
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,995
exists_on_gcp
def exists_on_gcp(image: str, tag: str) -> bool: out, err = run_shell( [ "gcloud", "artifacts", "docker", "images", "list", shlex.quote(image), "--include-tags", f"--filter=tags:{shlex.quote(tag)}", ] ) return tag in out and "sha256:" in out
python
wandb/sdk/launch/runner/vertex_runner.py
199
212
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,996
job_completed
def job_completed(self) -> bool: return self.completed or self.failed_to_start
python
wandb/sdk/launch/agent/agent.py
57
58
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,997
update_run_info
def update_run_info(self, launch_project: LaunchProject) -> None: self.run_id = launch_project.run_id self.project = launch_project.target_project
python
wandb/sdk/launch/agent/agent.py
60
62
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,998
_convert_access
def _convert_access(access: str) -> str: """Convert access string to a value accepted by wandb.""" access = access.upper() assert ( access == "PROJECT" or access == "USER" ), "Queue access must be either project or user" return access
python
wandb/sdk/launch/agent/agent.py
65
71
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
3,999
_max_from_config
def _max_from_config( config: Dict[str, Any], key: str, default: int = 1 ) -> Union[int, float]: """Get an integer from the config, or float.inf if -1. Utility for parsing integers from the agent config with a default, infinity handling, and integer parsing. Raises more informative error if parse error. """ try: val = config.get(key) if val is None: val = default max_from_config = int(val) except ValueError as e: raise LaunchError( f"Error when parsing LaunchAgent config key: ['{key}': " f"{config.get(key)}]. Error: {str(e)}" ) if max_from_config == -1: return float("inf") if max_from_config < 0: raise LaunchError( f"Error when parsing LaunchAgent config key: ['{key}': " f"{config.get(key)}]. Error: negative value." ) return max_from_config
python
wandb/sdk/launch/agent/agent.py
74
100
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }
4,000
_job_is_scheduler
def _job_is_scheduler(run_spec: Dict[str, Any]) -> bool: """Determine whether a job/runSpec is a sweep scheduler.""" if not run_spec: _logger.debug("Recieved runSpec in _job_is_scheduler that was empty") if run_spec.get("uri") != SCHEDULER_URI: return False if run_spec.get("resource") == "local-process": # If a scheduler is a local-process (100%), also # confirm command is in format: [wandb scheduler <sweep>] cmd = run_spec.get("overrides", {}).get("entry_point", []) if len(cmd) < 3: return False if cmd[:2] != ["wandb", "scheduler"]: return False return True
python
wandb/sdk/launch/agent/agent.py
103
121
{ "name": "Git-abouvier/wandb", "url": "https://github.com/Git-abouvier/wandb.git", "license": "MIT", "stars": 0, "forks": 0 }