scheduler.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  1. """Abstract Scheduler class."""
  2. from __future__ import annotations
  3. import asyncio
  4. import base64
  5. import copy
  6. import logging
  7. import os
  8. import socket
  9. import threading
  10. import time
  11. import traceback
  12. from abc import ABC, abstractmethod
  13. from collections.abc import Iterator
  14. from dataclasses import dataclass
  15. from enum import Enum
  16. from typing import TYPE_CHECKING, Any
  17. import click
  18. import wandb
  19. from wandb.errors import CommError
  20. from wandb.sdk.launch._launch_add import launch_add
  21. from wandb.sdk.launch.errors import LaunchError
  22. from wandb.sdk.launch.sweeps import SchedulerError
  23. from wandb.sdk.launch.sweeps.utils import (
  24. create_sweep_command_args,
  25. make_launch_sweep_entrypoint,
  26. )
  27. from wandb.sdk.launch.utils import (
  28. event_loop_thread_exec,
  29. strip_resource_args_and_template_vars,
  30. )
  31. from wandb.sdk.lib.runid import generate_id
  32. if TYPE_CHECKING:
  33. import wandb.apis.public as public
  34. from wandb.apis.internal import Api
  35. from wandb.apis.public import QueuedRun, Run
  36. _logger = logging.getLogger(__name__)
  37. LOG_PREFIX = f"{click.style('sched:', fg='cyan')} "
  38. DEFAULT_POLLING_SLEEP = 5.0
  39. class SchedulerState(Enum):
  40. PENDING = 0
  41. STARTING = 1
  42. RUNNING = 2
  43. FLUSH_RUNS = 3
  44. COMPLETED = 4
  45. FAILED = 5
  46. STOPPED = 6
  47. CANCELLED = 7
  48. class RunState(Enum):
  49. RUNNING = "running", "alive"
  50. PENDING = "pending", "alive"
  51. PREEMPTING = "preempting", "alive"
  52. CRASHED = "crashed", "dead"
  53. FAILED = "failed", "dead"
  54. KILLED = "killed", "dead"
  55. FINISHED = "finished", "dead"
  56. PREEMPTED = "preempted", "dead"
  57. # unknown when api.get_run_state fails or returns unexpected state
  58. # assumed alive, unless we get unknown 2x then move to failed (dead)
  59. UNKNOWN = "unknown", "alive"
  60. def __new__(cls: Any, *args: list, **kwds: Any) -> RunState:
  61. obj: RunState = object.__new__(cls)
  62. obj._value_ = args[0]
  63. return obj
  64. def __init__(self, _: str, life: str = "unknown") -> None:
  65. self._life = life
  66. @property
  67. def is_alive(self) -> bool:
  68. return self._life == "alive"
  69. @dataclass
  70. class _Worker:
  71. agent_config: dict[str, Any]
  72. agent_id: str
  73. @dataclass
  74. class SweepRun:
  75. id: str
  76. worker_id: int
  77. state: RunState = RunState.RUNNING
  78. queued_run: public.QueuedRun | None = None
  79. args: dict[str, Any] | None = None
  80. logs: list[str] | None = None
  81. class Scheduler(ABC):
  82. """A controller/agent that populates a Launch RunQueue from a hyperparameter sweep."""
  83. PLACEHOLDER_URI = "placeholder-uri-scheduler"
  84. SWEEP_JOB_TYPE = "sweep-controller"
  85. ENTRYPOINT = ["wandb", "scheduler", "WANDB_SWEEP_ID"]
  86. def __init__(
  87. self,
  88. api: Api,
  89. *args: Any | None,
  90. polling_sleep: float | None = None,
  91. sweep_id: str | None = None,
  92. entity: str | None = None,
  93. project: str | None = None,
  94. project_queue: str | None = None,
  95. num_workers: int | str | None = None,
  96. **kwargs: Any | None,
  97. ):
  98. import yaml
  99. from wandb.apis.public import Api as PublicApi
  100. self._api = api
  101. self._public_api = PublicApi()
  102. self._entity = (
  103. entity
  104. or os.environ.get("WANDB_ENTITY")
  105. or api.settings("entity")
  106. or api.default_entity
  107. )
  108. self._project = (
  109. project or os.environ.get("WANDB_PROJECT") or api.settings("project")
  110. )
  111. self._sweep_id: str = sweep_id or "empty-sweep-id"
  112. self._state: SchedulerState = SchedulerState.PENDING
  113. # Make sure the provided sweep_id corresponds to a valid sweep
  114. try:
  115. resp = self._api.sweep(
  116. sweep_id, "{}", entity=self._entity, project=self._project
  117. )
  118. if resp.get("state") == SchedulerState.CANCELLED.name:
  119. self._state = SchedulerState.CANCELLED
  120. self._sweep_config = yaml.safe_load(resp["config"])
  121. self._num_runs_launched: int = self._get_num_runs_launched(resp["runs"])
  122. if self._num_runs_launched > 0:
  123. wandb.termlog(
  124. f"{LOG_PREFIX}Found {self._num_runs_launched} previous valid runs for sweep {self._sweep_id}"
  125. )
  126. except Exception as e:
  127. raise SchedulerError(
  128. f"{LOG_PREFIX}Exception when finding sweep ({sweep_id}) {e}"
  129. )
  130. # Scheduler may receive additional kwargs which will be piped into the launch command
  131. self._kwargs: dict[str, Any] = kwargs
  132. # Dictionary of the runs being managed by the scheduler
  133. self._runs: dict[str, SweepRun] = {}
  134. # Threading lock to ensure thread-safe access to the runs dictionary
  135. self._threading_lock: threading.Lock = threading.Lock()
  136. self._polling_sleep = (
  137. polling_sleep if polling_sleep is not None else DEFAULT_POLLING_SLEEP
  138. )
  139. self._project_queue = project_queue
  140. # Optionally run multiple workers in (pseudo-)parallel. Workers do not
  141. # actually run training workloads, they simply send heartbeat messages
  142. # (emulating a real agent) and add new runs to the launch queue. The
  143. # launch agent is the one that actually runs the training workloads.
  144. self._workers: dict[int, _Worker] = {}
  145. # Init wandb scheduler run
  146. self._wandb_run = self._init_wandb_run()
  147. # Grab params from scheduler wandb run config
  148. num_workers = num_workers or self._wandb_run.config.get("scheduler", {}).get(
  149. "num_workers"
  150. )
  151. self._num_workers = int(num_workers) if str(num_workers).isdigit() else 8
  152. self._settings_config: dict[str, Any] = self._wandb_run.config.get(
  153. "settings", {}
  154. )
  155. @abstractmethod
  156. def _get_next_sweep_run(self, worker_id: int) -> SweepRun | None:
  157. """Called when worker available."""
  158. @abstractmethod
  159. def _poll(self) -> None:
  160. """Called every polling loop."""
  161. @abstractmethod
  162. def _exit(self) -> None:
  163. pass
  164. @abstractmethod
  165. def _load_state(self) -> None:
  166. pass
  167. @abstractmethod
  168. def _save_state(self) -> None:
  169. pass
  170. @property
  171. def state(self) -> SchedulerState:
  172. _logger.debug(f"{LOG_PREFIX}Scheduler state is {self._state.name}")
  173. return self._state
  174. @state.setter
  175. def state(self, value: SchedulerState) -> None:
  176. _logger.debug(f"{LOG_PREFIX}Scheduler was {self.state.name} is {value.name}")
  177. self._state = value
  178. @property
  179. def is_alive(self) -> bool:
  180. return self.state not in [
  181. SchedulerState.COMPLETED,
  182. SchedulerState.FAILED,
  183. SchedulerState.STOPPED,
  184. SchedulerState.CANCELLED,
  185. ]
  186. @property
  187. def at_runcap(self) -> bool:
  188. """False if under user-specified cap on # of runs."""
  189. run_cap = self._sweep_config.get("run_cap")
  190. if not run_cap:
  191. return False
  192. at_runcap: bool = self._num_runs_launched >= run_cap
  193. return at_runcap
  194. @property
  195. def num_active_runs(self) -> int:
  196. return len(self._runs)
  197. @property
  198. def busy_workers(self) -> dict[int, _Worker]:
  199. """Returns dict of id:worker already assigned to a launch run.
  200. runs should always have a worker_id, but are created before
  201. workers are assigned to the run
  202. """
  203. busy_workers = {}
  204. for _, r in self._yield_runs():
  205. busy_workers[r.worker_id] = self._workers[r.worker_id]
  206. return busy_workers
  207. @property
  208. def available_workers(self) -> dict[int, _Worker]:
  209. """Returns dict of id:worker ready to launch another run."""
  210. if len(self._workers) == 0:
  211. return {}
  212. return {
  213. _id: w for _id, w in self._workers.items() if _id not in self.busy_workers
  214. }
  215. def _init_wandb_run(self) -> wandb.Run:
  216. """Controls resume or init logic for a scheduler wandb run."""
  217. settings = wandb.Settings(disable_job_creation=True)
  218. run: wandb.Run = wandb.init( # type: ignore
  219. name=f"Scheduler.{self._sweep_id}",
  220. resume="allow",
  221. config=self._kwargs, # when run as a job, this sets config
  222. settings=settings,
  223. )
  224. return run
  225. def stop_sweep(self) -> None:
  226. """Stop the sweep."""
  227. self._state = SchedulerState.STOPPED
  228. def fail_sweep(self, err: str | None) -> None:
  229. """Fail the sweep w/ optional exception."""
  230. self._state = SchedulerState.FAILED
  231. if err:
  232. raise SchedulerError(err)
  233. def start(self) -> None:
  234. """Start a scheduler, confirms prerequisites, begins execution loop."""
  235. wandb.termlog(f"{LOG_PREFIX}Scheduler starting.")
  236. if not self.is_alive:
  237. wandb.termerror(
  238. f"{LOG_PREFIX}Sweep already in end state ({self.state.name.lower()}). Exiting..."
  239. )
  240. self.exit()
  241. return
  242. self._state = SchedulerState.STARTING
  243. if not self._try_load_executable():
  244. wandb.termerror(
  245. f"{LOG_PREFIX}No 'job' or 'image_uri' loaded from sweep config."
  246. )
  247. self.exit()
  248. return
  249. # For resuming sweeps
  250. self._load_state()
  251. asyncio.run(self._register_agents())
  252. self.run()
  253. def run(self) -> None:
  254. """Main run function."""
  255. wandb.termlog(f"{LOG_PREFIX}Scheduler running")
  256. self.state = SchedulerState.RUNNING
  257. try:
  258. while True:
  259. self._update_scheduler_run_state()
  260. if not self.is_alive:
  261. break
  262. wandb.termlog(f"{LOG_PREFIX}Polling for new runs to launch")
  263. self._update_run_states()
  264. self._poll()
  265. if self.state == SchedulerState.FLUSH_RUNS:
  266. if self.num_active_runs == 0:
  267. wandb.termlog(f"{LOG_PREFIX}Done polling on runs, exiting")
  268. break
  269. time.sleep(self._polling_sleep)
  270. continue
  271. for worker_id in self.available_workers:
  272. if self.at_runcap:
  273. wandb.termlog(
  274. f"{LOG_PREFIX}Sweep at run_cap ({self._num_runs_launched})"
  275. )
  276. self.state = SchedulerState.FLUSH_RUNS
  277. break
  278. try:
  279. run: SweepRun | None = self._get_next_sweep_run(worker_id)
  280. if not run:
  281. break
  282. except SchedulerError as e:
  283. raise SchedulerError(e)
  284. except Exception as e:
  285. wandb.termerror(
  286. f"{LOG_PREFIX}Failed to get next sweep run: {e}"
  287. )
  288. self.state = SchedulerState.FAILED
  289. break
  290. if self._add_to_launch_queue(run):
  291. self._num_runs_launched += 1
  292. time.sleep(self._polling_sleep)
  293. except KeyboardInterrupt:
  294. wandb.termwarn(f"{LOG_PREFIX}Scheduler received KeyboardInterrupt. Exiting")
  295. self.state = SchedulerState.STOPPED
  296. self.exit()
  297. return
  298. except Exception as e:
  299. wandb.termlog(f"{LOG_PREFIX}Scheduler failed with exception {e}")
  300. self.state = SchedulerState.FAILED
  301. self.exit()
  302. raise
  303. else:
  304. # scheduler succeeds if at runcap
  305. if self.state == SchedulerState.FLUSH_RUNS and self.at_runcap:
  306. self.state = SchedulerState.COMPLETED
  307. self.exit()
  308. def exit(self) -> None:
  309. self._exit()
  310. # _save_state isn't controlled, possibly fails
  311. try:
  312. self._save_state()
  313. except Exception:
  314. wandb.termerror(
  315. f"{LOG_PREFIX}Failed to save state: {traceback.format_exc()}"
  316. )
  317. status = ""
  318. if self.state == SchedulerState.FLUSH_RUNS:
  319. self._set_sweep_state("PAUSED")
  320. status = "paused"
  321. elif self.state == SchedulerState.COMPLETED:
  322. self._set_sweep_state("FINISHED")
  323. status = "completed"
  324. elif self.state in [SchedulerState.CANCELLED, SchedulerState.STOPPED]:
  325. self._set_sweep_state("CANCELED") # one L
  326. status = "cancelled"
  327. self._stop_runs()
  328. else:
  329. self.state = SchedulerState.FAILED
  330. self._set_sweep_state("CRASHED")
  331. status = "crashed"
  332. self._stop_runs()
  333. wandb.termlog(f"{LOG_PREFIX}Scheduler {status}")
  334. self._wandb_run.finish()
  335. def _get_num_runs_launched(self, runs: list[dict[str, Any]]) -> int:
  336. """Returns the number of valid runs in the sweep."""
  337. count = 0
  338. for run in runs:
  339. # if bad run, shouldn't be counted against run cap
  340. if run.get("state", "") in ["killed", "crashed"] and not run.get(
  341. "summaryMetrics"
  342. ):
  343. _logger.debug(
  344. f"excluding run: {run['name']} with state: {run['state']} from run cap \n{run}"
  345. )
  346. continue
  347. count += 1
  348. return count
  349. def _try_load_executable(self) -> bool:
  350. """Check existence of valid executable for a run.
  351. logs and returns False when job is unreachable
  352. """
  353. if self._kwargs.get("job"):
  354. try:
  355. _job_artifact = self._public_api.job(self._kwargs["job"])
  356. wandb.termlog(
  357. f"{LOG_PREFIX}Successfully loaded job ({_job_artifact.name}) in scheduler"
  358. )
  359. except Exception:
  360. wandb.termerror(f"{LOG_PREFIX}{traceback.format_exc()}")
  361. return False
  362. return True
  363. # TODO(gst): check docker existence? Use registry in launch config?
  364. return bool(self._kwargs.get("image_uri"))
  365. async def _register_agents(self) -> None:
  366. tasks = []
  367. register_agent = event_loop_thread_exec(self._api.register_agent)
  368. for worker_id in range(self._num_workers):
  369. _logger.debug(f"{LOG_PREFIX}Starting AgentHeartbeat worker ({worker_id})")
  370. try:
  371. worker = register_agent(
  372. f"{socket.gethostname()}-{worker_id}", # host
  373. sweep_id=self._sweep_id,
  374. project_name=self._project,
  375. entity=self._entity,
  376. )
  377. tasks.append(worker)
  378. except Exception as e:
  379. _logger.debug(f"failed to register agent: {e}")
  380. self.fail_sweep(f"failed to register agent: {e}")
  381. finished_tasks = await asyncio.gather(*tasks)
  382. for idx, agent_config in enumerate(finished_tasks):
  383. self._workers[idx] = _Worker(
  384. agent_config=agent_config,
  385. agent_id=agent_config["id"],
  386. )
  387. def _yield_runs(self) -> Iterator[tuple[str, SweepRun]]:
  388. """Thread-safe way to iterate over the runs."""
  389. with self._threading_lock:
  390. yield from self._runs.items()
  391. def _cleanup_runs(self, runs_to_remove: list[str]) -> None:
  392. """Helper for removing runs from memory.
  393. Can be overloaded to prevent deletion of runs, which is useful
  394. for debugging or when polling on completed runs.
  395. """
  396. with self._threading_lock:
  397. for run_id in runs_to_remove:
  398. wandb.termlog(f"{LOG_PREFIX}Cleaning up finished run ({run_id})")
  399. del self._runs[run_id]
  400. def _stop_runs(self) -> None:
  401. to_delete = []
  402. for run_id, _ in self._yield_runs():
  403. to_delete += [run_id]
  404. for run_id in to_delete:
  405. wandb.termlog(f"{LOG_PREFIX}Stopping run ({run_id})")
  406. if not self._stop_run(run_id):
  407. wandb.termwarn(f"{LOG_PREFIX}Failed to stop run ({run_id})")
  408. def _stop_run(self, run_id: str) -> bool:
  409. """Stops a run and removes it from the scheduler."""
  410. if run_id not in self._runs:
  411. _logger.debug(f"run: {run_id} not in _runs: {self._runs}")
  412. return False
  413. run = self._runs[run_id]
  414. del self._runs[run_id]
  415. if not run.queued_run:
  416. _logger.debug(
  417. f"tried to _stop_run but run not queued yet (run_id:{run.id})"
  418. )
  419. return False
  420. if not run.state.is_alive:
  421. # run already dead, just delete reference
  422. return True
  423. # run still alive, send stop signal
  424. encoded_run_id = base64.standard_b64encode(
  425. f"Run:v1:{run_id}:{self._project}:{self._entity}".encode()
  426. ).decode("utf-8")
  427. try:
  428. success: bool = self._api.stop_run(run_id=encoded_run_id)
  429. if success:
  430. wandb.termlog(f"{LOG_PREFIX}Stopped run {run_id}.")
  431. return True
  432. except Exception as e:
  433. _logger.debug(f"error stopping run ({run_id}): {e}")
  434. return False
  435. def _update_scheduler_run_state(self) -> None:
  436. """Update the scheduler state from state of scheduler run and sweep state."""
  437. state: RunState = self._get_run_state(self._wandb_run.id)
  438. # map scheduler run-state to scheduler-state
  439. if state == RunState.KILLED:
  440. self.state = SchedulerState.STOPPED
  441. elif state in [RunState.FAILED, RunState.CRASHED]:
  442. self.state = SchedulerState.FAILED
  443. elif state == RunState.FINISHED:
  444. self.state = SchedulerState.COMPLETED
  445. # check sweep state for completed states, overwrite scheduler state
  446. try:
  447. sweep_state = self._api.get_sweep_state(
  448. self._sweep_id, self._entity, self._project
  449. )
  450. except Exception as e:
  451. _logger.debug(f"sweep state error: {e}")
  452. return
  453. if sweep_state == "FINISHED":
  454. self.state = SchedulerState.COMPLETED
  455. elif sweep_state in ["CANCELLED", "STOPPED"]:
  456. self.state = SchedulerState.CANCELLED
  457. elif sweep_state == "PAUSED":
  458. self.state = SchedulerState.FLUSH_RUNS
  459. def _update_run_states(self) -> None:
  460. """Iterate through runs.
  461. Get state from backend and deletes runs if not in running state. Threadsafe.
  462. """
  463. runs_to_remove: list[str] = []
  464. for run_id, run in self._yield_runs():
  465. run.state = self._get_run_state(run_id, run.state)
  466. try:
  467. rqi_state = run.queued_run.state if run.queued_run else None
  468. except (CommError, LaunchError) as e:
  469. _logger.debug(f"Failed to get queued_run.state: {e}")
  470. rqi_state = None
  471. if not run.state.is_alive or rqi_state == "failed":
  472. _logger.debug(f"({run_id}) states: ({run.state}, {rqi_state})")
  473. runs_to_remove.append(run_id)
  474. self._cleanup_runs(runs_to_remove)
  475. def _get_metrics_from_run(self, run_id: str) -> list[Any]:
  476. """Use the public api to get metrics from a run.
  477. Uses the metric name found in the sweep config, any
  478. misspellings will result in an empty list.
  479. """
  480. try:
  481. queued_run: QueuedRun | None = self._runs[run_id].queued_run
  482. if not queued_run:
  483. return []
  484. api_run: Run = self._public_api.run(
  485. f"{queued_run.entity}/{queued_run.project}/{run_id}"
  486. )
  487. metric_name = self._sweep_config["metric"]["name"]
  488. history = api_run.scan_history(keys=["_step", metric_name])
  489. metrics = [x[metric_name] for x in history]
  490. return metrics
  491. except Exception as e:
  492. _logger.debug(f"[_get_metrics_from_run] {e}")
  493. return []
  494. def _get_run_info(self, run_id: str) -> dict[str, Any]:
  495. """Use the public api to get info about a run."""
  496. try:
  497. info: dict[str, Any] = self._api.get_run_info(
  498. self._entity, self._project, run_id
  499. )
  500. if info:
  501. return info
  502. except Exception as e:
  503. _logger.debug(f"[_get_run_info] {e}")
  504. return {}
  505. def _get_run_state(
  506. self, run_id: str, prev_run_state: RunState = RunState.UNKNOWN
  507. ) -> RunState:
  508. """Use the public api to get state of a run."""
  509. run_state = None
  510. try:
  511. state = self._api.get_run_state(self._entity, self._project, run_id)
  512. run_state = RunState(state)
  513. except CommError as e:
  514. _logger.debug(f"error getting state for run ({run_id}): {e}")
  515. if prev_run_state == RunState.UNKNOWN:
  516. # triggers when we get an unknown state for the second time
  517. wandb.termwarn(
  518. f"Failed to get runstate for run ({run_id}). Error: {traceback.format_exc()}"
  519. )
  520. run_state = RunState.FAILED
  521. else: # first time we get unknown state
  522. run_state = RunState.UNKNOWN
  523. except (AttributeError, ValueError):
  524. wandb.termwarn(
  525. f"Bad state ({run_state}) for run ({run_id}). Error: {traceback.format_exc()}"
  526. )
  527. run_state = RunState.UNKNOWN
  528. return run_state
  529. def _create_run(self) -> dict[str, Any]:
  530. """Use the public api to create a blank run."""
  531. try:
  532. server_run, inserted = self._api.upsert_run(
  533. project=self._project,
  534. entity=self._entity,
  535. sweep_name=self._sweep_id,
  536. )
  537. return server_run
  538. except Exception as e:
  539. _logger.debug(f"[_create_run] {e}")
  540. raise SchedulerError(
  541. "Error creating run from scheduler, check API connection and CLI version."
  542. )
  543. def _set_sweep_state(self, state: str) -> None:
  544. wandb.termlog(f"{LOG_PREFIX}Updating sweep state to: {state.lower()}")
  545. try:
  546. self._api.set_sweep_state(sweep=self._sweep_id, state=state)
  547. except Exception as e:
  548. _logger.debug(f"[set_sweep_state] {e}")
  549. def _encode(self, _id: str) -> str:
  550. return (
  551. base64.b64decode(bytes(_id.encode("utf-8"))).decode("utf-8").split(":")[2]
  552. )
  553. def _make_entry_and_launch_config(
  554. self, run: SweepRun
  555. ) -> tuple[list[str] | None, dict[str, dict[str, Any]]]:
  556. args = create_sweep_command_args({"args": run.args})
  557. entry_point, macro_args = make_launch_sweep_entrypoint(
  558. args, self._sweep_config.get("command")
  559. )
  560. # handle program macro
  561. if entry_point and "${program}" in entry_point:
  562. if not self._sweep_config.get("program"):
  563. raise SchedulerError(
  564. f"{LOG_PREFIX}Program macro in command has no corresponding 'program' in sweep config."
  565. )
  566. pidx = entry_point.index("${program}")
  567. entry_point[pidx] = self._sweep_config["program"]
  568. launch_config = copy.deepcopy(self._wandb_run.config.get("launch", {}))
  569. if "overrides" not in launch_config:
  570. launch_config["overrides"] = {"run_config": {}}
  571. if "run_config" not in launch_config["overrides"]:
  572. launch_config["overrides"]["run_config"] = {}
  573. launch_config["overrides"]["run_config"].update(args["args_dict"])
  574. if macro_args: # pipe in hyperparam args as params to launch
  575. launch_config["overrides"]["args"] = macro_args
  576. if entry_point:
  577. unresolved = [x for x in entry_point if str(x).startswith("${")]
  578. if unresolved:
  579. wandb.termwarn(
  580. f"{LOG_PREFIX}Sweep command contains unresolved macros: "
  581. f"{unresolved}, see launch docs for supported macros."
  582. )
  583. return entry_point, launch_config
  584. def _add_to_launch_queue(self, run: SweepRun) -> bool:
  585. """Convert a sweeprun into a launch job then push to runqueue."""
  586. # job and image first from CLI args, then from sweep config
  587. _job = self._kwargs.get("job") or self._sweep_config.get("job")
  588. _sweep_config_uri = self._sweep_config.get("image_uri")
  589. _image_uri = self._kwargs.get("image_uri") or _sweep_config_uri
  590. if _job is None and _image_uri is None:
  591. raise SchedulerError(f"{LOG_PREFIX}No 'job' nor 'image_uri' ({run.id})")
  592. elif _job is not None and _image_uri is not None:
  593. raise SchedulerError(f"{LOG_PREFIX}Sweep has both 'job' and 'image_uri'")
  594. entry_point, launch_config = self._make_entry_and_launch_config(run)
  595. if entry_point:
  596. wandb.termwarn(
  597. f"{LOG_PREFIX}Sweep command {entry_point} will override"
  598. f" {'job' if _job else 'image_uri'} entrypoint"
  599. )
  600. # override resource and args of job
  601. _job_launch_config = copy.deepcopy(self._wandb_run.config.get("launch")) or {}
  602. # default priority is "medium"
  603. _priority = int(launch_config.get("priority", 2)) # type: ignore
  604. # strip resource_args and template_variables from launch_config
  605. strip_resource_args_and_template_vars(_job_launch_config)
  606. run_id = run.id or generate_id()
  607. queued_run = launch_add(
  608. run_id=run_id,
  609. entry_point=entry_point,
  610. config=launch_config,
  611. docker_image=_image_uri, # TODO(gst): make agnostic (github? run uri?)
  612. job=_job,
  613. project=self._project,
  614. entity=self._entity,
  615. queue_name=self._kwargs.get("queue"),
  616. project_queue=self._project_queue,
  617. resource=_job_launch_config.get("resource"),
  618. resource_args=_job_launch_config.get("resource_args"),
  619. template_variables=_job_launch_config.get("template_variables"),
  620. author=self._kwargs.get("author"),
  621. sweep_id=self._sweep_id,
  622. priority=_priority,
  623. )
  624. run.queued_run = queued_run
  625. # TODO(gst): unify run and queued_run state
  626. run.state = RunState.RUNNING # assume it will get picked up
  627. self._runs[run_id] = run
  628. wandb.termlog(
  629. f"{LOG_PREFIX}Added run ({run_id}) to queue ({self._kwargs.get('queue')})"
  630. )
  631. return True