wandb_setup.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. """Global W&B library state.
  2. This module manages global state, which for wandb includes:
  3. - Settings configured through `wandb.setup()`
  4. - The list of active runs
  5. - A subprocess ("the internal service") that asynchronously uploads metrics
  6. This module is fork-aware: in a forked process such as that spawned by the
  7. `multiprocessing` module, `wandb.singleton()` returns a new object, not the
  8. one inherited from the parent process. This requirement comes from backward
  9. compatibility with old design choices: the hardest one to fix is that wandb
  10. was originally designed to have a single run for the entire process that
  11. `wandb.init()` was meant to return. Back then, the only way to create
  12. multiple simultaneous runs in a single script was to run subprocesses, and since
  13. the built-in `multiprocessing` module forks by default, this required a PID
  14. check to make `wandb.init()` ignore the inherited global run.
  15. Another reason for fork-awareness is that the process that starts up
  16. the internal service owns it and is responsible for shutting it down,
  17. and child processes shouldn't also try to do that. This is easier to
  18. redesign.
  19. """
  20. from __future__ import annotations
  21. import logging
  22. import os
  23. import pathlib
  24. import sys
  25. import threading
  26. from typing import TYPE_CHECKING, Any, Union
  27. import wandb
  28. import wandb.integration.sagemaker as sagemaker
  29. from wandb.env import CONFIG_DIR
  30. from wandb.errors import UsageError
  31. from wandb.sdk.lib import asyncio_manager, import_hooks, wb_logging
  32. from .lib import config_util, server
  33. if TYPE_CHECKING:
  34. from wandb.sdk import wandb_run
  35. from wandb.sdk.lib.service.service_connection import ServiceConnection
  36. from wandb.sdk.wandb_settings import Settings
  37. class _EarlyLogger:
  38. """Early logger which captures logs in memory until logging can be configured."""
  39. def __init__(self) -> None:
  40. self._log: list[tuple] = []
  41. self._exception: list[tuple] = []
  42. # support old warn() as alias of warning()
  43. self.warn = self.warning
  44. def debug(self, msg: str, *args: Any, **kwargs: Any) -> None:
  45. self._log.append((logging.DEBUG, msg, args, kwargs))
  46. def info(self, msg: str, *args: Any, **kwargs: Any) -> None:
  47. self._log.append((logging.INFO, msg, args, kwargs))
  48. def warning(self, msg: str, *args: Any, **kwargs: Any) -> None:
  49. self._log.append((logging.WARNING, msg, args, kwargs))
  50. def error(self, msg: str, *args: Any, **kwargs: Any) -> None:
  51. self._log.append((logging.ERROR, msg, args, kwargs))
  52. def critical(self, msg: str, *args: Any, **kwargs: Any) -> None:
  53. self._log.append((logging.CRITICAL, msg, args, kwargs))
  54. def exception(self, msg: str, *args: Any, **kwargs: Any) -> None:
  55. self._exception.append((msg, args, kwargs))
  56. def log(self, level: str, msg: str, *args: Any, **kwargs: Any) -> None:
  57. self._log.append((level, msg, args, kwargs))
  58. def _flush(self, new_logger: Logger) -> None:
  59. assert self is not new_logger
  60. for level, msg, args, kwargs in self._log:
  61. new_logger.log(level, msg, *args, **kwargs)
  62. for msg, args, kwargs in self._exception:
  63. new_logger.exception(msg, *args, **kwargs)
  64. Logger = Union[logging.Logger, _EarlyLogger]
  65. class _WandbSetup:
  66. """W&B library singleton."""
  67. def __init__(self, pid: int) -> None:
  68. self._asyncer = asyncio_manager.AsyncioManager()
  69. self._asyncer.start()
  70. self._connection: ServiceConnection | None = None
  71. self._active_runs: list[wandb_run.Run] = []
  72. self._active_runs_lock = threading.Lock()
  73. self._sweep_config: dict | None = None
  74. self._server: server.Server | None = None
  75. self._pid = pid
  76. # TODO(jhr): defer strict checks until settings are fully initialized
  77. # and logging is ready
  78. self._logger: Logger = _EarlyLogger()
  79. self._settings: Settings | None = None
  80. self._settings_environ: dict[str, str] | None = None
  81. @property
  82. def asyncer(self) -> asyncio_manager.AsyncioManager:
  83. """The internal asyncio thread used by wandb."""
  84. return self._asyncer
  85. def add_active_run(self, run: wandb_run.Run) -> None:
  86. """Append a run to the active runs list.
  87. This must be called when a run is initialized.
  88. Args:
  89. run: A newly initialized run.
  90. """
  91. with self._active_runs_lock:
  92. if run not in self._active_runs:
  93. self._active_runs.append(run)
  94. def remove_active_run(self, run: wandb_run.Run) -> None:
  95. """Remove the run from the active runs list.
  96. This must be called when a run is finished.
  97. Args:
  98. run: A run that is finished or crashed.
  99. """
  100. try:
  101. with self._active_runs_lock:
  102. self._active_runs.remove(run)
  103. except ValueError:
  104. pass # Removing a run multiple times is not an error.
  105. @property
  106. def most_recent_active_run(self) -> wandb_run.Run | None:
  107. """The most recently initialized run that is not yet finished."""
  108. with self._active_runs_lock:
  109. if not self._active_runs:
  110. return None
  111. return self._active_runs[-1]
  112. def finish_all_active_runs(self) -> None:
  113. """Finish all unfinished runs.
  114. NOTE: This is slightly inefficient as it finishes runs one at a time.
  115. This only exists to support using the `reinit="finish_previous"`
  116. setting together with `reinit="create_new"` which does not seem to be a
  117. useful pattern. Since `"create_new"` should eventually become the
  118. default and only behavior, it does not seem worth optimizing.
  119. """
  120. # Take a snapshot as each call to `finish()` modifies `_active_runs`.
  121. with self._active_runs_lock:
  122. runs_copy = list(self._active_runs)
  123. for run in runs_copy:
  124. run.finish()
  125. def did_environment_change(self) -> bool:
  126. """Check if os.environ has changed since settings were initialized."""
  127. if not self._settings_environ:
  128. return False
  129. exclude_env_vars = {"WANDB_SERVICE", "WANDB_KUBEFLOW_URL"}
  130. singleton_env = {
  131. k: v
  132. for k, v in self._settings_environ.items()
  133. if k.startswith("WANDB_") and k not in exclude_env_vars
  134. }
  135. os_env = {
  136. k: v
  137. for k, v in os.environ.items()
  138. if k.startswith("WANDB_") and k not in exclude_env_vars
  139. }
  140. return (
  141. set(singleton_env.keys()) != set(os_env.keys()) #
  142. or set(singleton_env.values()) != set(os_env.values())
  143. )
  144. def _load_settings(
  145. self,
  146. *,
  147. system_settings_path: str | None,
  148. disable_sagemaker: bool,
  149. overrides: Settings | None = None,
  150. ) -> None:
  151. """Load settings from environment variables, config files, etc.
  152. Args:
  153. system_settings_path: Location of system settings file to use.
  154. If not provided, reads the WANDB_CONFIG_DIR environment
  155. variable or uses the default location.
  156. disable_sagemaker: If true, skips modifying settings based on
  157. SageMaker.
  158. overrides: Additional settings to apply to the global settings.
  159. """
  160. from wandb.sdk.wandb_settings import Settings
  161. self._settings = Settings()
  162. # the pid of the process to monitor for system stats
  163. pid = os.getpid()
  164. self._logger.info(f"Current SDK version is {wandb.__version__}")
  165. self._logger.info(f"Configure stats pid to {pid}")
  166. self._settings.x_stats_pid = pid
  167. if system_settings_path:
  168. self._settings.settings_system = system_settings_path
  169. elif config_dir_str := os.getenv(CONFIG_DIR, None):
  170. config_dir = pathlib.Path(config_dir_str).expanduser()
  171. self._settings.settings_system = str(config_dir / "settings")
  172. else:
  173. self._settings.settings_system = str(
  174. pathlib.Path("~", ".config", "wandb", "settings").expanduser()
  175. )
  176. self._settings.update_from_system_settings()
  177. # load settings from the environment variables
  178. self._logger.info("Loading settings from environment variables")
  179. self._settings_environ = os.environ.copy()
  180. self._settings.update_from_env_vars(self._settings_environ)
  181. # infer settings from the system environment
  182. self._settings.update_from_system_environment()
  183. # load SageMaker settings
  184. if (
  185. not self._settings.sagemaker_disable
  186. and not disable_sagemaker
  187. and sagemaker.is_using_sagemaker()
  188. ):
  189. self._logger.info("Loading SageMaker settings")
  190. sagemaker.set_global_settings(self._settings)
  191. # load settings from the passed init/setup settings
  192. if overrides:
  193. self._settings.update_from_settings(overrides)
  194. wandb.termsetup(self._settings, None)
  195. def _update(self, settings: Settings | None) -> None:
  196. """Update settings, initializing them if necessary.
  197. Args:
  198. settings: Overrides to apply, if any.
  199. """
  200. if not self._settings:
  201. system_settings_path = settings.settings_system if settings else None
  202. disable_sagemaker = settings.sagemaker_disable if settings else False
  203. self._load_settings(
  204. system_settings_path=system_settings_path,
  205. disable_sagemaker=disable_sagemaker,
  206. overrides=settings,
  207. )
  208. # This is 'elif' because load_settings already applies overrides.
  209. elif settings:
  210. self._settings.update_from_settings(settings)
  211. def update_user_settings(self) -> None:
  212. # Get rid of cached results to force a refresh.
  213. self._server = None
  214. def _early_logger_flush(self, new_logger: Logger) -> None:
  215. if self._logger is new_logger:
  216. return
  217. if isinstance(self._logger, _EarlyLogger):
  218. self._logger._flush(new_logger)
  219. self._logger = new_logger
  220. def _get_logger(self) -> Logger:
  221. return self._logger
  222. @property
  223. def settings(self) -> Settings:
  224. """The global wandb settings.
  225. Initializes settings if they have not yet been loaded.
  226. """
  227. if not self._settings:
  228. self._load_settings(
  229. system_settings_path=None,
  230. disable_sagemaker=False,
  231. )
  232. assert self._settings
  233. return self._settings
  234. @property
  235. def settings_if_loaded(self) -> Settings | None:
  236. """The global wandb settings, or None if not yet loaded."""
  237. return self._settings
  238. def _get_entity(self) -> str | None:
  239. if self._settings and self._settings._offline:
  240. return None
  241. entity = self.viewer.get("entity")
  242. return entity
  243. def _get_username(self) -> str | None:
  244. if self._settings and self._settings._offline:
  245. return None
  246. return self.viewer.get("username")
  247. def _get_teams(self) -> list[str]:
  248. if self._settings and self._settings._offline:
  249. return []
  250. teams = self.viewer.get("teams")
  251. if teams:
  252. teams = [team["node"]["name"] for team in teams["edges"]]
  253. return teams or []
  254. @property
  255. def viewer(self) -> dict[str, Any]:
  256. if self._server is None:
  257. self._server = server.Server(settings=self.settings)
  258. return self._server.viewer
  259. def _load_user_settings(self) -> dict[str, Any] | None:
  260. # offline?
  261. if self._server is None:
  262. return None
  263. flags = self._server._flags
  264. user_settings = dict()
  265. if "code_saving_enabled" in flags:
  266. user_settings["save_code"] = flags["code_saving_enabled"]
  267. email = self.viewer.get("email", None)
  268. if email:
  269. user_settings["email"] = email
  270. return user_settings
  271. @property
  272. def config(self) -> dict:
  273. sweep_path = self.settings.sweep_param_path
  274. if sweep_path:
  275. self._sweep_config = config_util.dict_from_config_file(
  276. sweep_path, must_exist=True
  277. )
  278. config = {}
  279. # if config_paths was set, read in config dict
  280. if self.settings.config_paths:
  281. # TODO(jhr): handle load errors, handle list of files
  282. for config_path in self.settings.config_paths:
  283. config_dict = config_util.dict_from_config_file(config_path)
  284. if config_dict:
  285. config.update(config_dict)
  286. return config
  287. def _teardown(self, exit_code: int | None = None) -> None:
  288. import_hooks.unregister_all_post_import_hooks()
  289. if self._connection:
  290. internal_exit_code = self._connection.teardown(exit_code or 0)
  291. else:
  292. internal_exit_code = None
  293. self._asyncer.join()
  294. if internal_exit_code not in (None, 0):
  295. sys.exit(internal_exit_code)
  296. def ensure_service(self) -> ServiceConnection:
  297. """Returns a connection to the service process creating it if needed."""
  298. if self._connection:
  299. return self._connection
  300. from wandb.sdk.lib.service import service_connection
  301. self._connection = service_connection.connect_to_service(
  302. self._asyncer,
  303. self.settings,
  304. )
  305. return self._connection
  306. def assert_service(self) -> ServiceConnection:
  307. """Returns a connection to the service process, asserting it exists.
  308. Unlike ensure_service(), this will not start up a service process
  309. if it didn't already exist.
  310. """
  311. if not self._connection:
  312. raise AssertionError("Expected service process to exist.")
  313. return self._connection
  314. _singleton: _WandbSetup | None = None
  315. """The W&B library singleton, or None if not yet set up.
  316. The value is invalid and must not be used if `os.getpid() != _singleton._pid`.
  317. """
  318. _singleton_lock = threading.Lock()
  319. def singleton() -> _WandbSetup:
  320. """The W&B singleton for the current process.
  321. The first call to this in this process (which may be a fork of another
  322. process) creates the singleton, and all subsequent calls return it
  323. until teardown(). This does not start the service process.
  324. """
  325. return _setup(start_service=False, load_settings=False)
  326. @wb_logging.log_to_all_runs()
  327. def _setup(
  328. settings: Settings | None = None,
  329. start_service: bool = True,
  330. load_settings: bool = True,
  331. ) -> _WandbSetup:
  332. """Set up library context.
  333. Args:
  334. settings: Global settings to set, or updates to the global settings
  335. if the singleton has already been initialized.
  336. start_service: Whether to start up the service process.
  337. NOTE: A service process will only be started if allowed by the
  338. global settings (after the given updates). The service will not
  339. start up if the mode resolves to "disabled".
  340. load_settings: Whether to load settings from the environment
  341. if creating a new singleton. If False, then settings and
  342. start_service must be None.
  343. """
  344. global _singleton
  345. if not load_settings and settings:
  346. raise ValueError("Cannot pass settings if load_settings is False.")
  347. if not load_settings and start_service:
  348. raise ValueError("Cannot use start_service if load_settings is False.")
  349. pid = os.getpid()
  350. with _singleton_lock:
  351. if _singleton and _singleton._pid == pid:
  352. current_singleton = _singleton
  353. else:
  354. current_singleton = _WandbSetup(pid=pid)
  355. if load_settings:
  356. current_singleton._update(settings)
  357. if start_service and not current_singleton.settings._noop:
  358. current_singleton.ensure_service()
  359. _singleton = current_singleton
  360. # Update after configuring the _singleton.
  361. #
  362. # Do not hold the lock while updating credentials, as it writes back
  363. # to settings.
  364. if settings:
  365. _maybe_update_credentials(settings)
  366. return current_singleton
  367. def _maybe_update_credentials(settings: Settings) -> None:
  368. """Update session credentials if they're set on settings.
  369. This is a refactoring step for moving credentials into a separate module
  370. and out of settings. If a user calls `wandb.setup()` explicitly with an
  371. api_key or other credential, this overwrites credentials that might have
  372. been set by a call to `wandb.login()`.
  373. """
  374. if settings.api_key and settings.identity_token_file:
  375. raise UsageError(
  376. "The api_key and identity_token_file settings cannot be used together."
  377. )
  378. from wandb.sdk.lib import wbauth
  379. if settings.api_key:
  380. wbauth.use_explicit_auth(
  381. wbauth.AuthApiKey(
  382. host=wbauth.HostUrl(settings.base_url, app_url=settings.app_url),
  383. api_key=settings.api_key,
  384. ),
  385. source="wandb.setup()",
  386. )
  387. elif settings.identity_token_file:
  388. wbauth.use_explicit_auth(
  389. wbauth.AuthIdentityTokenFile(
  390. host=wbauth.HostUrl(settings.base_url, app_url=settings.app_url),
  391. path=settings.identity_token_file,
  392. ),
  393. source="wandb.setup()",
  394. )
  395. def setup(settings: Settings | None = None) -> _WandbSetup:
  396. """Prepares W&B for use in the current process and its children.
  397. You can usually ignore this as it is implicitly called by `wandb.init()`.
  398. When using wandb in multiple processes, calling `wandb.setup()`
  399. in the parent process before starting child processes may improve
  400. performance and resource utilization.
  401. Note that `wandb.setup()` modifies `os.environ`, and it is important
  402. that child processes inherit the modified environment variables.
  403. See also `wandb.teardown()`.
  404. Args:
  405. settings: Configuration settings to apply globally. These can be
  406. overridden by subsequent `wandb.init()` calls.
  407. Example:
  408. ```python
  409. import multiprocessing
  410. import wandb
  411. def run_experiment(params):
  412. with wandb.init(config=params):
  413. # Run experiment
  414. pass
  415. if __name__ == "__main__":
  416. # Start backend and set global config
  417. wandb.setup(settings={"project": "my_project"})
  418. # Define experiment parameters
  419. experiment_params = [
  420. {"learning_rate": 0.01, "epochs": 10},
  421. {"learning_rate": 0.001, "epochs": 20},
  422. ]
  423. # Start multiple processes, each running a separate experiment
  424. processes = []
  425. for params in experiment_params:
  426. p = multiprocessing.Process(target=run_experiment, args=(params,))
  427. p.start()
  428. processes.append(p)
  429. # Wait for all processes to complete
  430. for p in processes:
  431. p.join()
  432. # Optional: Explicitly shut down the backend
  433. wandb.teardown()
  434. ```
  435. """
  436. return _setup(settings=settings)
  437. @wb_logging.log_to_all_runs()
  438. def teardown(exit_code: int | None = None) -> None:
  439. """Waits for W&B to finish and frees resources.
  440. Completes any runs that were not explicitly finished
  441. using `run.finish()` and waits for all data to be uploaded.
  442. It is recommended to call this at the end of a session
  443. that used `wandb.setup()`. It is invoked automatically
  444. in an `atexit` hook, but this is not reliable in certain setups
  445. such as when using Python's `multiprocessing` module.
  446. """
  447. global _singleton
  448. from wandb.sdk.lib import wbauth
  449. with _singleton_lock:
  450. orig_singleton = _singleton
  451. _singleton = None
  452. if orig_singleton:
  453. orig_singleton._teardown(exit_code=exit_code)
  454. wbauth.unauthenticate_session(update_settings=False)