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,801 | _set_artifact_target | def _set_artifact_target(
self, artifact: "LocalArtifact", name: Optional[str] = None
) -> None:
assert (
self._artifact_target is None
), "Cannot update artifact_target. Existing target: {}/{}".format(
self._artifact_target.artifact, self._artifact_target.name
)
self._artifact_target = _WBValueArtifactTarget(artifact, name) | python | wandb/sdk/data_types/base_types/wb_value.py | 198 | 206 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,802 | _get_artifact_entry_ref_url | def _get_artifact_entry_ref_url(self) -> Optional[str]:
# If the object is coming from another artifact
if self._artifact_source and self._artifact_source.name:
ref_entry = self._artifact_source.artifact.get_path(
type(self).with_suffix(self._artifact_source.name)
)
return str(ref_entry.ref_url())
# Else, if the object is destined for another artifact and we support client IDs
elif (
self._artifact_target
and self._artifact_target.name
and self._artifact_target.artifact._client_id is not None
and self._artifact_target.artifact._final
and _server_accepts_client_ids()
):
return "wandb-client-artifact://{}/{}".format(
self._artifact_target.artifact._client_id,
type(self).with_suffix(self._artifact_target.name),
)
# Else if we do not support client IDs, but online, then block on upload
# Note: this is old behavior just to stay backwards compatible
# with older server versions. This code path should be removed
# once those versions are no longer supported. This path uses a .wait
# which blocks the user process on artifact upload.
elif (
self._artifact_target
and self._artifact_target.name
and self._artifact_target.artifact._logged_artifact is not None
and not util._is_offline()
and not _server_accepts_client_ids()
):
self._artifact_target.artifact.wait()
ref_entry = self._artifact_target.artifact.get_path(
type(self).with_suffix(self._artifact_target.name)
)
return str(ref_entry.ref_url())
return None | python | wandb/sdk/data_types/base_types/wb_value.py | 208 | 244 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,803 | _get_artifact_entry_latest_ref_url | def _get_artifact_entry_latest_ref_url(self) -> Optional[str]:
if (
self._artifact_target
and self._artifact_target.name
and self._artifact_target.artifact._client_id is not None
and self._artifact_target.artifact._final
and _server_accepts_client_ids()
):
return "wandb-client-artifact://{}:latest/{}".format(
self._artifact_target.artifact._sequence_client_id,
type(self).with_suffix(self._artifact_target.name),
)
# Else if we do not support client IDs, then block on upload
# Note: this is old behavior just to stay backwards compatible
# with older server versions. This code path should be removed
# once those versions are no longer supported. This path uses a .wait
# which blocks the user process on artifact upload.
elif (
self._artifact_target
and self._artifact_target.name
and self._artifact_target.artifact._logged_artifact is not None
and not util._is_offline()
and not _server_accepts_client_ids()
):
self._artifact_target.artifact.wait()
ref_entry = self._artifact_target.artifact.get_path(
type(self).with_suffix(self._artifact_target.name)
)
return str(ref_entry.ref_url())
return None | python | wandb/sdk/data_types/base_types/wb_value.py | 246 | 275 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,804 | __init__ | def __init__(self, val: dict, key: str) -> None:
"""Initialize a BoundingBoxes object.
The input dictionary `val` should contain the keys:
box_data: a list of dictionaries, each of which describes a bounding box.
class_labels: (optional) A map of integer class labels to their readable
class names.
Each bounding box dictionary should contain the following keys:
position: (dictionary) the position and size of the bounding box.
domain: (string) One of two options for the bounding box coordinate domain.
class_id: (integer) The class label id for this box.
scores: (dictionary of string to number, optional) A mapping of named fields
to numerical values (float or int).
box_caption: (optional) The label text, often composed of the class label,
class name, and/or scores.
The position dictionary should be in one of two formats:
{"minX", "minY", "maxX", "maxY"}: (dictionary) A set of coordinates defining
the upper and lower bounds of the box (the bottom left and top right
corners).
{"middle", "width", "height"}: (dictionary) A set of coordinates defining
the center and dimensions of the box, with "middle" as a list [x, y] for
the center point and "width" and "height" as numbers.
Note that boxes need not all use the same format.
Args:
val: (dictionary) A dictionary containing the bounding box data.
key: (string) The readable name or id for this set of bounding boxes (e.g.
predictions, ground_truth)
"""
super().__init__(val)
self._val = val["box_data"]
self._key = key
# Add default class mapping
if "class_labels" not in val:
np = util.get_module(
"numpy", required="Bounding box support requires numpy"
)
classes = (
np.unique(list(box["class_id"] for box in val["box_data"]))
.astype(np.int32)
.tolist()
)
class_labels = {c: "class_" + str(c) for c in classes}
self._class_labels = class_labels
else:
self._class_labels = val["class_labels"] | python | wandb/sdk/data_types/helper_types/bounding_boxes_2d.py | 150 | 197 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,805 | bind_to_run | def bind_to_run(
self,
run: "LocalRun",
key: Union[int, str],
step: Union[int, str],
id_: Optional[Union[int, str]] = None,
ignore_copy_err: Optional[bool] = None,
) -> None:
# bind_to_run key argument is the Image parent key
# the self._key value is the mask's sub key
super().bind_to_run(run, key, step, id_=id_, ignore_copy_err=ignore_copy_err)
run._add_singleton(
"bounding_box/class_labels",
str(key) + "_wandb_delimeter_" + self._key,
self._class_labels,
) | python | wandb/sdk/data_types/helper_types/bounding_boxes_2d.py | 199 | 214 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,806 | type_name | def type_name(cls) -> str:
return "boxes2D" | python | wandb/sdk/data_types/helper_types/bounding_boxes_2d.py | 217 | 218 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,807 | validate | def validate(self, val: dict) -> bool:
# Optional argument
if "class_labels" in val:
for k, v in list(val["class_labels"].items()):
if (not isinstance(k, numbers.Number)) or (not isinstance(v, str)):
raise TypeError(
"Class labels must be a dictionary of numbers to string"
)
boxes = val["box_data"]
if not isinstance(boxes, list):
raise TypeError("Boxes must be a list")
for box in boxes:
# Required arguments
error_str = "Each box must contain a position with: middle, width, and height or \
\nminX, maxX, minY, maxY."
if "position" not in box:
raise TypeError(error_str)
else:
valid = False
if (
"middle" in box["position"]
and len(box["position"]["middle"]) == 2
and has_num(box["position"], "width")
and has_num(box["position"], "height")
):
valid = True
elif (
has_num(box["position"], "minX")
and has_num(box["position"], "maxX")
and has_num(box["position"], "minY")
and has_num(box["position"], "maxY")
):
valid = True
if not valid:
raise TypeError(error_str)
# Optional arguments
if ("scores" in box) and not isinstance(box["scores"], dict):
raise TypeError("Box scores must be a dictionary")
elif "scores" in box:
for k, v in list(box["scores"].items()):
if not isinstance(k, str):
raise TypeError("A score key must be a string")
if not isinstance(v, numbers.Number):
raise TypeError("A score value must be a number")
if ("class_id" in box) and not isinstance(box["class_id"], int):
raise TypeError("A box's class_id must be an integer")
# Optional
if ("box_caption" in box) and not isinstance(box["box_caption"], str):
raise TypeError("A box's caption must be a string")
return True | python | wandb/sdk/data_types/helper_types/bounding_boxes_2d.py | 220 | 275 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,808 | to_json | def to_json(self, run_or_artifact: Union["LocalRun", "LocalArtifact"]) -> dict:
if isinstance(run_or_artifact, wandb.wandb_sdk.wandb_run.Run):
return super().to_json(run_or_artifact)
elif isinstance(run_or_artifact, wandb.wandb_sdk.wandb_artifacts.Artifact):
# TODO (tim): I would like to log out a proper dictionary representing this object, but don't
# want to mess with the visualizations that are currently available in the UI. This really should output
# an object with a _type key. Will need to push this change to the UI first to ensure backwards compat
return self._val
else:
raise ValueError("to_json accepts wandb_run.Run or wandb_artifact.Artifact") | python | wandb/sdk/data_types/helper_types/bounding_boxes_2d.py | 277 | 286 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,809 | from_json | def from_json(
cls: Type["BoundingBoxes2D"], json_obj: dict, source_artifact: "PublicArtifact"
) -> "BoundingBoxes2D":
return cls({"box_data": json_obj}, "") | python | wandb/sdk/data_types/helper_types/bounding_boxes_2d.py | 289 | 292 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,810 | __init__ | def __init__(self, class_set: Sequence[dict]) -> None:
"""Classes is holds class metadata intended to be used in concert with other objects when visualizing artifacts.
Args:
class_set (list): list of dicts in the form of {"id":int|str, "name":str}
"""
super().__init__()
for class_obj in class_set:
assert "id" in class_obj and "name" in class_obj
self._class_set = class_set | python | wandb/sdk/data_types/helper_types/classes.py | 19 | 28 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,811 | from_json | def from_json(
cls: Type["Classes"],
json_obj: dict,
source_artifact: Optional["PublicArtifact"],
) -> "Classes":
return cls(json_obj.get("class_set")) # type: ignore | python | wandb/sdk/data_types/helper_types/classes.py | 31 | 36 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,812 | to_json | def to_json(
self, run_or_artifact: Optional[Union["LocalRun", "LocalArtifact"]]
) -> dict:
json_obj = {}
# This is a bit of a hack to allow _ClassesIdType to
# be able to operate fully without an artifact in play.
# In all other cases, artifact should be a true artifact.
if run_or_artifact is not None:
json_obj = super().to_json(run_or_artifact)
json_obj["_type"] = Classes._log_type
json_obj["class_set"] = self._class_set
return json_obj | python | wandb/sdk/data_types/helper_types/classes.py | 38 | 49 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,813 | get_type | def get_type(self) -> "_ClassesIdType":
return _ClassesIdType(self) | python | wandb/sdk/data_types/helper_types/classes.py | 51 | 52 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,814 | __ne__ | def __ne__(self, other: object) -> bool:
return not self.__eq__(other) | python | wandb/sdk/data_types/helper_types/classes.py | 54 | 55 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,815 | __eq__ | def __eq__(self, other: object) -> bool:
if isinstance(other, Classes):
return self._class_set == other._class_set
else:
return False | python | wandb/sdk/data_types/helper_types/classes.py | 57 | 61 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,816 | __init__ | def __init__(
self,
classes_obj: Optional[Classes] = None,
valid_ids: Optional["_dtypes.UnionType"] = None,
):
if valid_ids is None:
valid_ids = _dtypes.UnionType()
elif isinstance(valid_ids, list):
valid_ids = _dtypes.UnionType(
[_dtypes.ConstType(item) for item in valid_ids]
)
elif isinstance(valid_ids, _dtypes.UnionType):
valid_ids = valid_ids
else:
raise TypeError("valid_ids must be None, list, or UnionType")
if classes_obj is None:
classes_obj = Classes(
[
{"id": _id.params["val"], "name": str(_id.params["val"])}
for _id in valid_ids.params["allowed_types"]
]
)
elif not isinstance(classes_obj, Classes):
raise TypeError("valid_ids must be None, or instance of Classes")
else:
valid_ids = _dtypes.UnionType(
[
_dtypes.ConstType(class_obj["id"])
for class_obj in classes_obj._class_set
]
)
self.wb_classes_obj_ref = classes_obj
self.params.update({"valid_ids": valid_ids}) | python | wandb/sdk/data_types/helper_types/classes.py | 69 | 103 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,817 | assign | def assign(self, py_obj: Optional[Any] = None) -> "_dtypes.Type":
return self.assign_type(_dtypes.ConstType(py_obj)) | python | wandb/sdk/data_types/helper_types/classes.py | 105 | 106 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,818 | assign_type | def assign_type(self, wb_type: "_dtypes.Type") -> "_dtypes.Type":
valid_ids = self.params["valid_ids"].assign_type(wb_type)
if not isinstance(valid_ids, _dtypes.InvalidType):
return self
return _dtypes.InvalidType() | python | wandb/sdk/data_types/helper_types/classes.py | 108 | 113 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,819 | from_obj | def from_obj(cls, py_obj: Optional[Any] = None) -> "_dtypes.Type":
return cls(py_obj) | python | wandb/sdk/data_types/helper_types/classes.py | 116 | 117 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,820 | to_json | def to_json(self, artifact: Optional["LocalArtifact"] = None) -> Dict[str, Any]:
cl_dict = super().to_json(artifact)
# TODO (tss): Refactor this block with the similar one in wandb.Image.
# This is a bit of a smell that the classes object does not follow
# the same file-pattern as other media types.
if artifact is not None:
class_name = os.path.join("media", "cls")
classes_entry = artifact.add(self.wb_classes_obj_ref, class_name)
cl_dict["params"]["classes_obj"] = {
"type": "classes-file",
"path": classes_entry.path,
"digest": classes_entry.digest, # is this needed really?
}
else:
cl_dict["params"]["classes_obj"] = self.wb_classes_obj_ref.to_json(artifact)
return cl_dict | python | wandb/sdk/data_types/helper_types/classes.py | 119 | 134 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,821 | from_json | def from_json(
cls,
json_dict: Dict[str, Any],
artifact: Optional["PublicArtifact"] = None,
) -> "_dtypes.Type":
classes_obj = None
if (
json_dict.get("params", {}).get("classes_obj", {}).get("type")
== "classes-file"
):
if artifact is not None:
classes_obj = artifact.get(
json_dict.get("params", {}).get("classes_obj", {}).get("path")
)
else:
raise RuntimeError("Expected artifact to be non-null.")
else:
classes_obj = Classes.from_json(
json_dict["params"]["classes_obj"], artifact
)
return cls(classes_obj) | python | wandb/sdk/data_types/helper_types/classes.py | 137 | 158 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,822 | __init__ | def __init__(self, val: dict, key: str) -> None:
"""Initialize an ImageMask object.
Arguments:
val: (dictionary) One of these two keys to represent the image:
mask_data : (2D numpy array) The mask containing an integer class label
for each pixel in the image
path : (string) The path to a saved image file of the mask
class_labels : (dictionary of integers to strings, optional) A mapping
of the integer class labels in the mask to readable class names.
These will default to class_0, class_1, class_2, etc.
key: (string)
The readable name or id for this mask type (e.g. predictions, ground_truth)
"""
super().__init__()
if "path" in val:
self._set_file(val["path"])
else:
np = util.get_module("numpy", required="Image mask support requires numpy")
# Add default class mapping
if "class_labels" not in val:
classes = np.unique(val["mask_data"]).astype(np.int32).tolist()
class_labels = {c: "class_" + str(c) for c in classes}
val["class_labels"] = class_labels
self.validate(val)
self._val = val
self._key = key
ext = "." + self.type_name() + ".png"
tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ext)
pil_image = util.get_module(
"PIL.Image",
required='wandb.Image needs the PIL package. To get it, run "pip install pillow".',
)
image = pil_image.fromarray(val["mask_data"].astype(np.int8), mode="L")
image.save(tmp_path, transparency=None)
self._set_file(tmp_path, is_tmp=True, extension=ext) | python | wandb/sdk/data_types/helper_types/image_mask.py | 118 | 159 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,823 | bind_to_run | def bind_to_run(
self,
run: "LocalRun",
key: Union[int, str],
step: Union[int, str],
id_: Optional[Union[int, str]] = None,
ignore_copy_err: Optional[bool] = None,
) -> None:
# bind_to_run key argument is the Image parent key
# the self._key value is the mask's sub key
super().bind_to_run(run, key, step, id_=id_, ignore_copy_err=ignore_copy_err)
if hasattr(self, "_val") and "class_labels" in self._val:
class_labels = self._val["class_labels"]
run._add_singleton(
"mask/class_labels",
str(key) + "_wandb_delimeter_" + self._key,
class_labels,
) | python | wandb/sdk/data_types/helper_types/image_mask.py | 161 | 179 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,824 | get_media_subdir | def get_media_subdir(cls: Type["ImageMask"]) -> str:
return os.path.join("media", "images", cls.type_name()) | python | wandb/sdk/data_types/helper_types/image_mask.py | 182 | 183 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,825 | from_json | def from_json(
cls: Type["ImageMask"], json_obj: dict, source_artifact: "PublicArtifact"
) -> "ImageMask":
return cls(
{"path": source_artifact.get_path(json_obj["path"]).download()},
key="",
) | python | wandb/sdk/data_types/helper_types/image_mask.py | 186 | 192 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,826 | to_json | def to_json(self, run_or_artifact: Union["LocalRun", "LocalArtifact"]) -> dict:
json_dict = super().to_json(run_or_artifact)
if isinstance(run_or_artifact, wandb.wandb_sdk.wandb_run.Run):
json_dict["_type"] = self.type_name()
return json_dict
elif isinstance(run_or_artifact, wandb.wandb_sdk.wandb_artifacts.Artifact):
# Nothing special to add (used to add "digest", but no longer used.)
return json_dict
else:
raise ValueError("to_json accepts wandb_run.Run or wandb_artifact.Artifact") | python | wandb/sdk/data_types/helper_types/image_mask.py | 194 | 204 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,827 | type_name | def type_name(cls: Type["ImageMask"]) -> str:
return cls._log_type | python | wandb/sdk/data_types/helper_types/image_mask.py | 207 | 208 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,828 | validate | def validate(self, val: dict) -> bool:
np = util.get_module("numpy", required="Image mask support requires numpy")
# 2D Make this work with all tensor(like) types
if "mask_data" not in val:
raise TypeError(
'Missing key "mask_data": An image mask requires mask data: a 2D array representing the predictions'
)
else:
error_str = "mask_data must be a 2D array"
shape = val["mask_data"].shape
if len(shape) != 2:
raise TypeError(error_str)
if not (
(val["mask_data"] >= 0).all() and (val["mask_data"] <= 255).all()
) and issubclass(val["mask_data"].dtype.type, np.integer):
raise TypeError("Mask data must be integers between 0 and 255")
# Optional argument
if "class_labels" in val:
for k, v in list(val["class_labels"].items()):
if (not isinstance(k, numbers.Number)) or (not isinstance(v, str)):
raise TypeError(
"Class labels must be a dictionary of numbers to strings"
)
return True | python | wandb/sdk/data_types/helper_types/image_mask.py | 210 | 234 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,829 | nice_id | def nice_id(name):
return ID_PREFIX + "-" + name | python | wandb/sdk/verify/verify.py | 29 | 30 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,830 | print_results | def print_results(
failed_test_or_tests: Optional[Union[str, List[str]]], warning: bool
) -> None:
if warning:
color = "yellow"
else:
color = "red"
if isinstance(failed_test_or_tests, str):
print(RED_X)
print(click.style(failed_test_or_tests, fg=color, bold=True))
elif isinstance(failed_test_or_tests, list) and len(failed_test_or_tests) > 0:
print(RED_X)
print(
"\n".join(
[click.style(f, fg=color, bold=True) for f in failed_test_or_tests]
)
)
else:
print(CHECKMARK) | python | wandb/sdk/verify/verify.py | 33 | 51 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,831 | check_host | def check_host(host: str) -> bool:
if host in ("api.wandb.ai", "http://api.wandb.ai", "https://api.wandb.ai"):
print_results("Cannot run wandb verify against api.wandb.ai", False)
return False
return True | python | wandb/sdk/verify/verify.py | 54 | 58 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,832 | check_logged_in | def check_logged_in(api: Api, host: str) -> bool:
print("Checking if logged in".ljust(72, "."), end="")
login_doc_url = "https://docs.wandb.ai/ref/cli/wandb-login"
fail_string = None
if api.api_key is None:
fail_string = (
"Not logged in. Please log in using `wandb login`. See the docs: {}".format(
click.style(login_doc_url, underline=True, fg="blue")
)
)
# check that api key is correct
# TODO: Better check for api key is correct
else:
res = api.api.viewer()
if not res:
fail_string = (
"Could not get viewer with default API key. "
f"Please relogin using `WANDB_BASE_URL={host} wandb login --relogin` and try again"
)
print_results(fail_string, False)
return fail_string is None | python | wandb/sdk/verify/verify.py | 61 | 82 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,833 | check_secure_requests | def check_secure_requests(url: str, test_url_string: str, failure_output: str) -> None:
# check if request is over https
print(test_url_string.ljust(72, "."), end="")
fail_string = None
if not url.startswith("https"):
fail_string = failure_output
print_results(fail_string, True) | python | wandb/sdk/verify/verify.py | 85 | 91 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,834 | check_cors_configuration | def check_cors_configuration(url: str, origin: str) -> None:
print("Checking CORs configuration of the bucket".ljust(72, "."), end="")
fail_string = None
res_get = requests.options(
url, headers={"Origin": origin, "Access-Control-Request-Method": "GET"}
)
if res_get.headers.get("Access-Control-Allow-Origin") is None:
fail_string = (
"Your object store does not have a valid CORs configuration, "
f"you must allow GET and PUT to Origin: {origin}"
)
print_results(fail_string, True) | python | wandb/sdk/verify/verify.py | 94 | 107 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,835 | check_run | def check_run(api: Api) -> bool:
print(
"Checking logged metrics, saving and downloading a file".ljust(72, "."), end=""
)
failed_test_strings = []
# set up config
n_epochs = 4
string_test = "A test config"
dict_test = {"config_val": 2, "config_string": "config string"}
list_test = [0, "one", "2"]
config = {
"epochs": n_epochs,
"stringTest": string_test,
"dictTest": dict_test,
"listTest": list_test,
}
# create a file to save
filepath = "./test with_special-characters.txt"
f = open(filepath, "w")
f.write("test")
f.close()
with wandb.init(
id=nice_id("check_run"), reinit=True, config=config, project=PROJECT_NAME
) as run:
run_id = run.id
entity = run.entity
logged = True
try:
for i in range(1, 11):
run.log({"loss": 1.0 / i}, step=i)
log_dict = {"val1": 1.0, "val2": 2}
run.log({"dict": log_dict}, step=i + 1)
except Exception:
logged = False
failed_test_strings.append(
"Failed to log values to run. Contact W&B for support."
)
try:
run.log({"HT%3ML ": wandb.Html('<a href="https://mysite">Link</a>')})
except Exception:
failed_test_strings.append(
"Failed to log to media. Contact W&B for support."
)
wandb.save(filepath)
public_api = wandb.Api()
prev_run = public_api.run(f"{entity}/{PROJECT_NAME}/{run_id}")
# raise Exception(prev_run.__dict__)
if prev_run is None:
failed_test_strings.append(
"Failed to access run through API. Contact W&B for support."
)
print_results(failed_test_strings, False)
return False
for key, value in prev_run.config.items():
if config[key] != value:
failed_test_strings.append(
"Read config values don't match run config. Contact W&B for support."
)
break
if logged and (
prev_run.history_keys["keys"]["loss"]["previousValue"] != 0.1
or prev_run.history_keys["lastStep"] != 11
or prev_run.history_keys["keys"]["dict.val1"]["previousValue"] != 1.0
or prev_run.history_keys["keys"]["dict.val2"]["previousValue"] != 2
):
failed_test_strings.append(
"History metrics don't match logged values. Check database encoding."
)
if logged and prev_run.summary["loss"] != 1.0 / 10:
failed_test_strings.append(
"Read summary values don't match expected value. Check database encoding, or contact W&B for support."
)
# TODO: (kdg) refactor this so it doesn't rely on an exception handler
try:
read_file = retry_fn(partial(prev_run.file, filepath))
# There's a race where the file hasn't been processed in the queue,
# we just retry until we get a download
read_file = retry_fn(partial(read_file.download, replace=True))
except Exception:
failed_test_strings.append(
"Unable to download file. Check SQS configuration, topic configuration and bucket permissions."
)
print_results(failed_test_strings, False)
return False
contents = read_file.read()
if contents != "test":
failed_test_strings.append(
"Contents of downloaded file do not match uploaded contents. Contact W&B for support."
)
print_results(failed_test_strings, False)
return len(failed_test_strings) == 0 | python | wandb/sdk/verify/verify.py | 110 | 206 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,836 | verify_manifest | def verify_manifest(
downloaded_manifest: Dict[str, Any],
computed_manifest: Dict[str, Any],
fails_list: List[str],
) -> None:
try:
for key in computed_manifest.keys():
assert (
computed_manifest[key]["digest"] == downloaded_manifest[key]["digest"]
)
assert computed_manifest[key]["size"] == downloaded_manifest[key]["size"]
except AssertionError:
fails_list.append(
"Artifact manifest does not appear as expected. Contact W&B for support."
) | python | wandb/sdk/verify/verify.py | 209 | 223 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,837 | verify_digest | def verify_digest(
downloaded: "ArtifactAPI", computed: "ArtifactAPI", fails_list: List[str]
) -> None:
if downloaded.digest != computed.digest:
fails_list.append(
"Artifact digest does not appear as expected. Contact W&B for support."
) | python | wandb/sdk/verify/verify.py | 226 | 232 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,838 | artifact_with_path_or_paths | def artifact_with_path_or_paths(
name: str, verify_dir: Optional[str] = None, singular: bool = False
) -> "Artifact":
art = wandb.Artifact(type="artsy", name=name)
# internal file
with open("verify_int_test.txt", "w") as f:
f.write("test 1")
f.close()
art.add_file(f.name)
if singular:
return art
if verify_dir is None:
verify_dir = "./"
with art.new_file("verify_a.txt") as f:
f.write("test 2")
if not os.path.exists(verify_dir):
os.makedirs(verify_dir)
with open(f"{verify_dir}/verify_1.txt", "w") as f:
f.write("1")
art.add_dir(verify_dir)
file3 = Path(verify_dir) / "verify_3.txt"
file3.write_text("3")
# reference to local file
art.add_reference(file3.resolve().as_uri())
return art | python | wandb/sdk/verify/verify.py | 235 | 261 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,839 | log_use_download_artifact | def log_use_download_artifact(
artifact: "Artifact",
alias: str,
name: str,
download_dir: str,
failed_test_strings: List[str],
add_extra_file: bool,
) -> Tuple[bool, Optional["ArtifactAPI"], List[str]]:
with wandb.init(
id=nice_id("log_artifact"),
reinit=True,
project=PROJECT_NAME,
config={"test": "artifact log"},
) as log_art_run:
if add_extra_file:
with open("verify_2.txt", "w") as f:
f.write("2")
f.close()
artifact.add_file(f.name)
try:
log_art_run.log_artifact(artifact, aliases=alias)
except Exception as e:
failed_test_strings.append(f"Unable to log artifact. {e}")
return False, None, failed_test_strings
with wandb.init(
id=nice_id("use_artifact"),
project=PROJECT_NAME,
config={"test": "artifact use"},
) as use_art_run:
try:
used_art = use_art_run.use_artifact(f"{name}:{alias}")
except Exception as e:
failed_test_strings.append(f"Unable to use artifact. {e}")
return False, None, failed_test_strings
try:
used_art.download(root=download_dir)
except Exception:
failed_test_strings.append(
"Unable to download artifact. Check bucket permissions."
)
return False, None, failed_test_strings
return True, used_art, failed_test_strings | python | wandb/sdk/verify/verify.py | 264 | 308 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,840 | check_artifacts | def check_artifacts() -> bool:
print("Checking artifact save and download workflows".ljust(72, "."), end="")
failed_test_strings: List[str] = []
# test checksum
sing_art_dir = "./verify_sing_art"
alias = "sing_art1"
name = "sing-artys"
singular_art = artifact_with_path_or_paths(name, singular=True)
cont_test, download_artifact, failed_test_strings = log_use_download_artifact(
singular_art, alias, name, sing_art_dir, failed_test_strings, False
)
if not cont_test or download_artifact is None:
print_results(failed_test_strings, False)
return False
try:
download_artifact.verify(root=sing_art_dir)
except ValueError:
failed_test_strings.append(
"Artifact does not contain expected checksum. Contact W&B for support."
)
# test manifest and digest
multi_art_dir = "./verify_art"
alias = "art1"
name = "my-artys"
art1 = artifact_with_path_or_paths(name, "./verify_art_dir", singular=False)
cont_test, download_artifact, failed_test_strings = log_use_download_artifact(
art1, alias, name, multi_art_dir, failed_test_strings, True
)
if not cont_test or download_artifact is None:
print_results(failed_test_strings, False)
return False
if set(os.listdir(multi_art_dir)) != {
"verify_a.txt",
"verify_2.txt",
"verify_1.txt",
"verify_3.txt",
"verify_int_test.txt",
}:
failed_test_strings.append(
"Artifact directory is missing files. Contact W&B for support."
)
computed = wandb.Artifact("computed", type="dataset")
computed.add_dir(multi_art_dir)
verify_digest(download_artifact, computed, failed_test_strings)
computed_manifest = computed.manifest.to_manifest_json()["contents"]
downloaded_manifest = download_artifact._load_manifest().to_manifest_json()[
"contents"
]
verify_manifest(downloaded_manifest, computed_manifest, failed_test_strings)
print_results(failed_test_strings, False)
return len(failed_test_strings) == 0 | python | wandb/sdk/verify/verify.py | 311 | 366 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,841 | check_graphql_put | def check_graphql_put(api: Api, host: str) -> Tuple[bool, Optional[str]]:
# check graphql endpoint using an upload
print("Checking signed URL upload".ljust(72, "."), end="")
failed_test_strings = []
gql_fp = "gql_test_file.txt"
f = open(gql_fp, "w")
f.write("test2")
f.close()
with wandb.init(
id=nice_id("graphql_put"),
reinit=True,
project=PROJECT_NAME,
config={"test": "put to graphql"},
) as run:
wandb.save(gql_fp)
public_api = wandb.Api()
prev_run = public_api.run(f"{run.entity}/{PROJECT_NAME}/{run.id}")
if prev_run is None:
failed_test_strings.append(
"Unable to access previous run through public API. Contact W&B for support."
)
print_results(failed_test_strings, False)
return False, None
# TODO: (kdg) refactor this so it doesn't rely on an exception handler
try:
read_file = retry_fn(partial(prev_run.file, gql_fp))
url = read_file.url
read_file = retry_fn(partial(read_file.download, replace=True))
except Exception:
failed_test_strings.append(
"Unable to read file successfully saved through a put request. Check SQS configurations, bucket permissions and topic configs."
)
print_results(failed_test_strings, False)
return False, None
contents = read_file.read()
try:
assert contents == "test2"
except AssertionError:
failed_test_strings.append(
"Read file contents do not match saved file contents. Contact W&B for support."
)
print_results(failed_test_strings, False)
return len(failed_test_strings) == 0, url | python | wandb/sdk/verify/verify.py | 369 | 412 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,842 | check_large_post | def check_large_post() -> bool:
print(
"Checking ability to send large payloads through proxy".ljust(72, "."), end=""
)
descy = "a" * int(10**7)
username = getpass.getuser()
failed_test_strings = []
query = gql(
"""
query Project($entity: String!, $name: String!, $runName: String!, $desc: String!){
project(entityName: $entity, name: $name) {
run(name: $runName, desc: $desc) {
name
summaryMetrics
}
}
}
"""
)
public_api = wandb.Api()
client = public_api._base_client
try:
client._get_result(
query,
variable_values={
"entity": username,
"name": PROJECT_NAME,
"runName": "",
"desc": descy,
},
timeout=60,
)
except Exception as e:
if isinstance(e, requests.HTTPError) and e.response.status_code == 413:
failed_test_strings.append(
'Failed to send a large payload. Check nginx.ingress.kubernetes.io/proxy-body-size is "0".'
)
else:
failed_test_strings.append(
f"Failed to send a large payload with error: {e}."
)
print_results(failed_test_strings, False)
return len(failed_test_strings) == 0 | python | wandb/sdk/verify/verify.py | 415 | 459 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,843 | check_wandb_version | def check_wandb_version(api: Api) -> None:
print("Checking wandb package version is up to date".ljust(72, "."), end="")
_, server_info = api.viewer_server_info()
fail_string = None
warning = False
max_cli_version = server_info.get("cliVersionInfo", {}).get("max_cli_version", None)
min_cli_version = server_info.get("cliVersionInfo", {}).get(
"min_cli_version", "0.0.1"
)
if parse_version(wandb.__version__) < parse_version(min_cli_version):
fail_string = "wandb version out of date, please run pip install --upgrade wandb=={}".format(
max_cli_version
)
elif parse_version(wandb.__version__) > parse_version(max_cli_version):
fail_string = (
"wandb version is not supported by your local installation. This could "
"cause some issues. If you're having problems try: please run `pip "
f"install --upgrade wandb=={max_cli_version}`"
)
warning = True
print_results(fail_string, warning) | python | wandb/sdk/verify/verify.py | 462 | 483 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,844 | retry_fn | def retry_fn(fn: Callable) -> Any:
ini_time = time.time()
res = None
i = 0
while i < MIN_RETRYS or time.time() - ini_time < GET_RUN_MAX_TIME:
i += 1
try:
res = fn()
break
except Exception:
time.sleep(1)
continue
return res | python | wandb/sdk/verify/verify.py | 486 | 498 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,845 | push_to_queue | def push_to_queue(
api: Api, queue_name: str, launch_spec: Dict[str, Any], project_queue: str
) -> Any:
try:
res = api.push_to_run_queue(queue_name, launch_spec, project_queue)
except Exception as e:
wandb.termwarn(f"{LOG_PREFIX}Exception when pushing to queue {e}")
return None
return res | python | wandb/sdk/launch/launch_add.py | 21 | 29 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,846 | launch_add | def launch_add(
uri: Optional[str] = None,
job: Optional[str] = None,
config: Optional[Dict[str, Any]] = None,
project: Optional[str] = None,
entity: Optional[str] = None,
queue_name: Optional[str] = None,
resource: Optional[str] = None,
entry_point: Optional[List[str]] = None,
name: Optional[str] = None,
version: Optional[str] = None,
docker_image: Optional[str] = None,
params: Optional[Dict[str, Any]] = None,
project_queue: Optional[str] = None,
resource_args: Optional[Dict[str, Any]] = None,
run_id: Optional[str] = None,
build: Optional[bool] = False,
repository: Optional[str] = None,
) -> "public.QueuedRun":
"""Enqueue a W&B launch experiment. With either a source uri, job or docker_image.
Arguments:
uri: URI of experiment to run. A wandb run uri or a Git repository URI.
job: string reference to a wandb.Job eg: wandb/test/my-job:latest
config: A dictionary containing the configuration for the run. May also contain
resource specific arguments under the key "resource_args"
project: Target project to send launched run to
entity: Target entity to send launched run to
queue: the name of the queue to enqueue the run to
resource: Execution backend for the run: W&B provides built-in support for "local-container" backend
entry_point: Entry point to run within the project. Defaults to using the entry point used
in the original run for wandb URIs, or main.py for git repository URIs.
name: Name run under which to launch the run.
version: For Git-based projects, either a commit hash or a branch name.
docker_image: The name of the docker image to use for the run.
params: Parameters (dictionary) for the entry point command. Defaults to using the
the parameters used to run the original run.
resource_args: Resource related arguments for launching runs onto a remote backend.
Will be stored on the constructed launch config under ``resource_args``.
run_id: optional string indicating the id of the launched run
build: optional flag defaulting to false, requires queue to be set
if build, an image is created, creates a job artifact, pushes a reference
to that job artifact to queue
repository: optional string to control the name of the remote repository, used when
pushing images to a registry
project_queue: optional string to control the name of the project for the queue. Primarily used
for back compatibility with project scoped queues
Example:
import wandb
project_uri = "https://github.com/wandb/examples"
params = {"alpha": 0.5, "l1_ratio": 0.01}
# Run W&B project and create a reproducible docker environment
# on a local host
api = wandb.apis.internal.Api()
wandb.launch_add(uri=project_uri, parameters=params)
Returns:
an instance of`wandb.api.public.QueuedRun` which gives information about the
queued run, or if `wait_until_started` or `wait_until_finished` are called, gives access
to the underlying Run information.
Raises:
`wandb.exceptions.LaunchError` if unsuccessful
"""
api = Api()
return _launch_add(
api,
uri,
job,
config,
project,
entity,
queue_name,
resource,
entry_point,
name,
version,
docker_image,
params,
project_queue,
resource_args,
run_id=run_id,
build=build,
repository=repository,
) | python | wandb/sdk/launch/launch_add.py | 32 | 120 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,847 | _launch_add | def _launch_add(
api: Api,
uri: Optional[str],
job: Optional[str],
config: Optional[Dict[str, Any]],
project: Optional[str],
entity: Optional[str],
queue_name: Optional[str],
resource: Optional[str],
entry_point: Optional[List[str]],
name: Optional[str],
version: Optional[str],
docker_image: Optional[str],
params: Optional[Dict[str, Any]],
project_queue: Optional[str],
resource_args: Optional[Dict[str, Any]] = None,
run_id: Optional[str] = None,
build: Optional[bool] = False,
repository: Optional[str] = None,
) -> "public.QueuedRun":
launch_spec = construct_launch_spec(
uri,
job,
api,
name,
project,
entity,
docker_image,
resource,
entry_point,
version,
params,
resource_args,
config,
run_id,
repository,
)
if build:
if resource == "local-process":
raise LaunchError(
"Cannot build a docker image for the resource: local-process"
)
if launch_spec.get("job") is not None:
wandb.termwarn("Build doesn't support setting a job. Overwriting job.")
launch_spec["job"] = None
launch_project = create_project_from_spec(launch_spec, api)
docker_image_uri = build_image_from_project(launch_project, api, config or {})
run = wandb.run or wandb.init(
project=launch_spec["project"],
entity=launch_spec["entity"],
job_type="launch_job",
)
args = compute_command_args(launch_project.override_args)
job_artifact = run._log_job_artifact_with_image(docker_image_uri, args)
job_name = job_artifact.wait().name
job = f"{launch_spec['entity']}/{launch_spec['project']}/{job_name}"
launch_spec["job"] = job
launch_spec["uri"] = None # Remove given URI --> now in job
if queue_name is None:
queue_name = "default"
if project_queue is None:
project_queue = LAUNCH_DEFAULT_PROJECT
validate_launch_spec_source(launch_spec)
res = push_to_queue(api, queue_name, launch_spec, project_queue)
if res is None or "runQueueItemId" not in res:
raise LaunchError("Error adding run to queue")
updated_spec = res.get("runSpec")
if updated_spec:
if updated_spec.get("resource_args"):
launch_spec["resource_args"] = updated_spec.get("resource_args")
if updated_spec.get("resource"):
launch_spec["resource"] = updated_spec.get("resource")
if project_queue == LAUNCH_DEFAULT_PROJECT:
wandb.termlog(f"{LOG_PREFIX}Added run to queue {queue_name}.")
else:
wandb.termlog(f"{LOG_PREFIX}Added run to queue {project_queue}/{queue_name}.")
wandb.termlog(f"{LOG_PREFIX}Launch spec:\n{pprint.pformat(launch_spec)}\n")
public_api = public.Api()
container_job = False
if job:
job_artifact = public_api.job(job)
if job_artifact._source_info.get("source_type") == "image":
container_job = True
queued_run = public_api.queued_run(
launch_spec["entity"],
launch_spec["project"],
queue_name,
res["runQueueItemId"],
container_job,
project_queue,
)
return queued_run # type: ignore | python | wandb/sdk/launch/launch_add.py | 123 | 225 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,848 | is_bare | def is_bare(self) -> bool:
return self.host is None | python | wandb/sdk/launch/wandb_reference.py | 53 | 54 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,849 | is_job | def is_job(self) -> bool:
return self.ref_type == ReferenceType.JOB | python | wandb/sdk/launch/wandb_reference.py | 56 | 57 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,850 | is_run | def is_run(self) -> bool:
return self.ref_type == ReferenceType.RUN | python | wandb/sdk/launch/wandb_reference.py | 59 | 60 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,851 | is_job_or_run | def is_job_or_run(self) -> bool:
return self.is_job() or self.is_run() | python | wandb/sdk/launch/wandb_reference.py | 62 | 63 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,852 | job_reference | def job_reference(self) -> str:
assert self.is_job()
return f"{self.job_name}:{self.job_alias}" | python | wandb/sdk/launch/wandb_reference.py | 65 | 67 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,853 | job_reference_scoped | def job_reference_scoped(self) -> str:
assert self.entity
assert self.project
unscoped = self.job_reference()
return f"{self.entity}/{self.project}/{unscoped}" | python | wandb/sdk/launch/wandb_reference.py | 69 | 73 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,854 | url_host | def url_host(self) -> str:
return f"{PREFIX_HTTPS}{self.host}" if self.host else "" | python | wandb/sdk/launch/wandb_reference.py | 75 | 76 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,855 | url_entity | def url_entity(self) -> str:
assert self.entity
return f"{self.url_host()}/{self.entity}" | python | wandb/sdk/launch/wandb_reference.py | 78 | 80 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,856 | url_project | def url_project(self) -> str:
assert self.project
return f"{self.url_entity()}/{self.project}" | python | wandb/sdk/launch/wandb_reference.py | 82 | 84 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,857 | parse | def parse(uri: str) -> Optional["WandbReference"]:
"""Attempt to parse a string as a W&B URL."""
# TODO: Error if HTTP and host is not localhost?
if (
not uri.startswith("/")
and not uri.startswith(PREFIX_HTTP)
and not uri.startswith(PREFIX_HTTPS)
):
return None
ref = WandbReference()
# This takes care of things like query and fragment
parsed = urlparse(uri)
if parsed.netloc:
ref.host = parsed.netloc
if not parsed.path.startswith("/"):
return ref
ref.path = parsed.path[1:]
parts = ref.path.split("/")
if len(parts) > 0:
if parts[0] not in RESERVED_NON_ENTITIES:
ref.path = None
ref.entity = parts[0]
if len(parts) > 1:
if parts[1] not in RESERVED_NON_PROJECTS:
ref.project = parts[1]
if len(parts) > 3 and parts[2] == "runs":
ref.ref_type = ReferenceType.RUN
ref.run_id = parts[3]
elif (
len(parts) > 4
and parts[2] == "artifacts"
and parts[3] == "job"
):
ref.ref_type = ReferenceType.JOB
ref.job_name = parts[4]
if len(parts) > 5 and parts[5] not in RESERVED_JOB_PATHS:
ref.job_alias = parts[5]
# TODO: Right now we are not tracking selection as part of URL state in the Jobs tab.
# If that changes we'll want to update this.
return ref | python | wandb/sdk/launch/wandb_reference.py | 87 | 131 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,858 | is_uri_job_or_run | def is_uri_job_or_run(uri: str) -> bool:
ref = WandbReference.parse(uri)
if ref and ref.is_job_or_run():
return True
return False | python | wandb/sdk/launch/wandb_reference.py | 134 | 138 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,859 | __init__ | def __init__(
self,
uri: Optional[str],
job: Optional[str],
api: Api,
launch_spec: Dict[str, Any],
target_entity: str,
target_project: str,
name: Optional[str],
docker_config: Dict[str, Any],
git_info: Dict[str, str],
overrides: Dict[str, Any],
resource: str,
resource_args: Dict[str, Any],
run_id: Optional[str],
):
if uri is not None and utils.is_bare_wandb_uri(uri):
uri = api.settings("base_url") + uri
_logger.info(f"{LOG_PREFIX}Updating uri with base uri: {uri}")
self.uri = uri
self.job = job
if job is not None:
wandb.termlog(f"{LOG_PREFIX}Launching job: {job}")
self._job_artifact: Optional[PublicArtifact] = None
self.api = api
self.launch_spec = launch_spec
self.target_entity = target_entity
self.target_project = target_project.lower()
self.name = name # TODO: replace with run_id
# the builder key can be passed in through the resource args
# but these resource_args are then passed to the appropriate
# runner, so we need to pop the builder key out
resource_args_build = resource_args.get(resource, {}).pop("builder", {})
self.resource = resource
self.resource_args = resource_args
self.python_version: Optional[str] = launch_spec.get("python_version")
self.cuda_base_image: Optional[str] = resource_args_build.get("cuda", {}).get(
"base_image"
)
self._base_image: Optional[str] = launch_spec.get("base_image")
self.docker_image: Optional[str] = docker_config.get(
"docker_image"
) or launch_spec.get("image_uri")
uid = RESOURCE_UID_MAP.get(resource, 1000)
if self._base_image:
uid = docker.get_image_uid(self._base_image)
_logger.info(f"{LOG_PREFIX}Retrieved base image uid {uid}")
self.docker_user_id: int = docker_config.get("user_id", uid)
self.git_version: Optional[str] = git_info.get("version")
self.git_repo: Optional[str] = git_info.get("repo")
self.override_args: Dict[str, Any] = overrides.get("args", {})
self.override_config: Dict[str, Any] = overrides.get("run_config", {})
self.override_artifacts: Dict[str, Any] = overrides.get("artifacts", {})
self.override_entrypoint: Optional[EntryPoint] = None
self.deps_type: Optional[str] = None
self._runtime: Optional[str] = None
self.run_id = run_id or generate_id()
self._entry_points: Dict[
str, EntryPoint
] = {} # todo: keep multiple entrypoint support?
if overrides.get("entry_point"):
_logger.info("Adding override entry point")
self.override_entrypoint = self.add_entry_point(
overrides.get("entry_point") # type: ignore
)
if self.docker_image is not None:
self.source = LaunchSource.DOCKER
self.project_dir = None
elif self.job is not None:
self.source = LaunchSource.JOB
self.project_dir = tempfile.mkdtemp()
elif self.uri is not None and utils._is_wandb_uri(self.uri):
_logger.info(f"URI {self.uri} indicates a wandb uri")
self.source = LaunchSource.WANDB
self.project_dir = tempfile.mkdtemp()
elif self.uri is not None and utils._is_git_uri(self.uri):
_logger.info(f"URI {self.uri} indicates a git uri")
self.source = LaunchSource.GIT
self.project_dir = tempfile.mkdtemp()
elif self.uri is not None and "placeholder-" in self.uri:
wandb.termlog(
f"{LOG_PREFIX}Launch received placeholder URI, replacing with local path."
)
self.uri = os.getcwd()
self.source = LaunchSource.LOCAL
self.project_dir = self.uri
else:
_logger.info(f"URI {self.uri} indicates a local uri")
# assume local
if self.uri is not None and not os.path.exists(self.uri):
raise LaunchError(
"Assumed URI supplied is a local path but path is not valid"
)
self.source = LaunchSource.LOCAL
self.project_dir = self.uri
self.aux_dir = tempfile.mkdtemp() | python | wandb/sdk/launch/_project_spec.py | 48 | 145 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,860 | base_image | def base_image(self) -> str:
"""Returns {PROJECT}_base:{PYTHON_VERSION}."""
# TODO: this should likely be source_project when we have it...
# don't make up a separate base image name if user provides a docker image
if self.docker_image is not None:
return self.docker_image
python_version = (self.python_version or "3").replace("+", "dev")
generated_name = "{}_base:{}".format(
self.target_project.replace(" ", "-"), python_version
)
return self._base_image or generated_name | python | wandb/sdk/launch/_project_spec.py | 148 | 160 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,861 | image_name | def image_name(self) -> str:
if self.docker_image is not None:
return self.docker_image
elif self.uri is not None:
cleaned_uri = self.uri.replace("https://", "/")
first_sep = cleaned_uri.find("/")
shortened_uri = cleaned_uri[first_sep:]
return wandb.util.make_docker_image_name_safe(shortened_uri)
else:
# this will always pass since one of these 3 is required
assert self.job is not None
return wandb.util.make_docker_image_name_safe(self.job.split(":")[0]) | python | wandb/sdk/launch/_project_spec.py | 163 | 174 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,862 | build_required | def build_required(self) -> bool:
"""Checks the source to see if a build is required."""
# since the image tag for images built from jobs
# is based on the job version index, which is immutable
# we don't need to build the image for a job if that tag
# already exists
if self.source != LaunchSource.JOB:
return True
return False | python | wandb/sdk/launch/_project_spec.py | 176 | 184 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,863 | docker_image | def docker_image(self) -> Optional[str]:
return self._docker_image | python | wandb/sdk/launch/_project_spec.py | 187 | 188 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,864 | docker_image | def docker_image(self, value: str) -> None:
self._docker_image = value
self._ensure_not_docker_image_and_local_process() | python | wandb/sdk/launch/_project_spec.py | 191 | 193 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,865 | get_single_entry_point | def get_single_entry_point(self) -> Optional["EntryPoint"]:
"""Returns the first entrypoint for the project, or None if no entry point was provided because a docker image was provided."""
# assuming project only has 1 entry point, pull that out
# tmp fn until we figure out if we want to support multiple entry points or not
if not self._entry_points:
if not self.docker_image:
raise LaunchError(
"Project must have at least one entry point unless docker image is specified."
)
return None
return list(self._entry_points.values())[0] | python | wandb/sdk/launch/_project_spec.py | 195 | 205 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,866 | add_entry_point | def add_entry_point(self, command: List[str]) -> "EntryPoint":
"""Add an entry point to the project."""
entry_point = command[-1]
new_entrypoint = EntryPoint(name=entry_point, command=command)
self._entry_points[entry_point] = new_entrypoint
return new_entrypoint | python | wandb/sdk/launch/_project_spec.py | 207 | 212 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,867 | _ensure_not_docker_image_and_local_process | def _ensure_not_docker_image_and_local_process(self) -> None:
if self.docker_image is not None and self.resource == "local-process":
raise LaunchError(
"Cannot specify docker image with local-process resource runner"
) | python | wandb/sdk/launch/_project_spec.py | 214 | 218 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,868 | _fetch_job | def _fetch_job(self) -> None:
public_api = wandb.apis.public.Api()
job_dir = tempfile.mkdtemp()
try:
job = public_api.job(self.job, path=job_dir)
except CommError:
raise LaunchError(
f"Job {self.job} not found. Jobs have the format: <entity>/<project>/<name>:<alias>"
)
job.configure_launch_project(self)
self._job_artifact = job._job_artifact | python | wandb/sdk/launch/_project_spec.py | 220 | 230 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,869 | get_image_source_string | def get_image_source_string(self) -> str:
"""Returns a unique string identifying the source of an image."""
if self.source == LaunchSource.LOCAL:
# TODO: more correct to get a hash of local uri contents
assert isinstance(self.uri, str)
return self.uri
elif self.source == LaunchSource.JOB:
assert self._job_artifact is not None
return f"{self._job_artifact.name}:v{self._job_artifact.version}"
elif self.source == LaunchSource.GIT:
assert isinstance(self.uri, str)
ret = self.uri
if self.git_version:
ret += self.git_version
return ret
elif self.source == LaunchSource.WANDB:
assert isinstance(self.uri, str)
return self.uri
elif self.source == LaunchSource.DOCKER:
assert isinstance(self.docker_image, str)
_logger.debug("")
return self.docker_image
else:
raise LaunchError("Unknown source type when determing image source string") | python | wandb/sdk/launch/_project_spec.py | 232 | 255 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,870 | _fetch_project_local | def _fetch_project_local(self, internal_api: Api) -> None:
"""Fetch a project (either wandb run or git repo) into a local directory, returning the path to the local project directory."""
# these asserts are all guaranteed to pass, but are required by mypy
assert self.source != LaunchSource.LOCAL and self.source != LaunchSource.JOB
assert isinstance(self.uri, str)
assert self.project_dir is not None
_logger.info("Fetching project locally...")
if utils._is_wandb_uri(self.uri):
source_entity, source_project, source_run_name = utils.parse_wandb_uri(
self.uri
)
run_info = utils.fetch_wandb_project_run_info(
source_entity, source_project, source_run_name, internal_api
)
program_name = run_info.get("codePath") or run_info["program"]
self.python_version = run_info.get("python", "3")
downloaded_code_artifact = utils.check_and_download_code_artifacts(
source_entity,
source_project,
source_run_name,
internal_api,
self.project_dir,
)
if not downloaded_code_artifact:
if not run_info["git"]:
raise LaunchError(
"Reproducing a run requires either an associated git repo or a code artifact logged with `run.log_code()`"
)
branch_name = utils._fetch_git_repo(
self.project_dir,
run_info["git"]["remote"],
run_info["git"]["commit"],
)
if self.git_version is None:
self.git_version = branch_name
patch = utils.fetch_project_diff(
source_entity, source_project, source_run_name, internal_api
)
if patch:
utils.apply_patch(patch, self.project_dir)
# For cases where the entry point wasn't checked into git
if not os.path.exists(os.path.join(self.project_dir, program_name)):
downloaded_entrypoint = utils.download_entry_point(
source_entity,
source_project,
source_run_name,
internal_api,
program_name,
self.project_dir,
)
if not downloaded_entrypoint:
raise LaunchError(
f"Entrypoint file: {program_name} does not exist, "
"and could not be downloaded. Please specify the entrypoint for this run."
)
if (
"_session_history.ipynb" in os.listdir(self.project_dir)
or ".ipynb" in program_name
):
program_name = utils.convert_jupyter_notebook_to_script(
program_name, self.project_dir
)
# Download any frozen requirements
utils.download_wandb_python_deps(
source_entity,
source_project,
source_run_name,
internal_api,
self.project_dir,
)
if not self._entry_points:
_, ext = os.path.splitext(program_name)
if ext == ".py":
entry_point = ["python", program_name]
elif ext == ".sh":
command = os.environ.get("SHELL", "bash")
entry_point = [command, program_name]
else:
raise LaunchError(f"Unsupported entrypoint: {program_name}")
self.add_entry_point(entry_point)
self.override_args = utils.merge_parameters(
self.override_args, run_info["args"]
)
else:
assert utils._GIT_URI_REGEX.match(self.uri), (
"Non-wandb URI %s should be a Git URI" % self.uri
)
if not self._entry_points:
wandb.termlog(
f"{LOG_PREFIX}Entry point for repo not specified, defaulting to python main.py"
)
self.add_entry_point(EntrypointDefaults.PYTHON)
branch_name = utils._fetch_git_repo(
self.project_dir, self.uri, self.git_version
)
if self.git_version is None:
self.git_version = branch_name | python | wandb/sdk/launch/_project_spec.py | 257 | 359 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,871 | __init__ | def __init__(self, name: str, command: List[str]):
self.name = name
self.command = command | python | wandb/sdk/launch/_project_spec.py | 365 | 367 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,872 | compute_command | def compute_command(self, user_parameters: Optional[Dict[str, Any]]) -> List[str]:
"""Converts user parameter dictionary to a string."""
command_arr = []
command_arr += self.command
extras = compute_command_args(user_parameters)
command_arr += extras
return command_arr | python | wandb/sdk/launch/_project_spec.py | 369 | 375 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,873 | compute_command_args | def compute_command_args(parameters: Optional[Dict[str, Any]]) -> List[str]:
arr: List[str] = []
if parameters is None:
return arr
for key, value in parameters.items():
if value is not None:
arr.append(f"--{key}")
arr.append(quote(str(value)))
else:
arr.append(f"--{key}")
return arr | python | wandb/sdk/launch/_project_spec.py | 378 | 388 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,874 | get_entry_point_command | def get_entry_point_command(
entry_point: Optional["EntryPoint"], parameters: Dict[str, Any]
) -> List[str]:
"""Returns the shell command to execute in order to run the specified entry point.
Arguments:
entry_point: Entry point to run
parameters: Parameters (dictionary) for the entry point command
Returns:
List of strings representing the shell command to be executed
"""
if entry_point is None:
return []
return entry_point.compute_command(parameters) | python | wandb/sdk/launch/_project_spec.py | 391 | 405 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,875 | create_project_from_spec | def create_project_from_spec(launch_spec: Dict[str, Any], api: Api) -> LaunchProject:
"""Constructs a LaunchProject instance using a launch spec.
Arguments:
launch_spec: Dictionary representation of launch spec
api: Instance of wandb.apis.internal Api
Returns:
An initialized `LaunchProject` object
"""
name: Optional[str] = None
if launch_spec.get("name"):
name = launch_spec["name"]
return LaunchProject(
launch_spec.get("uri"),
launch_spec.get("job"),
api,
launch_spec,
launch_spec["entity"],
launch_spec["project"],
name,
launch_spec.get("docker", {}),
launch_spec.get("git", {}),
launch_spec.get("overrides", {}),
launch_spec.get("resource", None),
launch_spec.get("resource_args", {}),
launch_spec.get("run_id", None),
) | python | wandb/sdk/launch/_project_spec.py | 408 | 435 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,876 | fetch_and_validate_project | def fetch_and_validate_project(
launch_project: LaunchProject, api: Api
) -> LaunchProject:
"""Fetches a project into a local directory, adds the config values to the directory, and validates the first entrypoint for the project.
Arguments:
launch_project: LaunchProject to fetch and validate.
api: Instance of wandb.apis.internal Api
Returns:
A validated `LaunchProject` object.
"""
if launch_project.source == LaunchSource.DOCKER:
return launch_project
if launch_project.source == LaunchSource.LOCAL:
if not launch_project._entry_points:
wandb.termlog(
f"{LOG_PREFIX}Entry point for repo not specified, defaulting to `python main.py`"
)
launch_project.add_entry_point(EntrypointDefaults.PYTHON)
elif launch_project.source == LaunchSource.JOB:
launch_project._fetch_job()
else:
launch_project._fetch_project_local(internal_api=api)
assert launch_project.project_dir is not None
# this prioritizes pip, and we don't support any cases where both are present
# conda projects when uploaded to wandb become pip projects via requirements.frozen.txt, wandb doesn't preserve conda envs
if os.path.exists(
os.path.join(launch_project.project_dir, "requirements.txt")
) or os.path.exists(
os.path.join(launch_project.project_dir, "requirements.frozen.txt")
):
launch_project.deps_type = "pip"
elif os.path.exists(os.path.join(launch_project.project_dir, "environment.yml")):
launch_project.deps_type = "conda"
return launch_project | python | wandb/sdk/launch/_project_spec.py | 438 | 476 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,877 | create_metadata_file | def create_metadata_file(
launch_project: LaunchProject,
image_uri: str,
sanitized_entrypoint_str: str,
sanitized_dockerfile_contents: str,
) -> None:
assert launch_project.project_dir is not None
with open(
os.path.join(launch_project.project_dir, DEFAULT_LAUNCH_METADATA_PATH),
"w",
) as f:
json.dump(
{
**launch_project.launch_spec,
"image_uri": image_uri,
"command": sanitized_entrypoint_str,
"dockerfile_contents": sanitized_dockerfile_contents,
},
f,
) | python | wandb/sdk/launch/_project_spec.py | 479 | 498 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,878 | resolve_agent_config | def resolve_agent_config( # noqa: C901
api: Api,
entity: Optional[str],
project: Optional[str],
max_jobs: Optional[int],
queues: Optional[Tuple[str]],
config: Optional[str],
) -> Tuple[Dict[str, Any], Api]:
"""Resolve the agent config.
Arguments:
api (Api): The api.
entity (str): The entity.
project (str): The project.
max_jobs (int): The max number of jobs.
queues (Tuple[str]): The queues.
config (str): The config.
Returns:
Tuple[Dict[str, Any], Api]: The resolved config and api.
"""
defaults = {
"entity": api.default_entity,
"project": LAUNCH_DEFAULT_PROJECT,
"max_jobs": 1,
"max_schedulers": 1,
"queues": [],
"api_key": api.api_key,
"base_url": api.settings("base_url"),
"registry": {},
"builder": {},
"runner": {},
}
user_set_project = False
resolved_config: Dict[str, Any] = defaults
config_path = config or os.path.expanduser(LAUNCH_CONFIG_FILE)
if os.path.isfile(config_path):
launch_config = {}
with open(config_path) as f:
try:
launch_config = yaml.safe_load(f)
except yaml.YAMLError as e:
raise LaunchError(f"Invalid launch agent config: {e}")
if launch_config.get("project") is not None:
user_set_project = True
resolved_config.update(launch_config.items())
elif config is not None:
raise LaunchError(
f"Could not find use specified launch config file: {config_path}"
)
if os.environ.get("WANDB_PROJECT") is not None:
resolved_config.update({"project": os.environ.get("WANDB_PROJECT")})
user_set_project = True
if os.environ.get("WANDB_ENTITY") is not None:
resolved_config.update({"entity": os.environ.get("WANDB_ENTITY")})
if os.environ.get("WANDB_API_KEY") is not None:
resolved_config.update({"api_key": os.environ.get("WANDB_API_KEY")})
if os.environ.get("WANDB_LAUNCH_MAX_JOBS") is not None:
resolved_config.update(
{"max_jobs": int(os.environ.get("WANDB_LAUNCH_MAX_JOBS", 1))}
)
if os.environ.get("WANDB_BASE_URL") is not None:
resolved_config.update({"base_url": os.environ.get("WANDB_BASE_URL")})
if project is not None:
resolved_config.update({"project": project})
user_set_project = True
if entity is not None:
resolved_config.update({"entity": entity})
if max_jobs is not None:
resolved_config.update({"max_jobs": int(max_jobs)})
if queues:
resolved_config.update({"queues": list(queues)})
# queue -> queues
if resolved_config.get("queue"):
if type(resolved_config.get("queue")) == str:
resolved_config["queues"].append(resolved_config["queue"])
else:
raise LaunchError(
f"Invalid launch agent config for key 'queue' with type: {type(resolved_config.get('queue'))}"
+ " (expected str). Specify multiple queues with the 'queues' key"
)
if (
resolved_config["entity"] != defaults["entity"]
or resolved_config["api_key"] != defaults["api_key"]
or resolved_config["base_url"] != defaults["base_url"]
):
settings = dict(
api_key=resolved_config["api_key"],
base_url=resolved_config["base_url"],
project=resolved_config["project"],
entity=resolved_config["entity"],
)
api = Api(default_settings=settings)
if user_set_project:
wandb.termwarn(
"Specifying a project for the launch agent is deprecated. Please use queues found in the Launch application at https://wandb.ai/launch."
)
return resolved_config, api | python | wandb/sdk/launch/launch.py | 28 | 129 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,879 | create_and_run_agent | def create_and_run_agent(
api: Api,
config: Dict[str, Any],
) -> None:
agent = LaunchAgent(api, config)
agent.loop() | python | wandb/sdk/launch/launch.py | 132 | 137 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,880 | _run | def _run(
uri: Optional[str],
job: Optional[str],
name: Optional[str],
project: Optional[str],
entity: Optional[str],
docker_image: Optional[str],
entry_point: Optional[List[str]],
version: Optional[str],
parameters: Optional[Dict[str, Any]],
resource: str,
resource_args: Optional[Dict[str, Any]],
launch_config: Optional[Dict[str, Any]],
synchronous: Optional[bool],
api: Api,
run_id: Optional[str],
repository: Optional[str],
) -> AbstractRun:
"""Helper that delegates to the project-running method corresponding to the passed-in backend."""
launch_spec = construct_launch_spec(
uri,
job,
api,
name,
project,
entity,
docker_image,
resource,
entry_point,
version,
parameters,
resource_args,
launch_config,
run_id,
repository,
)
validate_launch_spec_source(launch_spec)
launch_project = create_project_from_spec(launch_spec, api)
launch_project = fetch_and_validate_project(launch_project, api)
# construct runner config.
runner_config: Dict[str, Any] = {}
runner_config[PROJECT_SYNCHRONOUS] = synchronous
config = launch_config or {}
build_config, registry_config = construct_builder_args(config)
environment = loader.environment_from_config(config.get("environment", {}))
registry = loader.registry_from_config(registry_config, environment)
builder = loader.builder_from_config(build_config, environment, registry)
backend = loader.runner_from_config(resource, api, runner_config, environment)
if backend:
submitted_run = backend.run(launch_project, builder)
# this check will always pass, run is only optional in the agent case where
# a run queue id is present on the backend config
assert submitted_run
return submitted_run
else:
raise ExecutionError(
f"Unavailable backend {resource}, available backends: {', '.join(loader.WANDB_RUNNERS)}"
) | python | wandb/sdk/launch/launch.py | 140 | 200 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,881 | run | def run(
api: Api,
uri: Optional[str] = None,
job: Optional[str] = None,
entry_point: Optional[List[str]] = None,
version: Optional[str] = None,
parameters: Optional[Dict[str, Any]] = None,
name: Optional[str] = None,
resource: Optional[str] = None,
resource_args: Optional[Dict[str, Any]] = None,
project: Optional[str] = None,
entity: Optional[str] = None,
docker_image: Optional[str] = None,
config: Optional[Dict[str, Any]] = None,
synchronous: Optional[bool] = True,
run_id: Optional[str] = None,
repository: Optional[str] = None,
) -> AbstractRun:
"""Run a W&B launch experiment. The project can be wandb uri or a Git URI.
Arguments:
uri: URI of experiment to run. A wandb run uri or a Git repository URI.
job: string reference to a wandb.Job eg: wandb/test/my-job:latest
api: An instance of a wandb Api from wandb.apis.internal.
entry_point: Entry point to run within the project. Defaults to using the entry point used
in the original run for wandb URIs, or main.py for git repository URIs.
version: For Git-based projects, either a commit hash or a branch name.
parameters: Parameters (dictionary) for the entry point command. Defaults to using the
the parameters used to run the original run.
name: Name run under which to launch the run.
resource: Execution backend for the run.
resource_args: Resource related arguments for launching runs onto a remote backend.
Will be stored on the constructed launch config under ``resource_args``.
project: Target project to send launched run to
entity: Target entity to send launched run to
config: A dictionary containing the configuration for the run. May also contain
resource specific arguments under the key "resource_args".
synchronous: Whether to block while waiting for a run to complete. Defaults to True.
Note that if ``synchronous`` is False and ``backend`` is "local-container", this
method will return, but the current process will block when exiting until
the local run completes. If the current process is interrupted, any
asynchronous runs launched via this method will be terminated. If
``synchronous`` is True and the run fails, the current process will
error out as well.
run_id: ID for the run (To ultimately replace the :name: field)
repository: string name of repository path for remote registry
Example:
import wandb
project_uri = "https://github.com/wandb/examples"
params = {"alpha": 0.5, "l1_ratio": 0.01}
# Run W&B project and create a reproducible docker environment
# on a local host
api = wandb.apis.internal.Api()
wandb.launch(project_uri, api, parameters=params)
Returns:
an instance of`wandb.launch.SubmittedRun` exposing information (e.g. run ID)
about the launched run.
Raises:
`wandb.exceptions.ExecutionError` If a run launched in blocking mode
is unsuccessful.
"""
if config is None:
config = {}
# default to local container for runs without a queue
if resource is None:
resource = "local-container"
submitted_run_obj = _run(
uri=uri,
job=job,
name=name,
project=project,
entity=entity,
docker_image=docker_image,
entry_point=entry_point,
version=version,
parameters=parameters,
resource=resource,
resource_args=resource_args,
launch_config=config,
synchronous=synchronous,
api=api,
run_id=run_id,
repository=repository,
)
return submitted_run_obj | python | wandb/sdk/launch/launch.py | 203 | 294 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,882 | _wait_for | def _wait_for(submitted_run_obj: AbstractRun) -> None:
"""Wait on the passed-in submitted run, reporting its status to the tracking server."""
# Note: there's a small chance we fail to report the run's status to the tracking server if
# we're interrupted before we reach the try block below
try:
if submitted_run_obj.wait():
_logger.info("=== Submitted run succeeded ===")
else:
raise ExecutionError("Submitted run failed")
except KeyboardInterrupt:
_logger.error("=== Submitted run interrupted, cancelling run ===")
submitted_run_obj.cancel()
raise | python | wandb/sdk/launch/launch.py | 297 | 309 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,883 | _is_wandb_uri | def _is_wandb_uri(uri: str) -> bool:
return (
_WANDB_URI_REGEX.match(uri)
or _WANDB_DEV_URI_REGEX.match(uri)
or _WANDB_LOCAL_DEV_URI_REGEX.match(uri)
or _WANDB_QA_URI_REGEX.match(uri)
) is not None | python | wandb/sdk/launch/utils.py | 85 | 91 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,884 | _is_wandb_dev_uri | def _is_wandb_dev_uri(uri: str) -> bool:
return bool(_WANDB_DEV_URI_REGEX.match(uri)) | python | wandb/sdk/launch/utils.py | 94 | 95 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,885 | _is_wandb_local_uri | def _is_wandb_local_uri(uri: str) -> bool:
return bool(_WANDB_LOCAL_DEV_URI_REGEX.match(uri)) | python | wandb/sdk/launch/utils.py | 98 | 99 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,886 | _is_git_uri | def _is_git_uri(uri: str) -> bool:
return bool(_GIT_URI_REGEX.match(uri)) | python | wandb/sdk/launch/utils.py | 102 | 103 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,887 | sanitize_wandb_api_key | def sanitize_wandb_api_key(s: str) -> str:
return str(re.sub(API_KEY_REGEX, "WANDB_API_KEY", s)) | python | wandb/sdk/launch/utils.py | 106 | 107 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,888 | get_project_from_job | def get_project_from_job(job: str) -> Optional[str]:
job_parts = job.split("/")
if len(job_parts) == 3:
return job_parts[1]
return None | python | wandb/sdk/launch/utils.py | 110 | 114 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,889 | set_project_entity_defaults | def set_project_entity_defaults(
uri: Optional[str],
job: Optional[str],
api: Api,
project: Optional[str],
entity: Optional[str],
launch_config: Optional[Dict[str, Any]],
) -> Tuple[str, str]:
# set the target project and entity if not provided
source_uri = None
if uri is not None:
if _is_wandb_uri(uri):
_, source_uri, _ = parse_wandb_uri(uri)
elif _is_git_uri(uri):
source_uri = os.path.splitext(os.path.basename(uri))[0]
elif job is not None:
source_uri = get_project_from_job(job)
if project is None:
config_project = None
if launch_config:
config_project = launch_config.get("project")
project = config_project or source_uri or UNCATEGORIZED_PROJECT
if entity is None:
config_entity = None
if launch_config:
config_entity = launch_config.get("entity")
entity = config_entity or api.default_entity
prefix = ""
if platform.system() != "Windows" and sys.stdout.encoding == "UTF-8":
prefix = "🚀 "
wandb.termlog(f"{LOG_PREFIX}{prefix}Launching run into {entity}/{project}")
return project, entity | python | wandb/sdk/launch/utils.py | 117 | 148 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,890 | construct_launch_spec | def construct_launch_spec(
uri: Optional[str],
job: Optional[str],
api: Api,
name: Optional[str],
project: Optional[str],
entity: Optional[str],
docker_image: Optional[str],
resource: Optional[str],
entry_point: Optional[List[str]],
version: Optional[str],
parameters: Optional[Dict[str, Any]],
resource_args: Optional[Dict[str, Any]],
launch_config: Optional[Dict[str, Any]],
run_id: Optional[str],
repository: Optional[str],
) -> Dict[str, Any]:
"""Construct the launch specification from CLI arguments."""
# override base config (if supplied) with supplied args
launch_spec = launch_config if launch_config is not None else {}
if uri is not None:
launch_spec["uri"] = uri
if job is not None:
launch_spec["job"] = job
project, entity = set_project_entity_defaults(
uri,
job,
api,
project,
entity,
launch_config,
)
launch_spec["entity"] = entity
launch_spec["project"] = project
if name:
launch_spec["name"] = name
if "docker" not in launch_spec:
launch_spec["docker"] = {}
if docker_image:
launch_spec["docker"]["docker_image"] = docker_image
if "resource" not in launch_spec:
launch_spec["resource"] = resource if resource else None
if "git" not in launch_spec:
launch_spec["git"] = {}
if version:
launch_spec["git"]["version"] = version
if "overrides" not in launch_spec:
launch_spec["overrides"] = {}
if parameters:
override_args = util._user_args_to_dict(
launch_spec["overrides"].get("args", [])
)
base_args = override_args
launch_spec["overrides"]["args"] = merge_parameters(parameters, base_args)
elif isinstance(launch_spec["overrides"].get("args"), list):
launch_spec["overrides"]["args"] = util._user_args_to_dict(
launch_spec["overrides"].get("args")
)
if resource_args:
launch_spec["resource_args"] = resource_args
if entry_point:
launch_spec["overrides"]["entry_point"] = entry_point
if run_id is not None:
launch_spec["run_id"] = run_id
if repository:
launch_config = launch_config or {}
if launch_config.get("registry"):
launch_config["registry"]["url"] = repository
else:
launch_config["registry"] = {"url": repository}
return launch_spec | python | wandb/sdk/launch/utils.py | 151 | 231 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,891 | validate_launch_spec_source | def validate_launch_spec_source(launch_spec: Dict[str, Any]) -> None:
uri = launch_spec.get("uri")
job = launch_spec.get("job")
docker_image = launch_spec.get("docker", {}).get("docker_image")
if not bool(uri) and not bool(job) and not bool(docker_image):
raise LaunchError("Must specify a uri, job or docker image")
elif bool(uri) and bool(docker_image):
raise LaunchError("Found both uri and docker-image, only one can be set")
elif sum(map(bool, [uri, job, docker_image])) > 1:
raise LaunchError("Must specify exactly one of uri, job or image") | python | wandb/sdk/launch/utils.py | 234 | 244 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,892 | parse_wandb_uri | def parse_wandb_uri(uri: str) -> Tuple[str, str, str]:
"""Parse wandb uri to retrieve entity, project and run name."""
ref = WandbReference.parse(uri)
if not ref or not ref.entity or not ref.project or not ref.run_id:
raise LaunchError(f"Trouble parsing wandb uri {uri}")
return (ref.entity, ref.project, ref.run_id) | python | wandb/sdk/launch/utils.py | 247 | 252 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,893 | is_bare_wandb_uri | def is_bare_wandb_uri(uri: str) -> bool:
"""Check that a wandb uri is valid.
URI must be in the format
`/<entity>/<project>/runs/<run_name>[other stuff]`
or
`/<entity>/<project>/artifacts/job/<job_name>[other stuff]`.
"""
_logger.info(f"Checking if uri {uri} is bare...")
return uri.startswith("/") and WandbReference.is_uri_job_or_run(uri) | python | wandb/sdk/launch/utils.py | 255 | 264 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,894 | fetch_wandb_project_run_info | def fetch_wandb_project_run_info(
entity: str, project: str, run_name: str, api: Api
) -> Any:
_logger.info("Fetching run info...")
try:
result = api.get_run_info(entity, project, run_name)
except CommError:
result = None
if result is None:
raise LaunchError(
f"Run info is invalid or doesn't exist for {api.settings('base_url')}/{entity}/{project}/runs/{run_name}"
)
if result.get("codePath") is None:
# TODO: we don't currently expose codePath in the runInfo endpoint, this downloads
# it from wandb-metadata.json if we can.
metadata = api.download_url(
project, "wandb-metadata.json", run=run_name, entity=entity
)
if metadata is not None:
_, response = api.download_file(metadata["url"])
data = response.json()
result["codePath"] = data.get("codePath")
result["cudaVersion"] = data.get("cuda", None)
if result.get("args") is not None:
result["args"] = util._user_args_to_dict(result["args"])
return result | python | wandb/sdk/launch/utils.py | 267 | 293 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,895 | download_entry_point | def download_entry_point(
entity: str, project: str, run_name: str, api: Api, entry_point: str, dir: str
) -> bool:
metadata = api.download_url(
project, f"code/{entry_point}", run=run_name, entity=entity
)
if metadata is not None:
_, response = api.download_file(metadata["url"])
with util.fsync_open(os.path.join(dir, entry_point), "wb") as file:
for data in response.iter_content(chunk_size=1024):
file.write(data)
return True
return False | python | wandb/sdk/launch/utils.py | 296 | 308 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,896 | download_wandb_python_deps | def download_wandb_python_deps(
entity: str, project: str, run_name: str, api: Api, dir: str
) -> Optional[str]:
reqs = api.download_url(project, "requirements.txt", run=run_name, entity=entity)
if reqs is not None:
_logger.info("Downloading python dependencies")
_, response = api.download_file(reqs["url"])
with util.fsync_open(
os.path.join(dir, "requirements.frozen.txt"), "wb"
) as file:
for data in response.iter_content(chunk_size=1024):
file.write(data)
return "requirements.frozen.txt"
return None | python | wandb/sdk/launch/utils.py | 311 | 325 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,897 | get_local_python_deps | def get_local_python_deps(
dir: str, filename: str = "requirements.local.txt"
) -> Optional[str]:
try:
env = os.environ
with open(os.path.join(dir, filename), "w") as f:
subprocess.call(["pip", "freeze"], env=env, stdout=f)
return filename
except subprocess.CalledProcessError as e:
wandb.termerror(f"Command failed: {e}")
return None | python | wandb/sdk/launch/utils.py | 328 | 338 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,898 | diff_pip_requirements | def diff_pip_requirements(req_1: List[str], req_2: List[str]) -> Dict[str, str]:
"""Return a list of pip requirements that are not in req_1 but are in req_2."""
def _parse_req(req: List[str]) -> Dict[str, str]:
# TODO: This can be made more exhaustive, but for 99% of cases this is fine
# see https://pip.pypa.io/en/stable/reference/requirements-file-format/#example
d: Dict[str, str] = dict()
for line in req:
_name: str = None # type: ignore
_version: str = None # type: ignore
if line.startswith("#"): # Ignore comments
continue
elif "git+" in line or "hg+" in line:
_name = line.split("#egg=")[1]
_version = line.split("@")[-1].split("#")[0]
elif "==" in line:
_s = line.split("==")
_name = _s[0].lower()
_version = _s[1].split("#")[0].strip()
elif ">=" in line:
_s = line.split(">=")
_name = _s[0].lower()
_version = _s[1].split("#")[0].strip()
elif ">" in line:
_s = line.split(">")
_name = _s[0].lower()
_version = _s[1].split("#")[0].strip()
elif re.match(_VALID_PIP_PACKAGE_REGEX, line) is not None:
_name = line
else:
raise ValueError(f"Unable to parse pip requirements file line: {line}")
if _name is not None:
assert re.match(
_VALID_PIP_PACKAGE_REGEX, _name
), f"Invalid pip package name {_name}"
d[_name] = _version
return d
# Use symmetric difference between dict representation to print errors
try:
req_1_dict: Dict[str, str] = _parse_req(req_1)
req_2_dict: Dict[str, str] = _parse_req(req_2)
except (AssertionError, ValueError, IndexError, KeyError) as e:
raise LaunchError(f"Failed to parse pip requirements: {e}")
diff: List[Tuple[str, str]] = []
for item in set(req_1_dict.items()) ^ set(req_2_dict.items()):
diff.append(item)
# Parse through the diff to make it pretty
pretty_diff: Dict[str, str] = {}
for name, version in diff:
if pretty_diff.get(name) is None:
pretty_diff[name] = version
else:
pretty_diff[name] = f"v{version} and v{pretty_diff[name]}"
return pretty_diff | python | wandb/sdk/launch/utils.py | 341 | 395 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,899 | _parse_req | def _parse_req(req: List[str]) -> Dict[str, str]:
# TODO: This can be made more exhaustive, but for 99% of cases this is fine
# see https://pip.pypa.io/en/stable/reference/requirements-file-format/#example
d: Dict[str, str] = dict()
for line in req:
_name: str = None # type: ignore
_version: str = None # type: ignore
if line.startswith("#"): # Ignore comments
continue
elif "git+" in line or "hg+" in line:
_name = line.split("#egg=")[1]
_version = line.split("@")[-1].split("#")[0]
elif "==" in line:
_s = line.split("==")
_name = _s[0].lower()
_version = _s[1].split("#")[0].strip()
elif ">=" in line:
_s = line.split(">=")
_name = _s[0].lower()
_version = _s[1].split("#")[0].strip()
elif ">" in line:
_s = line.split(">")
_name = _s[0].lower()
_version = _s[1].split("#")[0].strip()
elif re.match(_VALID_PIP_PACKAGE_REGEX, line) is not None:
_name = line
else:
raise ValueError(f"Unable to parse pip requirements file line: {line}")
if _name is not None:
assert re.match(
_VALID_PIP_PACKAGE_REGEX, _name
), f"Invalid pip package name {_name}"
d[_name] = _version
return d | python | wandb/sdk/launch/utils.py | 344 | 377 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
3,900 | validate_wandb_python_deps | def validate_wandb_python_deps(
requirements_file: Optional[str],
dir: str,
) -> None:
"""Warn if local python dependencies differ from wandb requirements.txt."""
if requirements_file is not None:
requirements_path = os.path.join(dir, requirements_file)
with open(requirements_path) as f:
wandb_python_deps: List[str] = f.read().splitlines()
local_python_file = get_local_python_deps(dir)
if local_python_file is not None:
local_python_deps_path = os.path.join(dir, local_python_file)
with open(local_python_deps_path) as f:
local_python_deps: List[str] = f.read().splitlines()
diff_pip_requirements(wandb_python_deps, local_python_deps)
return
_logger.warning("Unable to validate local python dependencies") | python | wandb/sdk/launch/utils.py | 398 | 416 | {
"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.