-
Notifications
You must be signed in to change notification settings - Fork 618
/
util.py
1788 lines (1437 loc) 路 54.7 KB
/
util.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
import base64
import binascii
import codecs
import colorsys
import contextlib
import errno
import functools
import gzip
import hashlib
import importlib
import json
import logging
import math
import numbers
import os
import pathlib
import platform
import queue
import random
import re
import shlex
import socket
import sys
import tarfile
import tempfile
import threading
import time
import traceback
import urllib
from datetime import date, datetime, timedelta
from importlib import import_module
from sys import getsizeof
from types import ModuleType, TracebackType
from typing import (
IO,
Any,
Callable,
Dict,
Generator,
List,
Mapping,
Optional,
Sequence,
TextIO,
Tuple,
Type,
Union,
)
from urllib.parse import quote
import requests
import sentry_sdk # type: ignore
import shortuuid # type: ignore
import yaml
import wandb
from wandb.env import SENTRY_DSN, error_reporting_enabled, get_app_url
from wandb.errors import CommError, UsageError, term
CheckRetryFnType = Callable[[Exception], Union[bool, timedelta]]
logger = logging.getLogger(__name__)
_not_importable = set()
MAX_LINE_BYTES = (10 << 20) - (100 << 10) # imposed by back end
IS_GIT = os.path.exists(os.path.join(os.path.dirname(__file__), "..", ".git"))
RE_WINFNAMES = re.compile(r'[<>:"\\?*]')
# these match the environments for gorilla
if IS_GIT:
SENTRY_ENV = "development"
else:
SENTRY_ENV = "production"
PLATFORM_WINDOWS = "windows"
PLATFORM_LINUX = "linux"
PLATFORM_BSD = "bsd"
PLATFORM_DARWIN = "darwin"
PLATFORM_UNKNOWN = "unknown"
LAUNCH_JOB_ARTIFACT_SLOT_NAME = "_wandb_job"
def get_platform_name() -> str:
if sys.platform.startswith("win"):
return PLATFORM_WINDOWS
elif sys.platform.startswith("darwin"):
return PLATFORM_DARWIN
elif sys.platform.startswith("linux"):
return PLATFORM_LINUX
elif sys.platform.startswith(
(
"dragonfly",
"freebsd",
"netbsd",
"openbsd",
)
):
return PLATFORM_BSD
else:
return PLATFORM_UNKNOWN
# TODO(sentry): This code needs to be moved, sentry shouldn't be initialized as a
# side effect of loading a module.
sentry_client: Optional["sentry_sdk.client.Client"] = None
sentry_hub: Optional["sentry_sdk.hub.Hub"] = None
sentry_default_dsn = (
"https://a2f1d701163c42b097b9588e56b1c37e@o151352.ingest.sentry.io/5288891"
)
if error_reporting_enabled():
sentry_dsn = os.environ.get(SENTRY_DSN, sentry_default_dsn)
sentry_client = sentry_sdk.Client(
dsn=sentry_dsn,
default_integrations=False,
environment=SENTRY_ENV,
release=wandb.__version__,
)
sentry_hub = sentry_sdk.Hub(sentry_client)
POW_10_BYTES = [
("B", 10**0),
("KB", 10**3),
("MB", 10**6),
("GB", 10**9),
("TB", 10**12),
("PB", 10**15),
("EB", 10**18),
]
POW_2_BYTES = [
("B", 2**0),
("KiB", 2**10),
("MiB", 2**20),
("GiB", 2**30),
("TiB", 2**40),
("PiB", 2**50),
("EiB", 2**60),
]
def sentry_message(message: str) -> None:
if error_reporting_enabled():
sentry_hub.capture_message(message) # type: ignore
return None
def sentry_exc(
exc: Union[
str,
BaseException,
Tuple[
Optional[Type[BaseException]],
Optional[BaseException],
Optional[TracebackType],
],
None,
],
delay: bool = False,
) -> None:
if error_reporting_enabled():
if isinstance(exc, str):
sentry_hub.capture_exception(Exception(exc)) # type: ignore
else:
sentry_hub.capture_exception(exc) # type: ignore
if delay:
time.sleep(2)
return None
def sentry_reraise(exc: Any) -> None:
"""Re-raise an exception after logging it to Sentry
Use this for top-level exceptions when you want the user to see the traceback.
Must be called from within an exception handler.
"""
sentry_exc(exc)
# this will messily add this "reraise" function to the stack trace
# but hopefully it's not too bad
raise exc.with_traceback(sys.exc_info()[2])
def sentry_set_scope(
settings_dict: Optional[
Union[
"wandb.sdk.wandb_settings.Settings",
"wandb.sdk.internal.settings_static.SettingsStatic",
]
] = None,
process_context: Optional[str] = None,
) -> None:
if not error_reporting_enabled():
return None
# Tags come from two places: settings and args passed into this func.
args = dict(locals())
del args["settings_dict"]
settings_tags = [
"entity",
"project",
"run_id",
"run_url",
"sweep_url",
"sweep_id",
"deployment",
"_require_service",
]
s = settings_dict
# convenience function for getting attr from settings
def get(key: str) -> Any:
return getattr(s, key, None)
with sentry_hub.configure_scope() as scope: # type: ignore
scope.set_tag("platform", get_platform_name())
# apply settings tags
if s is not None:
for tag in settings_tags:
val = get(tag)
if val not in [None, ""]:
scope.set_tag(tag, val)
python_runtime = (
"colab"
if get("_colab")
else ("jupyter" if get("_jupyter") else "python")
)
scope.set_tag("python_runtime", python_runtime)
# Hack for constructing run_url and sweep_url given run_id and sweep_id
required = ["entity", "project", "base_url"]
params = {key: get(key) for key in required}
if all(params.values()):
# here we're guaranteed that entity, project, base_url all have valid values
app_url = wandb.util.app_url(params["base_url"])
e, p = (quote(params[k]) for k in ["entity", "project"])
# TODO: the settings object will be updated to contain run_url and sweep_url
# This is done by passing a settings_map in the run_start protocol buffer message
for word in ["run", "sweep"]:
_url, _id = f"{word}_url", f"{word}_id"
if not get(_url) and get(_id):
scope.set_tag(_url, f"{app_url}/{e}/{p}/{word}s/{get(_id)}")
if hasattr(s, "email"):
scope.user = {"email": s.email}
# apply directly passed-in tags
for tag, value in args.items():
if value is not None and value != "":
scope.set_tag(tag, value)
def vendor_setup() -> Callable:
"""This enables us to use the vendor directory for packages we don't depend on
Returns a function to call after imports are complete. Make sure to call this
function or you will modify the user's path which is never good. The pattern should be:
reset_path = vendor_setup()
# do any vendor imports...
reset_path()
"""
original_path = [directory for directory in sys.path]
def reset_import_path() -> None:
sys.path = original_path
parent_dir = os.path.abspath(os.path.dirname(__file__))
vendor_dir = os.path.join(parent_dir, "vendor")
vendor_packages = ("gql-0.2.0", "graphql-core-1.1")
package_dirs = [os.path.join(vendor_dir, p) for p in vendor_packages]
for p in [vendor_dir] + package_dirs:
if p not in sys.path:
sys.path.insert(1, p)
return reset_import_path
def apple_gpu_stats_binary() -> str:
parent_dir = os.path.abspath(os.path.dirname(__file__))
return os.path.join(parent_dir, "bin", "apple_gpu_stats")
def vendor_import(name: str) -> Any:
reset_path = vendor_setup()
module = import_module(name)
reset_path()
return module
def get_module(name: str, required: Optional[Union[str, bool]] = None) -> Any:
"""
Return module or None. Absolute import is required.
:param (str) name: Dot-separated module path. E.g., 'scipy.stats'.
:param (str) required: A string to raise a ValueError if missing
:return: (module|None) If import succeeds, the module will be returned.
"""
if name not in _not_importable:
try:
return import_module(name)
except Exception:
_not_importable.add(name)
msg = f"Error importing optional module {name}"
if required:
logger.exception(msg)
if required and name in _not_importable:
raise wandb.Error(required)
def get_optional_module(name) -> Optional["importlib.ModuleInterface"]: # type: ignore
return get_module(name)
np = get_module("numpy")
# TODO: Revisit these limits
VALUE_BYTES_LIMIT = 100000
def app_url(api_url: str) -> str:
"""Returns the frontend app url without a trailing slash."""
# TODO: move me to settings
app_url = get_app_url()
if app_url is not None:
return str(app_url.strip("/"))
if "://api.wandb.test" in api_url:
# dev mode
return api_url.replace("://api.", "://app.").strip("/")
elif "://api.wandb." in api_url:
# cloud
return api_url.replace("://api.", "://").strip("/")
elif "://api." in api_url:
# onprem cloud
return api_url.replace("://api.", "://app.").strip("/")
# wandb/local
return api_url
def get_full_typename(o: Any) -> Any:
"""We determine types based on type names so we don't have to import
(and therefore depend on) PyTorch, TensorFlow, etc.
"""
instance_name = o.__class__.__module__ + "." + o.__class__.__name__
if instance_name in ["builtins.module", "__builtin__.module"]:
return o.__name__
else:
return instance_name
def get_h5_typename(o: Any) -> Any:
typename = get_full_typename(o)
if is_tf_tensor_typename(typename):
return "tensorflow.Tensor"
elif is_pytorch_tensor_typename(typename):
return "torch.Tensor"
else:
return o.__class__.__module__.split(".")[0] + "." + o.__class__.__name__
def is_uri(string: str) -> bool:
parsed_uri = urllib.parse.urlparse(string)
return len(parsed_uri.scheme) > 0
def local_file_uri_to_path(uri: str) -> str:
"""
Convert URI to local filesystem path.
No-op if the uri does not have the expected scheme.
"""
path = urllib.parse.urlparse(uri).path if uri.startswith("file:") else uri
return urllib.request.url2pathname(path)
def get_local_path_or_none(path_or_uri: str) -> Optional[str]:
"""Check if the argument is a local path (no scheme or file:///) and return local path if true,
None otherwise.
"""
parsed_uri = urllib.parse.urlparse(path_or_uri)
if (
len(parsed_uri.scheme) == 0
or parsed_uri.scheme == "file"
and len(parsed_uri.netloc) == 0
):
return local_file_uri_to_path(path_or_uri)
else:
return None
def make_tarfile(
output_filename: str,
source_dir: str,
archive_name: str,
custom_filter: Optional[Callable] = None,
) -> None:
# Helper for filtering out modification timestamps
def _filter_timestamps(tar_info: "tarfile.TarInfo") -> Optional["tarfile.TarInfo"]:
tar_info.mtime = 0
return tar_info if custom_filter is None else custom_filter(tar_info)
descriptor, unzipped_filename = tempfile.mkstemp()
try:
with tarfile.open(unzipped_filename, "w") as tar:
tar.add(source_dir, arcname=archive_name, filter=_filter_timestamps)
# When gzipping the tar, don't include the tar's filename or modification time in the
# zipped archive (see https://docs.python.org/3/library/gzip.html#gzip.GzipFile)
with gzip.GzipFile(
filename="", fileobj=open(output_filename, "wb"), mode="wb", mtime=0
) as gzipped_tar, open(unzipped_filename, "rb") as tar_file:
gzipped_tar.write(tar_file.read())
finally:
os.close(descriptor)
os.remove(unzipped_filename)
def _user_args_to_dict(arguments: List[str]) -> Dict[str, Union[str, bool]]:
user_dict = dict()
value: Union[str, bool]
name: str
i = 0
while i < len(arguments):
arg = arguments[i]
split = arg.split("=", maxsplit=1)
# flag arguments don't require a value -> set to True if specified
if len(split) == 1 and (
i + 1 >= len(arguments) or arguments[i + 1].startswith("-")
):
name = split[0].lstrip("-")
value = True
i += 1
elif len(split) == 1 and not arguments[i + 1].startswith("-"):
name = split[0].lstrip("-")
value = arguments[i + 1]
i += 2
elif len(split) == 2:
name = split[0].lstrip("-")
value = split[1]
i += 1
if name in user_dict:
wandb.termerror(f"Repeated parameter: '{name}'")
sys.exit(1)
user_dict[name] = value
return user_dict
def is_tf_tensor(obj: Any) -> bool:
import tensorflow # type: ignore
return isinstance(obj, tensorflow.Tensor)
def is_tf_tensor_typename(typename: str) -> bool:
return typename.startswith("tensorflow.") and (
"Tensor" in typename or "Variable" in typename
)
def is_tf_eager_tensor_typename(typename: str) -> bool:
return typename.startswith("tensorflow.") and ("EagerTensor" in typename)
def is_pytorch_tensor(obj: Any) -> bool:
import torch # type: ignore
return isinstance(obj, torch.Tensor)
def is_pytorch_tensor_typename(typename: str) -> bool:
return typename.startswith("torch.") and (
"Tensor" in typename or "Variable" in typename
)
def is_jax_tensor_typename(typename: str) -> bool:
return typename.startswith("jaxlib.") and "DeviceArray" in typename
def get_jax_tensor(obj: Any) -> Optional[Any]:
import jax # type: ignore
return jax.device_get(obj)
def is_fastai_tensor_typename(typename: str) -> bool:
return typename.startswith("fastai.") and ("Tensor" in typename)
def is_pandas_data_frame_typename(typename: str) -> bool:
return typename.startswith("pandas.") and "DataFrame" in typename
def is_matplotlib_typename(typename: str) -> bool:
return typename.startswith("matplotlib.")
def is_plotly_typename(typename: str) -> bool:
return typename.startswith("plotly.")
def is_plotly_figure_typename(typename: str) -> bool:
return typename.startswith("plotly.") and typename.endswith(".Figure")
def is_numpy_array(obj: Any) -> bool:
return np and isinstance(obj, np.ndarray)
def is_pandas_data_frame(obj: Any) -> bool:
return is_pandas_data_frame_typename(get_full_typename(obj))
def ensure_matplotlib_figure(obj: Any) -> Any:
"""Extract the current figure from a matplotlib object or return the object if it's a figure.
raises ValueError if the object can't be converted.
"""
import matplotlib # type: ignore
from matplotlib.figure import Figure # type: ignore
# there are combinations of plotly and matplotlib versions that don't work well together,
# this patches matplotlib to add a removed method that plotly assumes exists
from matplotlib.spines import Spine # type: ignore
def is_frame_like(self: Any) -> bool:
"""Return True if directly on axes frame.
This is useful for determining if a spine is the edge of an
old style MPL plot. If so, this function will return True.
"""
position = self._position or ("outward", 0.0)
if isinstance(position, str):
if position == "center":
position = ("axes", 0.5)
elif position == "zero":
position = ("data", 0)
if len(position) != 2:
raise ValueError("position should be 2-tuple")
position_type, amount = position # type: ignore
if position_type == "outward" and amount == 0:
return True
else:
return False
Spine.is_frame_like = is_frame_like
if obj == matplotlib.pyplot:
obj = obj.gcf()
elif not isinstance(obj, Figure):
if hasattr(obj, "figure"):
obj = obj.figure
# Some matplotlib objects have a figure function
if not isinstance(obj, Figure):
raise ValueError(
"Only matplotlib.pyplot or matplotlib.pyplot.Figure objects are accepted."
)
return obj
def matplotlib_to_plotly(obj: Any) -> Any:
obj = ensure_matplotlib_figure(obj)
tools = get_module(
"plotly.tools",
required=(
"plotly is required to log interactive plots, install with: "
"`pip install plotly` or convert the plot to an image with `wandb.Image(plt)`"
),
)
return tools.mpl_to_plotly(obj)
def matplotlib_contains_images(obj: Any) -> bool:
obj = ensure_matplotlib_figure(obj)
return any(len(ax.images) > 0 for ax in obj.axes)
def json_friendly( # noqa: C901
obj: Any,
) -> Union[Tuple[Any, bool], Tuple[Union[None, str, float], bool]]: # noqa: C901
"""Convert an object into something that's more becoming of JSON"""
converted = True
typename = get_full_typename(obj)
if is_tf_eager_tensor_typename(typename):
obj = obj.numpy()
elif is_tf_tensor_typename(typename):
try:
obj = obj.eval()
except RuntimeError:
obj = obj.numpy()
elif is_pytorch_tensor_typename(typename) or is_fastai_tensor_typename(typename):
try:
if obj.requires_grad:
obj = obj.detach()
except AttributeError:
pass # before 0.4 is only present on variables
try:
obj = obj.data
except RuntimeError:
pass # happens for Tensors before 0.4
if obj.size():
obj = obj.cpu().detach().numpy()
else:
return obj.item(), True
elif is_jax_tensor_typename(typename):
obj = get_jax_tensor(obj)
if is_numpy_array(obj):
if obj.size == 1:
obj = obj.flatten()[0]
elif obj.size <= 32:
obj = obj.tolist()
elif np and isinstance(obj, np.generic):
obj = obj.item()
if isinstance(obj, float) and math.isnan(obj):
obj = None
elif isinstance(obj, np.generic) and (
obj.dtype.kind == "f" or obj.dtype == "bfloat16"
):
# obj is a numpy float with precision greater than that of native python float
# (i.e., float96 or float128) or it is of custom type such as bfloat16.
# in these cases, obj.item() does not return a native
# python float (in the first case - to avoid loss of precision,
# so we need to explicitly cast this down to a 64bit float)
obj = float(obj)
elif isinstance(obj, bytes):
obj = obj.decode("utf-8")
elif isinstance(obj, (datetime, date)):
obj = obj.isoformat()
elif callable(obj):
obj = (
f"{obj.__module__}.{obj.__qualname__}"
if hasattr(obj, "__qualname__") and hasattr(obj, "__module__")
else str(obj)
)
elif isinstance(obj, float) and math.isnan(obj):
obj = None
else:
converted = False
if getsizeof(obj) > VALUE_BYTES_LIMIT:
wandb.termwarn(
"Serializing object of type {} that is {} bytes".format(
type(obj).__name__, getsizeof(obj)
)
)
return obj, converted
def json_friendly_val(val: Any) -> Any:
"""Make any value (including dict, slice, sequence, etc) JSON friendly"""
converted: Union[dict, list]
if isinstance(val, dict):
converted = {}
for key, value in val.items():
converted[key] = json_friendly_val(value)
return converted
if isinstance(val, slice):
converted = dict(
slice_start=val.start, slice_step=val.step, slice_stop=val.stop
)
return converted
val, _ = json_friendly(val)
if isinstance(val, Sequence) and not isinstance(val, str):
converted = []
for value in val:
converted.append(json_friendly_val(value))
return converted
else:
if val.__class__.__module__ not in ("builtins", "__builtin__"):
val = str(val)
return val
def convert_plots(obj: Any) -> Any:
if is_matplotlib_typename(get_full_typename(obj)):
tools = get_module(
"plotly.tools",
required=(
"plotly is required to log interactive plots, install with: "
"`pip install plotly` or convert the plot to an image with `wandb.Image(plt)`"
),
)
obj = tools.mpl_to_plotly(obj)
if is_plotly_typename(get_full_typename(obj)):
return {"_type": "plotly", "plot": obj.to_plotly_json()}
else:
return obj
def maybe_compress_history(obj: Any) -> Tuple[Any, bool]:
if np and isinstance(obj, np.ndarray) and obj.size > 32:
return wandb.Histogram(obj, num_bins=32).to_json(), True
else:
return obj, False
def maybe_compress_summary(obj: Any, h5_typename: str) -> Tuple[Any, bool]:
if np and isinstance(obj, np.ndarray) and obj.size > 32:
return (
{
"_type": h5_typename, # may not be ndarray
"var": np.var(obj).item(),
"mean": np.mean(obj).item(),
"min": np.amin(obj).item(),
"max": np.amax(obj).item(),
"10%": np.percentile(obj, 10),
"25%": np.percentile(obj, 25),
"75%": np.percentile(obj, 75),
"90%": np.percentile(obj, 90),
"size": obj.size,
},
True,
)
else:
return obj, False
def launch_browser(attempt_launch_browser: bool = True) -> bool:
"""Decide if we should launch a browser"""
_display_variables = ["DISPLAY", "WAYLAND_DISPLAY", "MIR_SOCKET"]
_webbrowser_names_blocklist = ["www-browser", "lynx", "links", "elinks", "w3m"]
import webbrowser
launch_browser = attempt_launch_browser
if launch_browser:
if "linux" in sys.platform and not any(
os.getenv(var) for var in _display_variables
):
launch_browser = False
try:
browser = webbrowser.get()
if hasattr(browser, "name") and browser.name in _webbrowser_names_blocklist:
launch_browser = False
except webbrowser.Error:
launch_browser = False
return launch_browser
def generate_id(length: int = 8) -> str:
# ~3t run ids (36**8)
run_gen = shortuuid.ShortUUID(alphabet=list("0123456789abcdefghijklmnopqrstuvwxyz"))
return str(run_gen.random(length))
def parse_tfjob_config() -> Any:
"""Attempts to parse TFJob config, returning False if it can't find it"""
if os.getenv("TF_CONFIG"):
try:
return json.loads(os.environ["TF_CONFIG"])
except ValueError:
return False
else:
return False
class WandBJSONEncoder(json.JSONEncoder):
"""A JSON Encoder that handles some extra types."""
def default(self, obj: Any) -> Any:
if hasattr(obj, "json_encode"):
return obj.json_encode()
# if hasattr(obj, 'to_json'):
# return obj.to_json()
tmp_obj, converted = json_friendly(obj)
if converted:
return tmp_obj
return json.JSONEncoder.default(self, obj)
class WandBJSONEncoderOld(json.JSONEncoder):
"""A JSON Encoder that handles some extra types."""
def default(self, obj: Any) -> Any:
tmp_obj, converted = json_friendly(obj)
tmp_obj, compressed = maybe_compress_summary(tmp_obj, get_h5_typename(obj))
if converted:
return tmp_obj
return json.JSONEncoder.default(self, tmp_obj)
class WandBHistoryJSONEncoder(json.JSONEncoder):
"""A JSON Encoder that handles some extra types.
This encoder turns numpy like objects with a size > 32 into histograms"""
def default(self, obj: Any) -> Any:
obj, converted = json_friendly(obj)
obj, compressed = maybe_compress_history(obj)
if converted:
return obj
return json.JSONEncoder.default(self, obj)
class JSONEncoderUncompressed(json.JSONEncoder):
"""A JSON Encoder that handles some extra types.
This encoder turns numpy like objects with a size > 32 into histograms"""
def default(self, obj: Any) -> Any:
if is_numpy_array(obj):
return obj.tolist()
elif np and isinstance(obj, np.generic):
obj = obj.item()
return json.JSONEncoder.default(self, obj)
def json_dump_safer(obj: Any, fp: IO[str], **kwargs: Any) -> None:
"""Convert obj to json, with some extra encodable types."""
return json.dump(obj, fp, cls=WandBJSONEncoder, **kwargs)
def json_dumps_safer(obj: Any, **kwargs: Any) -> str:
"""Convert obj to json, with some extra encodable types."""
return json.dumps(obj, cls=WandBJSONEncoder, **kwargs)
# This is used for dumping raw json into files
def json_dump_uncompressed(obj: Any, fp: IO[str], **kwargs: Any) -> None:
"""Convert obj to json, with some extra encodable types."""
return json.dump(obj, fp, cls=JSONEncoderUncompressed, **kwargs)
def json_dumps_safer_history(obj: Any, **kwargs: Any) -> str:
"""Convert obj to json, with some extra encodable types, including histograms"""
return json.dumps(obj, cls=WandBHistoryJSONEncoder, **kwargs)
def make_json_if_not_number(
v: Union[int, float, str, Mapping, Sequence]
) -> Union[int, float, str]:
"""If v is not a basic type convert it to json."""
if isinstance(v, (float, int)):
return v
return json_dumps_safer(v)
def make_safe_for_json(obj: Any) -> Any:
"""Replace invalid json floats with strings. Also converts to lists and dicts."""
if isinstance(obj, Mapping):
return {k: make_safe_for_json(v) for k, v in obj.items()}
elif isinstance(obj, str):
# str's are Sequence, so we need to short-circuit
return obj
elif isinstance(obj, Sequence):
return [make_safe_for_json(v) for v in obj]
elif isinstance(obj, float):
# W&B backend and UI handle these strings
if obj != obj: # standard way to check for NaN
return "NaN"
elif obj == float("+inf"):
return "Infinity"
elif obj == float("-inf"):
return "-Infinity"
return obj
def mkdir_exists_ok(path: str) -> bool:
try:
os.makedirs(path)
return True
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
return False
else:
raise
def no_retry_auth(e: Any) -> bool:
if hasattr(e, "exception"):
e = e.exception
if not isinstance(e, requests.HTTPError):
return True
if e.response is None:
return True
# Don't retry bad request errors; raise immediately
if e.response.status_code in (400, 409):
return False
# Retry all non-forbidden/unauthorized/not-found errors.
if e.response.status_code not in (401, 403, 404):
return True
# Crash w/message on forbidden/unauthorized errors.
if e.response.status_code == 401:
raise CommError("Invalid or missing api_key. Run `wandb login`")
elif wandb.run:
raise CommError(f"Permission denied to access {wandb.run.path}")
else:
raise CommError("Permission denied, ask the project owner to grant you access")
def check_retry_conflict(e: Any) -> Optional[bool]:
"""Check if the exception is a conflict type so it can be retried.
Returns:
True - Should retry this operation
False - Should not retry this operation
None - No decision, let someone else decide
"""
if hasattr(e, "exception"):
e = e.exception
if isinstance(e, requests.HTTPError) and e.response is not None:
if e.response.status_code == 409:
return True
return None
def check_retry_conflict_or_gone(e: Any) -> Optional[bool]:
"""Check if the exception is a conflict or gone type so it can be retried or not.
Returns:
True - Should retry this operation
False - Should not retry this operation
None - No decision, let someone else decide
"""
if hasattr(e, "exception"):
e = e.exception
if isinstance(e, requests.HTTPError) and e.response is not None:
if e.response.status_code == 409:
return True
if e.response.status_code == 410:
return False
return None
def make_check_retry_fn(
fallback_retry_fn: CheckRetryFnType,
check_fn: Callable[[Exception], Optional[bool]],
check_timedelta: Optional[timedelta] = None,
) -> CheckRetryFnType:
"""Return a check_retry_fn which can be used by lib.Retry().
Arguments:
fallback_fn: Use this function if check_fn didn't decide if a retry should happen.
check_fn: Function which returns bool if retry should happen or None if unsure.
check_timedelta: Optional retry timeout if we check_fn matches the exception
"""
def check_retry_fn(e: Exception) -> Union[bool, timedelta]:
check = check_fn(e)
if check is None:
return fallback_retry_fn(e)
if check is False:
return False
if check_timedelta:
return check_timedelta
return True
return check_retry_fn
def find_runner(program: str) -> Union[None, list, List[str]]:
"""Return a command that will run program.
Arguments:
program: The string name of the program to try to run.
Returns:
commandline list of strings to run the program (eg. with subprocess.call()) or None
"""
if os.path.isfile(program) and not os.access(program, os.X_OK):
# program is a path to a non-executable file
try:
opened = open(program)
except OSError: # PermissionError doesn't exist in 2.7
return None
first_line = opened.readline().strip()
if first_line.startswith("#!"):
return shlex.split(first_line[2:])
if program.endswith(".py"):
return [sys.executable]
return None
def downsample(values: Sequence, target_length: int) -> list:
"""Downsamples 1d values to target_length, including start and end.
Algorithm just rounds index down.
Values can be any sequence, including a generator.
"""
if not target_length > 1:
raise UsageError("target_length must be > 1")
values = list(values)
if len(values) < target_length:
return values
ratio = float(len(values) - 1) / (target_length - 1)
result = []
for i in range(target_length):
result.append(values[int(i * ratio)])
return result
def has_num(dictionary: Mapping, key: Any) -> bool:
return key in dictionary and isinstance(dictionary[key], numbers.Number)
def md5_file(path: str) -> str: