_launch.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. from __future__ import annotations
  2. import asyncio
  3. import logging
  4. import os
  5. import sys
  6. from typing import Any
  7. import wandb
  8. from wandb.apis.internal import Api
  9. from . import loader
  10. from ._project_spec import LaunchProject
  11. from .agent import LaunchAgent
  12. from .agent.agent import construct_agent_configs
  13. from .environment.local_environment import LocalEnvironment
  14. from .errors import ExecutionError, LaunchError
  15. from .runner.abstract import AbstractRun
  16. from .utils import (
  17. LAUNCH_CONFIG_FILE,
  18. PROJECT_SYNCHRONOUS,
  19. construct_launch_spec,
  20. validate_launch_spec_source,
  21. )
  22. _logger = logging.getLogger(__name__)
  23. def set_launch_logfile(logfile: str) -> None:
  24. """Set the logfile for the launch agent."""
  25. # Get logger of parent module
  26. _launch_logger = logging.getLogger("wandb.sdk.launch")
  27. if logfile == "-":
  28. logfile_stream = sys.stdout
  29. else:
  30. try:
  31. logfile_stream = open(logfile, "w")
  32. # check if file is writable
  33. except Exception as e:
  34. wandb.termerror(
  35. f"Could not open {logfile} for writing logs. Please check "
  36. f"the path and permissions.\nError: {e}"
  37. )
  38. return
  39. wandb.termlog(
  40. f"Internal agent logs printing to {'stdout' if logfile == '-' else logfile}. "
  41. )
  42. handler = logging.StreamHandler(logfile_stream)
  43. handler.formatter = logging.Formatter(
  44. "%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d "
  45. "[%(filename)s:%(funcName)s():%(lineno)s] %(message)s"
  46. )
  47. _launch_logger.addHandler(handler)
  48. _launch_logger.log(logging.INFO, "Internal agent logs printing to %s", logfile)
  49. def resolve_agent_config(
  50. entity: str | None,
  51. max_jobs: int | None,
  52. queues: tuple[str] | None,
  53. config: str | None,
  54. verbosity: int | None,
  55. ) -> tuple[dict[str, Any], Api]:
  56. """Resolve the agent config.
  57. Arguments:
  58. api (Api): The api.
  59. entity (str): The entity.
  60. max_jobs (int): The max number of jobs.
  61. queues (Tuple[str]): The queues.
  62. config (str): The config.
  63. verbosity (int): How verbose to print, 0 or None = default, 1 = print status every 20 seconds, 2 = also print debugging information
  64. Returns:
  65. Tuple[Dict[str, Any], Api]: The resolved config and api.
  66. """
  67. import yaml
  68. defaults = {
  69. "max_jobs": 1,
  70. "max_schedulers": 1,
  71. "queues": [],
  72. "registry": {},
  73. "builder": {},
  74. "verbosity": 0,
  75. }
  76. resolved_config: dict[str, Any] = defaults
  77. config_path = config or os.path.expanduser(LAUNCH_CONFIG_FILE)
  78. if os.path.isfile(config_path):
  79. launch_config = {}
  80. with open(config_path) as f:
  81. try:
  82. launch_config = yaml.safe_load(f)
  83. # This is considered unreachable by mypy, but it's not.
  84. if launch_config is None:
  85. launch_config = {} # type: ignore
  86. except yaml.YAMLError as e:
  87. raise LaunchError(f"Invalid launch agent config: {e}")
  88. resolved_config.update(launch_config.items())
  89. elif config is not None:
  90. raise LaunchError(
  91. f"Could not find use specified launch config file: {config_path}"
  92. )
  93. if os.environ.get("WANDB_ENTITY") is not None:
  94. resolved_config.update({"entity": os.environ.get("WANDB_ENTITY")})
  95. if os.environ.get("WANDB_LAUNCH_MAX_JOBS") is not None:
  96. resolved_config.update(
  97. {"max_jobs": int(os.environ.get("WANDB_LAUNCH_MAX_JOBS", 1))}
  98. )
  99. if entity is not None:
  100. resolved_config.update({"entity": entity})
  101. if max_jobs is not None:
  102. resolved_config.update({"max_jobs": int(max_jobs)})
  103. if queues:
  104. resolved_config.update({"queues": list(queues)})
  105. if verbosity:
  106. resolved_config.update({"verbosity": int(verbosity)})
  107. # queue -> queues
  108. if resolved_config.get("queue"):
  109. if isinstance(resolved_config.get("queue"), str):
  110. resolved_config["queues"].append(resolved_config["queue"])
  111. else:
  112. msg = (
  113. "Invalid launch agent config for key 'queue' with type: {type(resolved_config.get('queue'))} "
  114. "(expected str). Specify multiple queues with the 'queues' key"
  115. )
  116. raise LaunchError(msg)
  117. keys = ["entity"]
  118. settings = {
  119. k: resolved_config.get(k) for k in keys if resolved_config.get(k) is not None
  120. }
  121. api = Api(default_settings=settings)
  122. if resolved_config.get("entity") is None:
  123. resolved_config.update({"entity": api.default_entity})
  124. return resolved_config, api
  125. def create_and_run_agent(
  126. api: Api,
  127. config: dict[str, Any],
  128. ) -> None:
  129. try:
  130. from wandb.sdk.launch.agent import config as agent_config
  131. except ModuleNotFoundError:
  132. raise LaunchError(
  133. "wandb launch-agent requires pydantic to be installed. "
  134. "Please install with `pip install wandb[launch]`"
  135. )
  136. try:
  137. agent_config.AgentConfig(**config)
  138. except agent_config.ValidationError as e:
  139. errors = e.errors()
  140. for error in errors:
  141. loc = ".".join([str(x) for x in error.get("loc", [])])
  142. msg = f"Agent config error in field {loc}"
  143. value = error.get("input")
  144. if not isinstance(value, dict):
  145. msg += f" (value: {value})"
  146. msg += f": {error['msg']}"
  147. wandb.termerror(msg)
  148. raise LaunchError("Invalid launch agent config")
  149. agent = LaunchAgent(api, config)
  150. try:
  151. asyncio.run(agent.loop())
  152. except asyncio.CancelledError:
  153. pass
  154. async def _launch(
  155. api: Api,
  156. job: str | None = None,
  157. name: str | None = None,
  158. project: str | None = None,
  159. entity: str | None = None,
  160. docker_image: str | None = None,
  161. entry_point: list[str] | None = None,
  162. version: str | None = None,
  163. resource: str | None = None,
  164. resource_args: dict[str, Any] | None = None,
  165. launch_config: dict[str, Any] | None = None,
  166. synchronous: bool | None = None,
  167. run_id: str | None = None,
  168. repository: str | None = None,
  169. ) -> AbstractRun:
  170. """Helper that delegates to the project-running method corresponding to the passed-in backend."""
  171. if launch_config is None:
  172. launch_config = {}
  173. if resource is None:
  174. resource = "local-container"
  175. launch_spec = construct_launch_spec(
  176. None,
  177. job,
  178. api,
  179. name,
  180. project,
  181. entity,
  182. docker_image,
  183. resource,
  184. entry_point,
  185. version,
  186. resource_args,
  187. launch_config,
  188. run_id,
  189. repository,
  190. author=None,
  191. )
  192. validate_launch_spec_source(launch_spec)
  193. launch_project = LaunchProject.from_spec(launch_spec, api)
  194. launch_project.fetch_and_validate_project()
  195. entrypoint = launch_project.get_job_entry_point()
  196. image_uri = (
  197. launch_project.docker_image or launch_project.job_base_image
  198. ) # Either set by user or None.
  199. # construct runner config.
  200. runner_config: dict[str, Any] = {}
  201. runner_config[PROJECT_SYNCHRONOUS] = synchronous
  202. config = launch_config or {}
  203. environment_config, build_config, registry_config = construct_agent_configs(config)
  204. environment = loader.environment_from_config(environment_config)
  205. if environment is not None and not isinstance(environment, LocalEnvironment):
  206. await environment.verify()
  207. registry = loader.registry_from_config(registry_config, environment)
  208. builder = loader.builder_from_config(build_config, environment, registry)
  209. if not (launch_project.docker_image or launch_project.job_base_image):
  210. assert entrypoint
  211. image_uri = await builder.build_image(launch_project, entrypoint, None)
  212. backend = loader.runner_from_config(
  213. resource, api, runner_config, environment, registry
  214. )
  215. if backend:
  216. assert image_uri
  217. submitted_run = await backend.run(launch_project, image_uri)
  218. # this check will always pass, run is only optional in the agent case where
  219. # a run queue id is present on the backend config
  220. assert submitted_run
  221. return submitted_run
  222. else:
  223. raise ExecutionError(
  224. f"Unavailable backend {resource}, available backends: {', '.join(loader.WANDB_RUNNERS)}"
  225. )
  226. def launch(
  227. api: Api,
  228. job: str | None = None,
  229. entry_point: list[str] | None = None,
  230. version: str | None = None,
  231. name: str | None = None,
  232. resource: str | None = None,
  233. resource_args: dict[str, Any] | None = None,
  234. project: str | None = None,
  235. entity: str | None = None,
  236. docker_image: str | None = None,
  237. config: dict[str, Any] | None = None,
  238. synchronous: bool | None = True,
  239. run_id: str | None = None,
  240. repository: str | None = None,
  241. ) -> AbstractRun:
  242. """Launch a W&B launch experiment.
  243. Arguments:
  244. job: string reference to a wandb.Job eg: wandb/test/my-job:latest
  245. api: An instance of a wandb Api from wandb.apis.internal.
  246. entry_point: Entry point to run within the project. Defaults to using the entry point used
  247. in the original run for wandb URIs, or main.py for git repository URIs.
  248. version: For Git-based projects, either a commit hash or a branch name.
  249. name: Name run under which to launch the run.
  250. resource: Execution backend for the run.
  251. resource_args: Resource related arguments for launching runs onto a remote backend.
  252. Will be stored on the constructed launch config under ``resource_args``.
  253. project: Target project to send launched run to
  254. entity: Target entity to send launched run to
  255. config: A dictionary containing the configuration for the run. May also contain
  256. resource specific arguments under the key "resource_args".
  257. synchronous: Whether to block while waiting for a run to complete. Defaults to True.
  258. Note that if ``synchronous`` is False and ``backend`` is "local-container", this
  259. method will return, but the current process will block when exiting until
  260. the local run completes. If the current process is interrupted, any
  261. asynchronous runs launched via this method will be terminated. If
  262. ``synchronous`` is True and the run fails, the current process will
  263. error out as well.
  264. run_id: ID for the run (To ultimately replace the :name: field)
  265. repository: string name of repository path for remote registry
  266. Example:
  267. ```python
  268. from wandb.sdk.launch import launch
  269. job = "wandb/jobs/Hello World:latest"
  270. params = {"epochs": 5}
  271. # Run W&B project and create a reproducible docker environment
  272. # on a local host
  273. api = wandb.apis.internal.Api()
  274. launch(api, job, parameters=params)
  275. ```
  276. Returns:
  277. an instance of`wandb.launch.SubmittedRun` exposing information (e.g. run ID)
  278. about the launched run.
  279. Raises:
  280. `wandb.exceptions.ExecutionError` If a run launched in blocking mode
  281. is unsuccessful.
  282. """
  283. submitted_run_obj = asyncio.run(
  284. _launch(
  285. job=job,
  286. name=name,
  287. project=project,
  288. entity=entity,
  289. docker_image=docker_image,
  290. entry_point=entry_point,
  291. version=version,
  292. resource=resource,
  293. resource_args=resource_args,
  294. launch_config=config,
  295. synchronous=synchronous,
  296. api=api,
  297. run_id=run_id,
  298. repository=repository,
  299. )
  300. )
  301. return submitted_run_obj