create_job.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. from __future__ import annotations
  2. import json
  3. import logging
  4. import os
  5. import re
  6. import sys
  7. import tempfile
  8. from typing import Any
  9. import wandb
  10. from wandb.apis.internal import Api
  11. from wandb.sdk.artifacts.artifact import Artifact
  12. from wandb.sdk.internal.job_builder import JobBuilder
  13. from wandb.sdk.launch.git_reference import GitReference
  14. from wandb.sdk.launch.inputs.internal import _validate_schema
  15. from wandb.sdk.launch.utils import (
  16. _is_git_uri,
  17. get_current_python_version,
  18. get_entrypoint_file,
  19. )
  20. from wandb.sdk.lib import filesystem
  21. from wandb.util import make_artifact_name_safe
  22. logging.basicConfig(stream=sys.stdout, level=logging.INFO)
  23. _logger = logging.getLogger("wandb")
  24. CODE_ARTIFACT_EXCLUDE_PATHS = ["wandb", ".git"]
  25. def create_job(
  26. path: str,
  27. job_type: str,
  28. entity: str | None = None,
  29. project: str | None = None,
  30. name: str | None = None,
  31. description: str | None = None,
  32. aliases: list[str] | None = None,
  33. runtime: str | None = None,
  34. entrypoint: str | None = None,
  35. git_hash: str | None = None,
  36. build_context: str | None = None,
  37. dockerfile: str | None = None,
  38. ) -> Artifact | None:
  39. """Create a job from a path, not as the output of a run.
  40. Arguments:
  41. path (str): Path to the job directory.
  42. job_type (str): Type of the job. One of "git", "code", or "image".
  43. entity (Optional[str]): Entity to create the job under.
  44. project (Optional[str]): Project to create the job under.
  45. name (Optional[str]): Name of the job.
  46. description (Optional[str]): Description of the job.
  47. aliases (Optional[List[str]]): Aliases for the job.
  48. runtime (Optional[str]): Python runtime of the job, like 3.9.
  49. entrypoint (Optional[str]): Entrypoint of the job. If build_context is
  50. provided, path is relative to build_context.
  51. git_hash (Optional[str]): Git hash of a specific commit, when using git type jobs.
  52. build_context (Optional[str]): Path to the build context, when using image type jobs.
  53. dockerfile (Optional[str]): Path to the Dockerfile, when using image type jobs.
  54. If build_context is provided, path is relative to build_context.
  55. Returns:
  56. Optional[Artifact]: The artifact created by the job, the action (for printing), and job aliases.
  57. None if job creation failed.
  58. Example:
  59. ```python
  60. artifact_job = wandb.create_job(
  61. job_type="code",
  62. path=".",
  63. entity="wandb",
  64. project="jobs",
  65. name="my-train-job",
  66. description="My training job",
  67. aliases=["train"],
  68. runtime="3.9",
  69. entrypoint="train.py",
  70. )
  71. # then run the newly created job
  72. artifact_job.call()
  73. ```
  74. """
  75. api = Api()
  76. artifact_job, _action, _aliases = _create_job(
  77. api,
  78. job_type,
  79. path,
  80. entity,
  81. project,
  82. name,
  83. description,
  84. aliases,
  85. runtime,
  86. entrypoint,
  87. git_hash,
  88. build_context,
  89. dockerfile,
  90. )
  91. return artifact_job
  92. def _create_job(
  93. api: Api,
  94. job_type: str,
  95. path: str,
  96. entity: str | None = None,
  97. project: str | None = None,
  98. name: str | None = None,
  99. description: str | None = None,
  100. aliases: list[str] | None = None,
  101. runtime: str | None = None,
  102. entrypoint: str | None = None,
  103. git_hash: str | None = None,
  104. build_context: str | None = None,
  105. dockerfile: str | None = None,
  106. base_image: str | None = None,
  107. services: dict[str, str] | None = None,
  108. schema: dict[str, Any] | None = None,
  109. ) -> tuple[Artifact | None, str, list[str]]:
  110. wandb.termlog(f"Creating launch job of type: {job_type}...")
  111. if name and name != make_artifact_name_safe(name):
  112. wandb.termerror(
  113. f"Artifact names may only contain alphanumeric characters, dashes, underscores, and dots. Did you mean: {make_artifact_name_safe(name)}"
  114. )
  115. return None, "", []
  116. if runtime is not None and not re.match(r"^3\.\d+$", runtime):
  117. wandb.termerror(
  118. f"Runtime (-r, --runtime) must be a minor version of Python 3, "
  119. f"e.g. 3.9 or 3.10, received {runtime}"
  120. )
  121. return None, "", []
  122. aliases = aliases or []
  123. tempdir = tempfile.TemporaryDirectory()
  124. try:
  125. metadata, requirements = _make_metadata_for_partial_job(
  126. job_type=job_type,
  127. tempdir=tempdir,
  128. git_hash=git_hash,
  129. runtime=runtime,
  130. path=path,
  131. entrypoint=entrypoint,
  132. )
  133. if not metadata:
  134. return None, "", []
  135. except Exception as e:
  136. wandb.termerror(f"Error creating job: {e}")
  137. return None, "", []
  138. _dump_metadata_and_requirements(
  139. metadata=metadata,
  140. tmp_path=tempdir.name,
  141. requirements=requirements,
  142. )
  143. try:
  144. # init hidden wandb run with job building disabled (handled manually)
  145. run = wandb.init(
  146. dir=tempdir.name,
  147. settings={"silent": True, "disable_job_creation": True},
  148. entity=entity,
  149. project=project,
  150. job_type="cli_create_job",
  151. )
  152. except Exception:
  153. # Error printed by wandb.init
  154. return None, "", []
  155. job_builder = _configure_job_builder_for_partial(tempdir.name, job_source=job_type)
  156. job_builder._settings.job_name = name
  157. job_builder._services = services or {}
  158. if job_type == "code":
  159. assert entrypoint is not None
  160. job_name = _make_code_artifact(
  161. api=api,
  162. job_builder=job_builder,
  163. path=path,
  164. entrypoint=entrypoint,
  165. run=run, # type: ignore
  166. entity=entity,
  167. project=project,
  168. name=name,
  169. )
  170. if not job_name:
  171. return None, "", []
  172. name = job_name
  173. # build job artifact, loads wandb-metadata and creates wandb-job.json here
  174. artifact = job_builder.build(
  175. api.api,
  176. dockerfile=dockerfile,
  177. build_context=build_context,
  178. base_image=base_image,
  179. )
  180. if not artifact:
  181. wandb.termerror("JobBuilder failed to build a job")
  182. _logger.debug("Failed to build job, check job source and metadata")
  183. return None, "", []
  184. if not name:
  185. name = artifact.name
  186. aliases += job_builder._aliases
  187. if "latest" not in aliases:
  188. aliases += ["latest"]
  189. metadata = {"_partial": True}
  190. if schema:
  191. _validate_schema(schema)
  192. metadata = {
  193. "input_schemas": {
  194. "@wandb.config": schema,
  195. }
  196. }
  197. res, _ = api.create_artifact(
  198. artifact_type_name="job",
  199. artifact_collection_name=name,
  200. digest=artifact.digest,
  201. client_id=artifact._client_id,
  202. sequence_client_id=artifact._sequence_client_id,
  203. entity_name=entity,
  204. project_name=project,
  205. run_name=run.id, # type: ignore # run will be deleted after creation
  206. description=description,
  207. metadata=metadata,
  208. is_user_created=True,
  209. aliases=[{"artifactCollectionName": name, "alias": a} for a in aliases],
  210. )
  211. action = "No changes detected for"
  212. if not res.get("artifactSequence", {}).get("latestArtifact"):
  213. # When there is no latestArtifact, we are creating new
  214. action = "Created"
  215. elif res.get("state") == "PENDING":
  216. # updating an existing artifafct, state is pending awaiting call to
  217. # log_artifact to upload and finalize artifact. If not pending, digest
  218. # is the same as latestArtifact, so no changes detected
  219. action = "Updated"
  220. run.log_artifact(artifact, aliases=aliases) # type: ignore
  221. artifact.wait()
  222. run.finish() # type: ignore
  223. # fetch, then delete hidden run
  224. _run = wandb.Api().run(f"{entity}/{project}/{run.id}") # type: ignore
  225. _run.delete()
  226. return artifact, action, aliases
  227. def _make_metadata_for_partial_job(
  228. job_type: str,
  229. tempdir: tempfile.TemporaryDirectory,
  230. git_hash: str | None,
  231. runtime: str | None,
  232. path: str,
  233. entrypoint: str | None,
  234. ) -> tuple[dict[str, Any] | None, list[str] | None]:
  235. """Create metadata for partial jobs, return metadata and requirements."""
  236. metadata = {}
  237. if job_type == "git":
  238. assert entrypoint is not None
  239. repo_metadata = _create_repo_metadata(
  240. path=path,
  241. tempdir=tempdir.name,
  242. entrypoint=entrypoint,
  243. git_hash=git_hash,
  244. runtime=runtime,
  245. )
  246. if not repo_metadata:
  247. tempdir.cleanup() # otherwise git can pollute
  248. return None, None
  249. metadata.update(repo_metadata)
  250. return metadata, None
  251. if job_type == "code":
  252. assert entrypoint is not None
  253. artifact_metadata, requirements = _create_artifact_metadata(
  254. path=path, entrypoint=entrypoint, runtime=runtime
  255. )
  256. if not artifact_metadata:
  257. return None, None
  258. metadata.update(artifact_metadata)
  259. return metadata, requirements
  260. if job_type == "image":
  261. if runtime:
  262. wandb.termwarn(
  263. "Setting runtime is not supported for image jobs, ignoring runtime"
  264. )
  265. # TODO(gst): support entrypoint for image based jobs
  266. if entrypoint:
  267. wandb.termwarn(
  268. "Setting an entrypoint is not currently supported for image jobs, ignoring entrypoint argument"
  269. )
  270. metadata.update({"python": runtime or "", "docker": path})
  271. return metadata, None
  272. wandb.termerror(f"Invalid job type: {job_type}")
  273. return None, None
  274. def _maybe_warn_python_no_executable(entrypoint: str):
  275. entrypoint_list = entrypoint.split(" ")
  276. if len(entrypoint_list) == 1 and entrypoint_list[0].endswith(".py"):
  277. wandb.termwarn(
  278. f"Entrypoint {entrypoint} is a python file without an executable, you may want to use `python {entrypoint}` as the entrypoint instead."
  279. )
  280. def _create_repo_metadata(
  281. path: str,
  282. tempdir: str,
  283. entrypoint: str,
  284. git_hash: str | None = None,
  285. runtime: str | None = None,
  286. ) -> dict[str, Any] | None:
  287. # Make sure the entrypoint doesn't contain any backward path traversal
  288. if entrypoint and ".." in entrypoint:
  289. wandb.termerror("Entrypoint cannot contain backward path traversal")
  290. return None
  291. _maybe_warn_python_no_executable(entrypoint)
  292. if not _is_git_uri(path):
  293. wandb.termerror("Path must be a git URI")
  294. return None
  295. ref = GitReference(path, git_hash)
  296. if not ref:
  297. wandb.termerror("Could not parse git URI")
  298. return None
  299. ref.fetch(tempdir)
  300. commit = ref.commit_hash
  301. if not commit:
  302. if not ref.commit_hash:
  303. wandb.termerror("Could not find git commit hash")
  304. return None
  305. commit = ref.commit_hash
  306. local_dir = os.path.join(tempdir, ref.path or "")
  307. python_version = runtime
  308. if not python_version:
  309. if os.path.exists(os.path.join(local_dir, "runtime.txt")):
  310. with open(os.path.join(local_dir, "runtime.txt")) as f:
  311. python_version = f.read().strip()
  312. elif os.path.exists(os.path.join(local_dir, ".python-version")):
  313. with open(os.path.join(local_dir, ".python-version")) as f:
  314. python_version = f.read().strip().splitlines()[0]
  315. else:
  316. python_version, _ = get_current_python_version()
  317. python_version = _clean_python_version(python_version)
  318. metadata = {
  319. "git": {
  320. "commit": commit,
  321. "remote": ref.url,
  322. },
  323. "entrypoint": entrypoint.split(" "),
  324. "python": python_version, # used to build container
  325. "notebook": False, # partial jobs from notebooks not supported
  326. }
  327. return metadata
  328. def _create_artifact_metadata(
  329. path: str, entrypoint: str, runtime: str | None = None
  330. ) -> tuple[dict[str, Any] | None, list[str] | None]:
  331. if not os.path.isdir(path):
  332. wandb.termerror("Path must be a valid file or directory")
  333. return {}, []
  334. _maybe_warn_python_no_executable(entrypoint)
  335. entrypoint_list = entrypoint.split(" ")
  336. entrypoint_file = get_entrypoint_file(entrypoint_list)
  337. # read local requirements.txt and dump to temp dir for builder
  338. requirements = []
  339. depspath = os.path.join(path, "requirements.txt")
  340. if os.path.exists(depspath):
  341. with open(depspath) as f:
  342. requirements = f.read().splitlines()
  343. if not any(["wandb" in r for r in requirements]):
  344. wandb.termwarn("wandb is not present in requirements.txt.")
  345. if runtime:
  346. python_version = _clean_python_version(runtime)
  347. else:
  348. python_version, _ = get_current_python_version()
  349. python_version = _clean_python_version(python_version)
  350. metadata = {
  351. "python": python_version,
  352. "codePath": entrypoint_file,
  353. "entrypoint": entrypoint_list,
  354. }
  355. return metadata, requirements
  356. def _configure_job_builder_for_partial(tmpdir: str, job_source: str) -> JobBuilder:
  357. """Configure job builder with temp dir and job source."""
  358. # adjust git source to repo
  359. if job_source == "git":
  360. job_source = "repo"
  361. # adjust code source to artifact
  362. if job_source == "code":
  363. job_source = "artifact"
  364. settings = wandb.Settings(job_source=job_source)
  365. job_builder = JobBuilder(
  366. settings=settings, # type: ignore
  367. verbose=True,
  368. files_dir=tmpdir,
  369. )
  370. job_builder._partial = True
  371. # never allow notebook runs
  372. job_builder._is_notebook_run = False
  373. # set run inputs and outputs to empty dicts
  374. job_builder.set_config({})
  375. job_builder.set_summary({})
  376. return job_builder
  377. def _make_code_artifact(
  378. api: Api,
  379. job_builder: JobBuilder,
  380. run: wandb.Run,
  381. path: str,
  382. entrypoint: str,
  383. entity: str | None,
  384. project: str | None,
  385. name: str | None,
  386. ) -> str | None:
  387. """Helper for creating and logging code artifacts.
  388. Returns the name of the eventual job.
  389. """
  390. entrypoint_list = entrypoint.split(" ")
  391. # We no longer require the entrypoint to end in an existing file. But we
  392. # need something to use as the default job artifact name. In the future we
  393. # may require the user to provide a job name explicitly when calling
  394. # wandb job create.
  395. entrypoint_file = entrypoint_list[-1]
  396. artifact_name = _make_code_artifact_name(os.path.join(path, entrypoint_file), name)
  397. code_artifact = wandb.Artifact(
  398. name=artifact_name,
  399. type="code",
  400. description="Code artifact for job",
  401. )
  402. try:
  403. code_artifact.add_dir(path)
  404. except Exception as e:
  405. if os.path.islink(path):
  406. wandb.termerror(
  407. "Symlinks are not supported for code artifact jobs, please copy the code into a directory and try again"
  408. )
  409. wandb.termerror(f"Error adding to code artifact: {e}")
  410. return None
  411. # Remove paths we don't want to include, if present
  412. for item in CODE_ARTIFACT_EXCLUDE_PATHS:
  413. try:
  414. code_artifact.remove(item)
  415. except FileNotFoundError:
  416. pass
  417. res, _ = api.create_artifact(
  418. artifact_type_name="code",
  419. artifact_collection_name=artifact_name,
  420. digest=code_artifact.digest,
  421. client_id=code_artifact._client_id,
  422. sequence_client_id=code_artifact._sequence_client_id,
  423. entity_name=entity,
  424. project_name=project,
  425. run_name=run.id, # run will be deleted after creation
  426. description="Code artifact for job",
  427. metadata={"codePath": path, "entrypoint": entrypoint_file},
  428. is_user_created=True,
  429. aliases=[
  430. {"artifactCollectionName": artifact_name, "alias": a} for a in ["latest"]
  431. ],
  432. )
  433. run.log_artifact(code_artifact)
  434. code_artifact.wait()
  435. job_builder._handle_server_artifact(res, code_artifact) # type: ignore
  436. # code artifacts have "code" prefix, remove it and alias
  437. if not name:
  438. name = code_artifact.name.replace("code", "job").split(":")[0]
  439. return name
  440. def _make_code_artifact_name(path: str, name: str | None) -> str:
  441. """Make a code artifact name from a path and user provided name."""
  442. if name:
  443. return f"code-{name}"
  444. clean_path = path.replace("./", "")
  445. if clean_path[0] == "/":
  446. clean_path = clean_path[1:]
  447. if clean_path[-1] == "/":
  448. clean_path = clean_path[:-1]
  449. path_name = f"code-{make_artifact_name_safe(clean_path)}"
  450. return path_name
  451. def _dump_metadata_and_requirements(
  452. tmp_path: str, metadata: dict[str, Any], requirements: list[str] | None
  453. ) -> None:
  454. """Dump manufactured metadata and requirements.txt.
  455. File used by the job_builder to create a job from provided metadata.
  456. """
  457. filesystem.mkdir_exists_ok(tmp_path)
  458. with open(os.path.join(tmp_path, "wandb-metadata.json"), "w") as f:
  459. json.dump(metadata, f)
  460. requirements = requirements or []
  461. with open(os.path.join(tmp_path, "requirements.txt"), "w") as f:
  462. f.write("\n".join(requirements))
  463. def _clean_python_version(python_version: str) -> str:
  464. # remove micro if present
  465. if python_version.count(".") > 1:
  466. python_version = ".".join(python_version.split(".")[:2])
  467. _logger.debug(f"micro python version stripped. Now: {python_version}")
  468. return python_version