-
Notifications
You must be signed in to change notification settings - Fork 618
/
wandb_init.py
1115 lines (969 loc) 路 43.9 KB
/
wandb_init.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Defines wandb.init() and associated classes and methods.
`wandb.init()` indicates the beginning of a new run. In an ML training pipeline,
you could add `wandb.init()` to the beginning of your training script as well as
your evaluation script, and each step would be tracked as a run in W&B.
For more on using `wandb.init()`, including code snippets, check out our
[guide and FAQs](https://docs.wandb.ai/guides/track/launch).
"""
import copy
import json
import logging
import os
import pathlib
import platform
import sys
import tempfile
import traceback
from typing import Any, Dict, Optional, Sequence, Union
import shortuuid # type: ignore
import wandb
from wandb import trigger
from wandb.errors import UsageError
from wandb.integration import sagemaker
from wandb.integration.magic import magic_install
from wandb.util import _is_artifact_representation, sentry_exc
from . import wandb_login, wandb_setup
from .backend.backend import Backend
from .lib import (
RunDisabled,
SummaryDisabled,
filesystem,
ipython,
module,
reporting,
telemetry,
)
from .lib.deprecate import Deprecated, deprecate
from .lib.mailbox import Mailbox, MailboxHandle
from .lib.printer import get_printer
from .lib.proto_util import message_to_dict
from .lib.wburls import wburls
from .wandb_helper import parse_config
from .wandb_run import Run, TeardownHook, TeardownStage
from .wandb_settings import Settings, Source
logger = None # logger configured during wandb.init()
def _set_logger(log_object):
"""Configure module logger."""
global logger
logger = log_object
def online_status(*args, **kwargs):
pass
def _huggingface_version():
if "transformers" in sys.modules:
trans = wandb.util.get_module("transformers")
if hasattr(trans, "__version__"):
return trans.__version__
return None
def _maybe_mp_process(backend: Backend) -> bool:
parent_process = getattr(
backend._multiprocessing, "parent_process", None
) # New in version 3.8.
if parent_process:
return parent_process() is not None
process = backend._multiprocessing.current_process()
if process.name == "MainProcess":
return False
if process.name.startswith("Process-"):
return True
return False
def _handle_launch_config(settings: "Settings") -> Dict[str, Any]:
launch_run_config = {}
if not settings.launch:
return launch_run_config
if os.environ.get("WANDB_CONFIG") is not None:
try:
launch_run_config = json.loads(os.environ.get("WANDB_CONFIG", "{}"))
except (ValueError, SyntaxError):
wandb.termwarn("Malformed WANDB_CONFIG, using original config")
elif settings.launch_config_path and os.path.exists(settings.launch_config_path):
with open(settings.launch_config_path) as fp:
launch_config = json.loads(fp.read())
launch_run_config = launch_config.get("overrides", {}).get("run_config")
return launch_run_config
class _WandbInit:
_init_telemetry_obj: telemetry.TelemetryRecord
def __init__(self):
self.kwargs = None
self.settings = None
self.sweep_config = None
self.launch_config = {}
self.config = None
self.run = None
self.backend = None
self._teardown_hooks = []
self._wl = None
self._reporter = None
self.notebook = None
self.printer = None
self._init_telemetry_obj = telemetry.TelemetryRecord()
self.deprecated_features_used: Dict[str, str] = dict()
def _setup_printer(self, settings: Settings) -> None:
if self.printer:
return
self.printer = get_printer(settings._jupyter)
def setup(self, kwargs) -> None: # noqa: C901
"""Completes setup for `wandb.init()`.
This includes parsing all arguments, applying them with settings and enabling logging.
"""
self.kwargs = kwargs
# if the user ran, for example, `wandb.login(`) before `wandb.init()`,
# the singleton will already be set up and so if e.g. env vars are set
# in between, they will be ignored, which we need to inform the user about.
singleton = wandb_setup._WandbSetup._instance
if singleton is not None:
self._setup_printer(settings=singleton._settings)
exclude_env_vars = {"WANDB_SERVICE", "WANDB_KUBEFLOW_URL"}
# check if environment variables have changed
singleton_env = {
k: v
for k, v in singleton._environ.items()
if k.startswith("WANDB_") and k not in exclude_env_vars
}
os_env = {
k: v
for k, v in os.environ.items()
if k.startswith("WANDB_") and k not in exclude_env_vars
}
if set(singleton_env.keys()) != set(os_env.keys()) or set(
singleton_env.values()
) != set(os_env.values()):
line = (
"Changes to your `wandb` environment variables will be ignored "
"because your `wandb` session has already started. "
"For more information on how to modify your settings with "
"`wandb.init()` arguments, please refer to "
f"{self.printer.link(wburls.get('wandb_init'), 'the W&B docs')}."
)
self.printer.display(line, level="warn")
self._wl = wandb_setup.setup()
# Make sure we have a logger setup (might be an early logger)
_set_logger(self._wl._get_logger())
# Start with settings from wandb library singleton
settings: Settings = self._wl.settings.copy()
settings_param = kwargs.pop("settings", None)
if settings_param is not None and isinstance(settings_param, (Settings, dict)):
settings.update(settings_param, source=Source.INIT)
self._setup_printer(settings)
self._reporter = reporting.setup_reporter(settings=settings)
sagemaker_config: Dict = (
dict() if settings.sagemaker_disable else sagemaker.parse_sm_config()
)
if sagemaker_config:
sagemaker_api_key = sagemaker_config.get("wandb_api_key", None)
sagemaker_run, sagemaker_env = sagemaker.parse_sm_resources()
if sagemaker_env:
if sagemaker_api_key:
sagemaker_env["WANDB_API_KEY"] = sagemaker_api_key
settings._apply_env_vars(sagemaker_env)
wandb.setup(settings=settings)
settings.update(sagemaker_run, source=Source.SETUP)
with telemetry.context(obj=self._init_telemetry_obj) as tel:
tel.feature.sagemaker = True
with telemetry.context(obj=self._init_telemetry_obj) as tel:
if kwargs.get("config"):
tel.feature.set_init_config = True
if kwargs.get("name"):
tel.feature.set_init_name = True
if kwargs.get("id"):
tel.feature.set_init_id = True
if kwargs.get("tags"):
tel.feature.set_init_tags = True
# Remove parameters that are not part of settings
init_config = kwargs.pop("config", None) or dict()
# todo: remove this once officially deprecated
deprecated_kwargs = {
"config_include_keys": (
"Use `config=wandb.helper.parse_config(config_object, include=('key',))` instead."
),
"config_exclude_keys": (
"Use `config=wandb.helper.parse_config(config_object, exclude=('key',))` instead."
),
}
for deprecated_kwarg, msg in deprecated_kwargs.items():
if kwargs.get(deprecated_kwarg):
self.deprecated_features_used[deprecated_kwarg] = msg
init_config = parse_config(
init_config,
include=kwargs.pop("config_include_keys", None),
exclude=kwargs.pop("config_exclude_keys", None),
)
# merge config with sweep or sagemaker (or config file)
self.sweep_config = dict()
sweep_config = self._wl._sweep_config or dict()
self.config = dict()
self.init_artifact_config = dict()
for config_data in (
sagemaker_config,
self._wl._config,
init_config,
):
if not config_data:
continue
# split out artifacts, since when inserted into
# config they will trigger use_artifact
# but the run is not yet upserted
self._split_artifacts_from_config(config_data, self.config)
if sweep_config:
self._split_artifacts_from_config(sweep_config, self.sweep_config)
monitor_gym = kwargs.pop("monitor_gym", None)
if monitor_gym and len(wandb.patched["gym"]) == 0:
wandb.gym.monitor()
if wandb.patched["tensorboard"]:
with telemetry.context(obj=self._init_telemetry_obj) as tel:
tel.feature.tensorboard_patch = True
tensorboard = kwargs.pop("tensorboard", None)
sync_tensorboard = kwargs.pop("sync_tensorboard", None)
if tensorboard or sync_tensorboard and len(wandb.patched["tensorboard"]) == 0:
wandb.tensorboard.patch()
with telemetry.context(obj=self._init_telemetry_obj) as tel:
tel.feature.tensorboard_sync = True
magic = kwargs.get("magic")
if magic not in (None, False):
magic_install(kwargs)
# handle login related parameters as these are applied to global state
init_settings = {
key: kwargs[key]
for key in ["anonymous", "force", "mode", "resume"]
if kwargs.get(key) is not None
}
if init_settings:
settings.update(init_settings, source=Source.INIT)
if not settings._offline and not settings._noop:
wandb_login._login(
anonymous=kwargs.pop("anonymous", None),
force=kwargs.pop("force", None),
_disable_warning=True,
_silent=settings.quiet or settings.silent,
_entity=kwargs.get("entity") or settings.entity,
)
# apply updated global state after login was handled
settings._apply_settings(wandb.setup().settings)
# get status of code saving before applying user settings
save_code_pre_user_settings = settings.save_code
settings._apply_init(kwargs)
if not settings._offline and not settings._noop:
user_settings = self._wl._load_user_settings()
settings._apply_user(user_settings)
# ensure that user settings don't set saving to true
# if user explicitly set these to false in UI
if save_code_pre_user_settings is False:
settings.update({"save_code": False}, source=Source.INIT)
# TODO(jhr): should this be moved? probably.
settings._set_run_start_time(source=Source.INIT)
if not settings._noop:
self._log_setup(settings)
if settings._jupyter:
self._jupyter_setup(settings)
launch_config = _handle_launch_config(settings)
if launch_config:
self._split_artifacts_from_config(launch_config, self.launch_config)
self.settings = settings
# self.settings.freeze()
def teardown(self):
# TODO: currently this is only called on failed wandb.init attempts
# normally this happens on the run object
logger.info("tearing down wandb.init")
for hook in self._teardown_hooks:
hook.call()
def _split_artifacts_from_config(self, config_source, config_target):
for k, v in config_source.items():
if _is_artifact_representation(v):
self.init_artifact_config[k] = v
else:
config_target.setdefault(k, v)
def _enable_logging(self, log_fname, run_id=None):
"""Enables logging to the global debug log.
This adds a run_id to the log, in case of multiple processes on the same machine.
Currently, there is no way to disable logging after it's enabled.
"""
handler = logging.FileHandler(log_fname)
handler.setLevel(logging.INFO)
class WBFilter(logging.Filter):
def filter(self, record):
record.run_id = run_id
return True
if run_id:
formatter = logging.Formatter(
"%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d "
"[%(run_id)s:%(filename)s:%(funcName)s():%(lineno)s] %(message)s"
)
else:
formatter = logging.Formatter(
"%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d "
"[%(filename)s:%(funcName)s():%(lineno)s] %(message)s"
)
handler.setFormatter(formatter)
if run_id:
handler.addFilter(WBFilter())
logger.propagate = False
logger.addHandler(handler)
# TODO: make me configurable
logger.setLevel(logging.DEBUG)
self._teardown_hooks.append(
TeardownHook(
lambda: (handler.close(), logger.removeHandler(handler)),
TeardownStage.LATE,
)
)
def _safe_symlink(self, base, target, name, delete=False):
# TODO(jhr): do this with relpaths, but i cant figure it out on no sleep
if not hasattr(os, "symlink"):
return
pid = os.getpid()
tmp_name = os.path.join(base, "%s.%d" % (name, pid))
if delete:
try:
os.remove(os.path.join(base, name))
except OSError:
pass
target = os.path.relpath(target, base)
try:
os.symlink(target, tmp_name)
os.rename(tmp_name, os.path.join(base, name))
except OSError:
pass
def _pause_backend(self):
if self.backend is not None:
logger.info("pausing backend")
# Attempt to save the code on every execution
if self.notebook.save_ipynb():
res = self.run.log_code(root=None)
logger.info("saved code: %s", res)
self.backend.interface.publish_pause()
def _resume_backend(self):
if self.backend is not None:
logger.info("resuming backend")
self.backend.interface.publish_resume()
def _jupyter_teardown(self):
"""Teardown hooks and display saving, called with wandb.finish."""
ipython = self.notebook.shell
self.notebook.save_history()
if self.notebook.save_ipynb():
res = self.run.log_code(root=None)
logger.info("saved code and history: %s", res)
logger.info("cleaning up jupyter logic")
# because of how we bind our methods we manually find them to unregister
for hook in ipython.events.callbacks["pre_run_cell"]:
if "_resume_backend" in hook.__name__:
ipython.events.unregister("pre_run_cell", hook)
for hook in ipython.events.callbacks["post_run_cell"]:
if "_pause_backend" in hook.__name__:
ipython.events.unregister("post_run_cell", hook)
ipython.display_pub.publish = ipython.display_pub._orig_publish
del ipython.display_pub._orig_publish
def _jupyter_setup(self, settings):
"""Add hooks, and session history saving."""
self.notebook = wandb.jupyter.Notebook(settings)
ipython = self.notebook.shell
# Monkey patch ipython publish to capture displayed outputs
if not hasattr(ipython.display_pub, "_orig_publish"):
logger.info("configuring jupyter hooks %s", self)
ipython.display_pub._orig_publish = ipython.display_pub.publish
# Registering resume and pause hooks
ipython.events.register("pre_run_cell", self._resume_backend)
ipython.events.register("post_run_cell", self._pause_backend)
self._teardown_hooks.append(
TeardownHook(self._jupyter_teardown, TeardownStage.EARLY)
)
def publish(data, metadata=None, **kwargs):
ipython.display_pub._orig_publish(data, metadata=metadata, **kwargs)
self.notebook.save_display(
ipython.execution_count, {"data": data, "metadata": metadata}
)
ipython.display_pub.publish = publish
def _log_setup(self, settings):
"""Sets up logging from settings."""
filesystem._safe_makedirs(os.path.dirname(settings.log_user))
filesystem._safe_makedirs(os.path.dirname(settings.log_internal))
filesystem._safe_makedirs(os.path.dirname(settings.sync_file))
filesystem._safe_makedirs(settings.files_dir)
filesystem._safe_makedirs(settings._tmp_code_dir)
if settings.symlink:
self._safe_symlink(
os.path.dirname(settings.sync_symlink_latest),
os.path.dirname(settings.sync_file),
os.path.basename(settings.sync_symlink_latest),
delete=True,
)
self._safe_symlink(
os.path.dirname(settings.log_symlink_user),
settings.log_user,
os.path.basename(settings.log_symlink_user),
delete=True,
)
self._safe_symlink(
os.path.dirname(settings.log_symlink_internal),
settings.log_internal,
os.path.basename(settings.log_symlink_internal),
delete=True,
)
_set_logger(logging.getLogger("wandb"))
self._enable_logging(settings.log_user)
self._wl._early_logger_flush(logger)
logger.info(f"Logging user logs to {settings.log_user}")
logger.info(f"Logging internal logs to {settings.log_internal}")
def _make_run_disabled(self) -> RunDisabled:
drun = RunDisabled()
drun.config = wandb.wandb_sdk.wandb_config.Config()
drun.config.update(self.sweep_config)
drun.config.update(self.config)
drun.summary = SummaryDisabled()
drun.log = lambda data, *_, **__: drun.summary.update(data)
drun.finish = lambda *_, **__: module.unset_globals()
drun.step = 0
drun.resumed = False
drun.disabled = True
drun.id = shortuuid.uuid()
drun.name = "dummy-" + drun.id
drun.dir = tempfile.gettempdir()
module.set_global(
run=drun,
config=drun.config,
log=drun.log,
summary=drun.summary,
save=drun.save,
use_artifact=drun.use_artifact,
log_artifact=drun.log_artifact,
define_metric=drun.define_metric,
plot_table=drun.plot_table,
alert=drun.alert,
)
return drun
def _on_init_progress(self, handle: MailboxHandle) -> None:
assert self.printer
line = "Waiting for wandb.init()...\r"
percent_done = handle.percent_done
self.printer.progress_update(line, percent_done=percent_done)
def init(self) -> Union[Run, RunDisabled, None]: # noqa: C901
if logger is None:
raise RuntimeError("Logger not initialized")
logger.info("calling init triggers")
trigger.call("on_init", **self.kwargs)
logger.info(
f"wandb.init called with sweep_config: {self.sweep_config}\nconfig: {self.config}"
)
if self.settings._noop:
return self._make_run_disabled()
if self.settings.reinit or (
self.settings._jupyter and self.settings.reinit is not False
):
if len(self._wl._global_run_stack) > 0:
if len(self._wl._global_run_stack) > 1:
wandb.termwarn(
"If you want to track multiple runs concurrently in wandb, "
"you should use multi-processing not threads" # noqa: E501
)
last_id = self._wl._global_run_stack[-1]._run_id
logger.info(
f"re-initializing run, found existing run on stack: {last_id}"
)
jupyter = (
self.settings._jupyter
and not self.settings.silent
and ipython.in_jupyter()
)
if jupyter:
ipython.display_html(
f"Finishing last run (ID:{last_id}) before initializing another..."
)
self._wl._global_run_stack[-1].finish()
if jupyter:
ipython.display_html(
f"Successfully finished last run (ID:{last_id}). Initializing new run:<br/>"
)
elif isinstance(wandb.run, Run):
allow_return_run = True
manager = self._wl._get_manager()
if manager:
current_pid = os.getpid()
if current_pid != wandb.run._init_pid:
# We shouldn't return a stale global run if we are in a new pid
allow_return_run = False
if allow_return_run:
logger.info("wandb.init() called when a run is still active")
with telemetry.context() as tel:
tel.feature.init_return_run = True
return wandb.run
logger.info("starting backend")
manager = self._wl._get_manager()
if manager:
logger.info("setting up manager")
manager._inform_init(settings=self.settings, run_id=self.settings.run_id)
mailbox = Mailbox()
backend = Backend(settings=self.settings, manager=manager, mailbox=mailbox)
backend.ensure_launched()
backend.server_connect()
logger.info("backend started and connected")
# Make sure we are logged in
# wandb_login._login(_backend=backend, _settings=self.settings)
# resuming needs access to the server, check server_status()?
run = Run(
config=self.config,
settings=self.settings,
sweep_config=self.sweep_config,
launch_config=self.launch_config,
)
# probe the active start method
active_start_method: Optional[str] = None
if self.settings.start_method == "thread":
active_start_method = self.settings.start_method
else:
active_start_method = getattr(
backend._multiprocessing, "get_start_method", lambda: None
)()
# Populate initial telemetry
with telemetry.context(run=run, obj=self._init_telemetry_obj) as tel:
tel.cli_version = wandb.__version__
tel.python_version = platform.python_version()
hf_version = _huggingface_version()
if hf_version:
tel.huggingface_version = hf_version
if self.settings._jupyter:
tel.env.jupyter = True
if self.settings._kaggle:
tel.env.kaggle = True
if self.settings._windows:
tel.env.windows = True
if self.settings.launch:
tel.feature.launch = True
for module_name in telemetry.list_telemetry_imports(only_imported=True):
setattr(tel.imports_init, module_name, True)
if active_start_method == "spawn":
tel.env.start_spawn = True
elif active_start_method == "fork":
tel.env.start_fork = True
elif active_start_method == "forkserver":
tel.env.start_forkserver = True
elif active_start_method == "thread":
tel.env.start_thread = True
if manager:
tel.feature.service = True
tel.env.maybe_mp = _maybe_mp_process(backend)
# todo: detected issues with settings.
if self.settings.__dict__["_Settings__preprocessing_warnings"]:
tel.issues.settings__preprocessing_warnings = True
if self.settings.__dict__["_Settings__validation_warnings"]:
tel.issues.settings__validation_warnings = True
if self.settings.__dict__["_Settings__unexpected_args"]:
tel.issues.settings__unexpected_args = True
if not self.settings.label_disable:
if self.notebook:
run._label_probe_notebook(self.notebook)
else:
run._label_probe_main()
for deprecated_feature, msg in self.deprecated_features_used.items():
warning_message = f"`{deprecated_feature}` is deprecated. {msg}"
deprecate(
field_name=getattr(Deprecated, "init__" + deprecated_feature),
warning_message=warning_message,
run=run,
)
logger.info("updated telemetry")
run._set_library(self._wl)
run._set_backend(backend)
run._set_reporter(self._reporter)
run._set_teardown_hooks(self._teardown_hooks)
# TODO: pass mode to backend
# run_synced = None
backend._hack_set_run(run)
assert backend.interface
backend.interface.publish_header()
# Using GitRepo() blocks & can be slow, depending on user's current git setup.
# We don't want to block run initialization/start request, so populate run's git
# info beforehand.
if not self.settings.disable_git:
run._populate_git_info()
if self.settings._offline:
with telemetry.context(run=run) as tel:
tel.feature.offline = True
run_proto = backend.interface._make_run(run)
backend.interface._publish_run(run_proto)
run._set_run_obj_offline(run_proto)
if self.settings.resume:
wandb.termwarn(
"`resume` will be ignored since W&B syncing is set to `offline`. "
f"Starting a new run with run id {run.id}."
)
else:
run_result = None
error_message: Optional[str] = None
logger.info(
f"communicating run to backend with {self.settings.init_timeout} second timeout"
)
handle = backend.interface.deliver_run(run)
result = handle.wait(
timeout=self.settings.init_timeout, on_progress=self._on_init_progress
)
if result:
run_result = result.run_result
if not run_result:
logger.error("backend process timed out")
error_message = "Error communicating with wandb process"
if active_start_method != "fork":
error_message += (
f"\nFor more info see: {wburls.get('doc_start_err')}"
)
elif run_result.error:
error_message = run_result.error.message
if error_message:
logger.error(f"encountered error: {error_message}")
if not manager:
# Shutdown the backend and get rid of the logger
# we don't need to do console cleanup at this point
backend.cleanup()
self.teardown()
raise UsageError(error_message)
assert run_result and run_result.run
if run_result.run.resumed:
logger.info("run resumed")
with telemetry.context(run=run) as tel:
tel.feature.resumed = True
run._set_run_obj(run_result.run)
run._on_init()
logger.info("starting run threads in backend")
# initiate run (stats and metadata probing)
run_obj = run._run_obj or run._run_obj_offline
self.settings._apply_run_start(message_to_dict(run_obj))
run._update_settings(self.settings)
if manager:
manager._inform_start(settings=self.settings, run_id=self.settings.run_id)
assert backend.interface
assert run_obj
_ = backend.interface.communicate_run_start(run_obj)
self._wl._global_run_stack.append(run)
self.run = run
run._handle_launch_artifact_overrides()
if (
self.settings.launch
and self.settings.launch_config_path
and os.path.exists(self.settings.launch_config_path)
):
run._save(self.settings.launch_config_path)
# put artifacts in run config here
# since doing so earlier will cause an error
# as the run is not upserted
for k, v in self.init_artifact_config.items():
run.config.update({k: v}, allow_val_change=True)
job_artifact = run._launch_artifact_mapping.get(
wandb.util.LAUNCH_JOB_ARTIFACT_SLOT_NAME
)
if job_artifact:
run.use_artifact(job_artifact)
self.backend = backend
self._reporter.set_context(run=run)
run._on_start()
logger.info("run started, returning control to user process")
return run
def getcaller():
# py2 doesnt have stack_info
# src, line, func, stack = logger.findCaller(stack_info=True)
src, line, func = logger.findCaller()[:3]
print("Problem at:", src, line, func)
def _attach(
attach_id: Optional[str] = None,
run_id: Optional[str] = None,
*,
run: Optional["Run"] = None,
) -> Union[Run, RunDisabled, None]:
"""Attach to a run currently executing in another process/thread.
Arguments:
attach_id: (str, optional) The id of the run or an attach identifier
that maps to a run.
run_id: (str, optional) The id of the run to attach to.
run: (Run, optional) The run instance to attach
"""
attach_id = attach_id or run_id
if not ((attach_id is None) ^ (run is None)):
raise UsageError("Either (`attach_id` or `run_id`) or `run` must be specified")
attach_id = attach_id or run._attach_id
if attach_id is None:
raise UsageError(
"Either `attach_id` or `run_id` must be specified or `run` must have `_attach_id`"
)
wandb._assert_is_user_process()
_wl = wandb_setup._setup()
_set_logger(_wl._get_logger())
if logger is None:
raise UsageError("logger is not initialized")
manager = _wl._get_manager()
if manager:
response = manager._inform_attach(attach_id=attach_id)
settings: Settings = copy.copy(_wl._settings)
settings.update(
{
"run_id": attach_id,
"_start_time": response["_start_time"],
"_start_datetime": response["_start_datetime"],
},
source=Source.INIT,
)
# TODO: consolidate this codepath with wandb.init()
mailbox = Mailbox()
backend = Backend(settings=settings, manager=manager, mailbox=mailbox)
backend.ensure_launched()
backend.server_connect()
logger.info("attach backend started and connected")
if run is None:
run = Run(settings=settings)
else:
run._init(settings=settings)
run._set_library(_wl)
run._set_backend(backend)
backend._hack_set_run(run)
assert backend.interface
resp = backend.interface.communicate_attach(attach_id)
if not resp:
raise UsageError("problem")
if resp and resp.error and resp.error.message:
raise UsageError(f"bad: {resp.error.message}")
run._set_run_obj(resp.run)
run._on_attach()
return run
def init(
job_type: Optional[str] = None,
dir: Union[str, pathlib.Path, None] = None,
config: Union[Dict, str, None] = None,
project: Optional[str] = None,
entity: Optional[str] = None,
reinit: bool = None,
tags: Optional[Sequence] = None,
group: Optional[str] = None,
name: Optional[str] = None,
notes: Optional[str] = None,
magic: Union[dict, str, bool] = None,
config_exclude_keys=None,
config_include_keys=None,
anonymous: Optional[str] = None,
mode: Optional[str] = None,
allow_val_change: Optional[bool] = None,
resume: Optional[Union[bool, str]] = None,
force: Optional[bool] = None,
tensorboard=None, # alias for sync_tensorboard
sync_tensorboard=None,
monitor_gym=None,
save_code=None,
id=None,
settings: Union[Settings, Dict[str, Any], None] = None,
) -> Union[Run, RunDisabled, None]:
"""Starts a new run to track and log to W&B.
In an ML training pipeline, you could add `wandb.init()`
to the beginning of your training script as well as your evaluation
script, and each piece would be tracked as a run in W&B.
`wandb.init()` spawns a new background process to log data to a run, and it
also syncs data to wandb.ai by default, so you can see live visualizations.
Call `wandb.init()` to start a run before logging data with `wandb.log()`:
<!--yeadoc-test:init-method-log-->
```python
import wandb
wandb.init()
# ... calculate metrics, generate media
wandb.log({"accuracy": 0.9})
```
`wandb.init()` returns a run object, and you can also access the run object
via `wandb.run`:
<!--yeadoc-test:init-and-assert-global-->
```python
import wandb
run = wandb.init()
assert run is wandb.run
```
At the end of your script, we will automatically call `wandb.finish` to
finalize and cleanup the run. However, if you call `wandb.init` from a
child process, you must explicitly call `wandb.finish` at the end of the
child process.
For more on using `wandb.init()`, including detailed examples, check out our
[guide and FAQs](https://docs.wandb.ai/guides/track/launch).
Arguments:
project: (str, optional) The name of the project where you're sending
the new run. If the project is not specified, the run is put in an
"Uncategorized" project.
entity: (str, optional) An entity is a username or team name where
you're sending runs. This entity must exist before you can send runs
there, so make sure to create your account or team in the UI before
starting to log runs.
If you don't specify an entity, the run will be sent to your default
entity, which is usually your username. Change your default entity
in [your settings](https://wandb.ai/settings) under "default location
to create new projects".
config: (dict, argparse, absl.flags, str, optional)
This sets `wandb.config`, a dictionary-like object for saving inputs
to your job, like hyperparameters for a model or settings for a data
preprocessing job. The config will show up in a table in the UI that
you can use to group, filter, and sort runs. Keys should not contain
`.` in their names, and values should be under 10 MB.
If dict, argparse or absl.flags: will load the key value pairs into
the `wandb.config` object.
If str: will look for a yaml file by that name, and load config from
that file into the `wandb.config` object.
save_code: (bool, optional) Turn this on to save the main script or
notebook to W&B. This is valuable for improving experiment
reproducibility and to diff code across experiments in the UI. By
default this is off, but you can flip the default behavior to on
in [your settings page](https://wandb.ai/settings).
group: (str, optional) Specify a group to organize individual runs into
a larger experiment. For example, you might be doing cross
validation, or you might have multiple jobs that train and evaluate
a model against different test sets. Group gives you a way to
organize runs together into a larger whole, and you can toggle this
on and off in the UI. For more details, see our
[guide to grouping runs](https://docs.wandb.com/library/grouping).
job_type: (str, optional) Specify the type of run, which is useful when
you're grouping runs together into larger experiments using group.
For example, you might have multiple jobs in a group, with job types
like train and eval. Setting this makes it easy to filter and group
similar runs together in the UI so you can compare apples to apples.
tags: (list, optional) A list of strings, which will populate the list
of tags on this run in the UI. Tags are useful for organizing runs
together, or applying temporary labels like "baseline" or
"production". It's easy to add and remove tags in the UI, or filter
down to just runs with a specific tag.
name: (str, optional) A short display name for this run, which is how
you'll identify this run in the UI. By default, we generate a random
two-word name that lets you easily cross-reference runs from the
table to charts. Keeping these run names short makes the chart
legends and tables easier to read. If you're looking for a place to
save your hyperparameters, we recommend saving those in config.
notes: (str, optional) A longer description of the run, like a `-m` commit
message in git. This helps you remember what you were doing when you
ran this run.
dir: (str or pathlib.Path, optional) An absolute path to a directory where
metadata will be stored. When you call `download()` on an artifact,
this is the directory where downloaded files will be saved. By default,
this is the `./wandb` directory.
resume: (bool, str, optional) Sets the resuming behavior. Options:
`"allow"`, `"must"`, `"never"`, `"auto"` or `None`. Defaults to `None`.
Cases:
- `None` (default): If the new run has the same ID as a previous run,
this run overwrites that data.
- `"auto"` (or `True`): if the previous run on this machine crashed,
automatically resume it. Otherwise, start a new run.
- `"allow"`: if id is set with `init(id="UNIQUE_ID")` or
`WANDB_RUN_ID="UNIQUE_ID"` and it is identical to a previous run,
wandb will automatically resume the run with that id. Otherwise,
wandb will start a new run.
- `"never"`: if id is set with `init(id="UNIQUE_ID")` or
`WANDB_RUN_ID="UNIQUE_ID"` and it is identical to a previous run,
wandb will crash.
- `"must"`: if id is set with `init(id="UNIQUE_ID")` or
`WANDB_RUN_ID="UNIQUE_ID"` and it is identical to a previous run,
wandb will automatically resume the run with the id. Otherwise
wandb will crash.
See [our guide to resuming runs](https://docs.wandb.com/library/advanced/resuming)
for more.
reinit: (bool, optional) Allow multiple `wandb.init()` calls in the same
process. (default: `False`)
magic: (bool, dict, or str, optional) The bool controls whether we try to
auto-instrument your script, capturing basic details of your run
without you having to add more wandb code. (default: `False`)
You can also pass a dict, json string, or yaml filename.
config_exclude_keys: (list, optional) string keys to exclude from
`wandb.config`.
config_include_keys: (list, optional) string keys to include in
`wandb.config`.
anonymous: (str, optional) Controls anonymous data logging. Options:
- `"never"` (default): requires you to link your W&B account before
tracking the run, so you don't accidentally create an anonymous