internal.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. """The layer between launch sdk user code and the wandb internal process.
  2. If there is an active run this communication is done through the wandb run's
  3. backend interface.
  4. If there is no active run, the messages are staged on the StagedLaunchInputs
  5. singleton and sent when a run is created.
  6. """
  7. from __future__ import annotations
  8. import os
  9. import pathlib
  10. import shutil
  11. import tempfile
  12. from typing import Any
  13. import wandb
  14. import wandb.data_types
  15. from wandb.sdk.launch.errors import LaunchError
  16. from wandb.sdk.launch.inputs.schema import META_SCHEMA
  17. from wandb.util import get_module
  18. from .files import config_path_is_valid, override_file
  19. PERIOD = "."
  20. BACKSLASH = "\\"
  21. LAUNCH_MANAGED_CONFIGS_DIR = "_wandb_configs"
  22. class ConfigTmpDir:
  23. """Singleton for managing temporary directories for configuration files.
  24. Any configuration files designated as inputs to a launch job are copied to
  25. a temporary directory. This singleton manages the temporary directory and
  26. provides paths to the configuration files.
  27. """
  28. _instance = None
  29. def __new__(cls):
  30. if cls._instance is None:
  31. cls._instance = object.__new__(cls)
  32. return cls._instance
  33. def __init__(self):
  34. if not hasattr(self, "_tmp_dir"):
  35. self._tmp_dir = tempfile.mkdtemp()
  36. self._configs_dir = os.path.join(self._tmp_dir, LAUNCH_MANAGED_CONFIGS_DIR)
  37. os.mkdir(self._configs_dir)
  38. @property
  39. def tmp_dir(self):
  40. return pathlib.Path(self._tmp_dir)
  41. @property
  42. def configs_dir(self):
  43. return pathlib.Path(self._configs_dir)
  44. class JobInputArguments:
  45. """Arguments for the publish_job_input of Interface."""
  46. def __init__(
  47. self,
  48. include: list[str] | None = None,
  49. exclude: list[str] | None = None,
  50. schema: dict | None = None,
  51. file_path: str | None = None,
  52. run_config: bool | None = None,
  53. ):
  54. self.include = include
  55. self.exclude = exclude
  56. self.schema = schema
  57. self.file_path = file_path
  58. self.run_config = run_config
  59. class StagedLaunchInputs:
  60. _instance = None
  61. def __new__(cls):
  62. if cls._instance is None:
  63. cls._instance = object.__new__(cls)
  64. return cls._instance
  65. def __init__(self) -> None:
  66. if not hasattr(self, "_staged_inputs"):
  67. self._staged_inputs: list[JobInputArguments] = []
  68. def add_staged_input(
  69. self,
  70. input_arguments: JobInputArguments,
  71. ):
  72. self._staged_inputs.append(input_arguments)
  73. def apply(self, run: wandb.Run):
  74. """Apply the staged inputs to the given run."""
  75. for input in self._staged_inputs:
  76. _publish_job_input(input, run)
  77. def _publish_job_input(
  78. input: JobInputArguments,
  79. run: wandb.Run,
  80. ) -> None:
  81. """Publish a job input to the backend interface of the given run.
  82. Arguments:
  83. input (JobInputArguments): The arguments for the job input.
  84. run (wandb.Run): The run to publish the job input to.
  85. """
  86. assert run._backend is not None
  87. assert run._backend.interface is not None
  88. assert input.run_config is not None
  89. interface = run._backend.interface
  90. if input.file_path:
  91. config_dir = ConfigTmpDir()
  92. dest = os.path.join(config_dir.configs_dir, input.file_path)
  93. run.save(dest, base_path=config_dir.tmp_dir)
  94. interface.publish_job_input(
  95. include_paths=[_split_on_unesc_dot(path) for path in input.include]
  96. if input.include
  97. else [],
  98. exclude_paths=[_split_on_unesc_dot(path) for path in input.exclude]
  99. if input.exclude
  100. else [],
  101. input_schema=input.schema,
  102. run_config=input.run_config,
  103. file_path=input.file_path or "",
  104. )
  105. def _replace_refs_and_allofs(schema: dict, defs: dict | None) -> dict:
  106. """Recursively fix JSON schemas with common issues.
  107. 1. Replaces any instances of $ref with their associated definition in defs
  108. 2. Removes any "allOf" lists that only have one item, "lifting" the item up
  109. See test_internal.py for examples
  110. """
  111. ret: dict[str, Any] = {}
  112. if "$ref" in schema and defs:
  113. # Reference found, replace it with its definition
  114. def_key = schema.pop("$ref").split("#/$defs/")[1]
  115. # Also run recursive replacement in case a ref contains more refs
  116. ret = _replace_refs_and_allofs(defs[def_key], defs)
  117. for key, val in schema.items():
  118. if isinstance(val, dict):
  119. # Step into dicts recursively
  120. new_val_dict = _replace_refs_and_allofs(val, defs)
  121. ret[key] = new_val_dict
  122. elif isinstance(val, list):
  123. # Step into each item in the list
  124. new_val_list = []
  125. for item in val:
  126. if isinstance(item, dict):
  127. new_val_list.append(_replace_refs_and_allofs(item, defs))
  128. else:
  129. new_val_list.append(item)
  130. # Lift up allOf blocks with only one item
  131. if (
  132. key == "allOf"
  133. and len(new_val_list) == 1
  134. and isinstance(new_val_list[0], dict)
  135. ):
  136. ret.update(new_val_list[0])
  137. else:
  138. ret[key] = new_val_list
  139. else:
  140. # For anything else (str, int, etc) keep it as-is
  141. ret[key] = val
  142. return ret
  143. def _prepare_schema(schema: Any) -> dict:
  144. """Prepare a schema for validation.
  145. This function prepares a schema for validation by:
  146. 1. Converting a Pydantic model instance or class to a dict
  147. 2. Replacing $ref with their associated definition in defs
  148. 3. Removing any "allOf" lists that only have one item, "lifting" the item up
  149. We support both an instance of a pydantic BaseModel class (e.g. schema=MySchema(...))
  150. or the BaseModel class itself (e.g. schema=MySchema)
  151. """
  152. if hasattr(schema, "model_json_schema") and callable(
  153. schema.model_json_schema # type: ignore
  154. ):
  155. schema = schema.model_json_schema()
  156. if not isinstance(schema, dict):
  157. raise LaunchError(
  158. "schema must be a dict, Pydantic model instance, or Pydantic model class."
  159. )
  160. defs = schema.pop("$defs", None)
  161. return _replace_refs_and_allofs(schema, defs)
  162. def _validate_schema(schema: dict) -> None:
  163. jsonschema = get_module(
  164. "jsonschema",
  165. required="Setting job schema requires the jsonschema package. Please install it with `pip install 'wandb[launch]'`.",
  166. lazy=False,
  167. )
  168. validator = jsonschema.Draft202012Validator(META_SCHEMA)
  169. errs = sorted(validator.iter_errors(schema), key=str)
  170. if errs:
  171. wandb.termwarn(f"Schema includes unhandled or invalid configurations:\n{errs}")
  172. def handle_config_file_input(
  173. path: str,
  174. include: list[str] | None = None,
  175. exclude: list[str] | None = None,
  176. schema: Any | None = None,
  177. ):
  178. """Declare an overridable configuration file for a launch job.
  179. The configuration file is copied to a temporary directory and the path to
  180. the copy is sent to the backend interface of the active run and used to
  181. configure the job builder.
  182. If there is no active run, the configuration file is staged and sent when a
  183. run is created.
  184. """
  185. config_path_is_valid(path)
  186. override_file(path)
  187. tmp_dir = ConfigTmpDir()
  188. dest = os.path.join(tmp_dir.configs_dir, path)
  189. dest_dir = os.path.dirname(dest)
  190. if not os.path.exists(dest_dir):
  191. os.makedirs(dest_dir)
  192. shutil.copy(
  193. path,
  194. dest,
  195. )
  196. if schema:
  197. schema = _prepare_schema(schema)
  198. _validate_schema(schema)
  199. arguments = JobInputArguments(
  200. include=include,
  201. exclude=exclude,
  202. schema=schema,
  203. file_path=path,
  204. run_config=False,
  205. )
  206. if wandb.run is not None:
  207. _publish_job_input(arguments, wandb.run)
  208. else:
  209. staged_inputs = StagedLaunchInputs()
  210. staged_inputs.add_staged_input(arguments)
  211. def handle_run_config_input(
  212. include: list[str] | None = None,
  213. exclude: list[str] | None = None,
  214. schema: Any | None = None,
  215. ):
  216. """Declare wandb.config as an overridable configuration for a launch job.
  217. The include and exclude paths are sent to the backend interface of the
  218. active run and used to configure the job builder.
  219. If there is no active run, the include and exclude paths are staged and sent
  220. when a run is created.
  221. """
  222. if schema:
  223. schema = _prepare_schema(schema)
  224. _validate_schema(schema)
  225. arguments = JobInputArguments(
  226. include=include,
  227. exclude=exclude,
  228. schema=schema,
  229. run_config=True,
  230. file_path=None,
  231. )
  232. if wandb.run is not None:
  233. _publish_job_input(arguments, wandb.run)
  234. else:
  235. stage_inputs = StagedLaunchInputs()
  236. stage_inputs.add_staged_input(arguments)
  237. def _split_on_unesc_dot(path: str) -> list[str]:
  238. r"""Split a string on unescaped dots.
  239. Arguments:
  240. path (str): The string to split.
  241. Raises:
  242. ValueError: If the path has a trailing escape character.
  243. Returns:
  244. List[str]: The split string.
  245. """
  246. parts = []
  247. part = ""
  248. i = 0
  249. while i < len(path):
  250. if path[i] == BACKSLASH:
  251. if i == len(path) - 1:
  252. raise LaunchError(
  253. f"Invalid config path {path}: trailing {BACKSLASH}.",
  254. )
  255. if path[i + 1] == PERIOD:
  256. part += PERIOD
  257. i += 2
  258. elif path[i] == PERIOD:
  259. parts.append(part)
  260. part = ""
  261. i += 1
  262. else:
  263. part += path[i]
  264. i += 1
  265. if part:
  266. parts.append(part)
  267. return parts