wandb_setup.py 20 KB

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