-
Notifications
You must be signed in to change notification settings - Fork 618
/
wandb_artifacts.py
2053 lines (1759 loc) 路 69.2 KB
/
wandb_artifacts.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 contextlib
import hashlib
import json
import os
import pathlib
import re
import shutil
import tempfile
import time
from typing import (
Any,
cast,
Dict,
Generator,
IO,
List,
Mapping,
Optional,
Sequence,
Tuple,
TYPE_CHECKING,
Union,
)
from urllib.parse import parse_qsl, quote, urlparse
import requests
import urllib3
import wandb
from wandb import env
from wandb import util
from wandb.apis import InternalApi, PublicApi
from wandb.apis.public import Artifact as PublicArtifact
import wandb.data_types as data_types
from wandb.errors import CommError
from wandb.errors.term import termlog, termwarn
from wandb.sdk.internal import progress
from . import lib as wandb_lib
from .data_types._dtypes import Type, TypeRegistry
from .interface.artifacts import ( # noqa: F401 pylint: disable=unused-import
Artifact as ArtifactInterface,
ArtifactEntry,
ArtifactManifest,
ArtifactsCache,
b64_string_to_hex,
get_artifacts_cache,
md5_file_b64,
md5_string,
StorageHandler,
StorageLayout,
StoragePolicy,
)
if TYPE_CHECKING:
import google.cloud.storage as gcs_module # type: ignore
import boto3 # type: ignore
import wandb.filesync.step_prepare.StepPrepare as StepPrepare # type: ignore
# This makes the first sleep 1s, and then doubles it up to total times,
# which makes for ~18 hours.
_REQUEST_RETRY_STRATEGY = urllib3.util.retry.Retry(
backoff_factor=1,
total=16,
status_forcelist=(308, 408, 409, 429, 500, 502, 503, 504),
)
_REQUEST_POOL_CONNECTIONS = 64
_REQUEST_POOL_MAXSIZE = 64
ARTIFACT_TMP = tempfile.TemporaryDirectory("wandb-artifacts")
class _AddedObj:
def __init__(self, entry: ArtifactEntry, obj: data_types.WBValue):
self.entry = entry
self.obj = obj
def _normalize_metadata(metadata: Optional[Dict[str, Any]]) -> Dict[str, Any]:
if metadata is None:
return {}
if not isinstance(metadata, dict):
raise TypeError(f"metadata must be dict, not {type(metadata)}")
return cast(
Dict[str, Any], json.loads(json.dumps(util.json_friendly_val(metadata)))
)
class Artifact(ArtifactInterface):
"""
Flexible and lightweight building block for dataset and model versioning.
Constructs an empty artifact whose contents can be populated using its
`add` family of functions. Once the artifact has all the desired files,
you can call `wandb.log_artifact()` to log it.
Arguments:
name: (str) A human-readable name for this artifact, which is how you
can identify this artifact in the UI or reference it in `use_artifact`
calls. Names can contain letters, numbers, underscores, hyphens, and
dots. The name must be unique across a project.
type: (str) The type of the artifact, which is used to organize and differentiate
artifacts. Common types include `dataset` or `model`, but you can use any string
containing letters, numbers, underscores, hyphens, and dots.
description: (str, optional) Free text that offers a description of the artifact. The
description is markdown rendered in the UI, so this is a good place to place tables,
links, etc.
metadata: (dict, optional) Structured data associated with the artifact,
for example class distribution of a dataset. This will eventually be queryable
and plottable in the UI. There is a hard limit of 100 total keys.
Examples:
Basic usage
```
wandb.init()
artifact = wandb.Artifact('mnist', type='dataset')
artifact.add_dir('mnist/')
wandb.log_artifact(artifact)
```
Raises:
Exception: if problem.
Returns:
An `Artifact` object.
"""
_added_objs: Dict[int, _AddedObj]
_added_local_paths: Dict[str, ArtifactEntry]
_distributed_id: Optional[str]
_metadata: dict
_logged_artifact: Optional[ArtifactInterface]
_incremental: bool
_client_id: str
def __init__(
self,
name: str,
type: str,
description: Optional[str] = None,
metadata: Optional[dict] = None,
incremental: Optional[bool] = None,
use_as: Optional[str] = None,
) -> None:
if not re.match(r"^[a-zA-Z0-9_\-.]+$", name):
raise ValueError(
"Artifact name may only contain alphanumeric characters, dashes, underscores, and dots. "
'Invalid name: "%s"' % name
)
metadata = _normalize_metadata(metadata)
# TODO: this shouldn't be a property of the artifact. It's a more like an
# argument to log_artifact.
storage_layout = StorageLayout.V2
if env.get_use_v1_artifacts():
storage_layout = StorageLayout.V1
self._storage_policy = WandbStoragePolicy(
config={
"storageLayout": storage_layout,
# TODO: storage region
}
)
self._api = InternalApi()
self._final = False
self._digest = ""
self._file_entries = None
self._manifest = ArtifactManifestV1(self, self._storage_policy)
self._cache = get_artifacts_cache()
self._added_objs = {}
self._added_local_paths = {}
# You can write into this directory when creating artifact files
self._artifact_dir = tempfile.TemporaryDirectory()
self._type = type
self._name = name
self._description = description
self._metadata = metadata
self._distributed_id = None
self._logged_artifact = None
self._incremental = False
self._client_id = util.generate_id(128)
self._sequence_client_id = util.generate_id(128)
self._cache.store_client_artifact(self)
self._use_as = use_as
if incremental:
self._incremental = incremental
wandb.termwarn("Using experimental arg `incremental`")
@property
def id(self) -> Optional[str]:
if self._logged_artifact:
return self._logged_artifact.id
# The artifact hasn't been saved so an ID doesn't exist yet.
return None
@property
def version(self) -> str:
if self._logged_artifact:
return self._logged_artifact.version
raise ValueError(
"Cannot call version on an artifact before it has been logged or in offline mode"
)
@property
def entity(self) -> str:
if self._logged_artifact:
return self._logged_artifact.entity
return self._api.settings("entity") or self._api.viewer().get("entity") # type: ignore
@property
def project(self) -> str:
if self._logged_artifact:
return self._logged_artifact.project
return self._api.settings("project") # type: ignore
@property
def manifest(self) -> ArtifactManifest:
if self._logged_artifact:
return self._logged_artifact.manifest
self.finalize()
return self._manifest
@property
def digest(self) -> str:
if self._logged_artifact:
return self._logged_artifact.digest
self.finalize()
# Digest will be none if the artifact hasn't been saved yet.
return self._digest
@property
def type(self) -> str:
if self._logged_artifact:
return self._logged_artifact.type
return self._type
@property
def name(self) -> str:
if self._logged_artifact:
return self._logged_artifact.name
return self._name
@property
def state(self) -> str:
if self._logged_artifact:
return self._logged_artifact.state
return "PENDING"
@property
def size(self) -> int:
if self._logged_artifact:
return self._logged_artifact.size
sizes: List[int]
sizes = []
for entry in self._manifest.entries:
e_size = self._manifest.entries[entry].size
if e_size is not None:
sizes.append(e_size)
return sum(sizes)
@property
def commit_hash(self) -> str:
if self._logged_artifact:
return self._logged_artifact.commit_hash
raise ValueError(
"Cannot access commit_hash on an artifact before it has been logged or in offline mode"
)
@property
def description(self) -> Optional[str]:
if self._logged_artifact:
return self._logged_artifact.description
return self._description
@description.setter
def description(self, desc: Optional[str]) -> None:
if self._logged_artifact:
self._logged_artifact.description = desc
return
self._description = desc
@property
def metadata(self) -> dict:
if self._logged_artifact:
return self._logged_artifact.metadata
return self._metadata
@metadata.setter
def metadata(self, metadata: dict) -> None:
metadata = _normalize_metadata(metadata)
if self._logged_artifact:
self._logged_artifact.metadata = metadata
return
self._metadata = metadata
@property
def aliases(self) -> List[str]:
if self._logged_artifact:
return self._logged_artifact.aliases
raise ValueError(
"Cannot call aliases on an artifact before it has been logged or in offline mode"
)
@aliases.setter
def aliases(self, aliases: List[str]) -> None:
"""
Arguments:
aliases: (list) The list of aliases associated with this artifact.
"""
if self._logged_artifact:
self._logged_artifact.aliases = aliases
return
raise ValueError(
"Cannot set aliases on an artifact before it has been logged or in offline mode"
)
@property
def use_as(self) -> Optional[str]:
return self._use_as
@property
def distributed_id(self) -> Optional[str]:
return self._distributed_id
@distributed_id.setter
def distributed_id(self, distributed_id: Optional[str]) -> None:
self._distributed_id = distributed_id
@property
def incremental(self) -> bool:
return self._incremental
def used_by(self) -> List["wandb.apis.public.Run"]:
if self._logged_artifact:
return self._logged_artifact.used_by()
raise ValueError(
"Cannot call used_by on an artifact before it has been logged or in offline mode"
)
def logged_by(self) -> "wandb.apis.public.Run":
if self._logged_artifact:
return self._logged_artifact.logged_by()
raise ValueError(
"Cannot call logged_by on an artifact before it has been logged or in offline mode"
)
@contextlib.contextmanager
def new_file(
self, name: str, mode: str = "w", encoding: Optional[str] = None
) -> Generator[IO, None, None]:
self._ensure_can_add()
path = os.path.join(self._artifact_dir.name, name.lstrip("/"))
if os.path.exists(path):
raise ValueError(f'File with name "{name}" already exists at "{path}"')
util.mkdir_exists_ok(os.path.dirname(path))
try:
with util.fsync_open(path, mode, encoding) as f:
yield f
except UnicodeEncodeError as e:
wandb.termerror(
f"Failed to open the provided file (UnicodeEncodeError: {e}). Please provide the proper encoding."
)
raise e
self.add_file(path, name=name)
def add_file(
self,
local_path: str,
name: Optional[str] = None,
is_tmp: Optional[bool] = False,
) -> ArtifactEntry:
self._ensure_can_add()
if not os.path.isfile(local_path):
raise ValueError("Path is not a file: %s" % local_path)
name = util.to_forward_slash_path(name or os.path.basename(local_path))
digest = md5_file_b64(local_path)
if is_tmp:
file_path, file_name = os.path.split(name)
file_name_parts = file_name.split(".")
file_name_parts[0] = b64_string_to_hex(digest)[:20]
name = os.path.join(file_path, ".".join(file_name_parts))
return self._add_local_file(name, local_path, digest=digest)
def add_dir(self, local_path: str, name: Optional[str] = None) -> None:
self._ensure_can_add()
if not os.path.isdir(local_path):
raise ValueError("Path is not a directory: %s" % local_path)
termlog(
"Adding directory to artifact (%s)... "
% os.path.join(".", os.path.normpath(local_path)),
newline=False,
)
start_time = time.time()
paths = []
for dirpath, _, filenames in os.walk(local_path, followlinks=True):
for fname in filenames:
physical_path = os.path.join(dirpath, fname)
logical_path = os.path.relpath(physical_path, start=local_path)
if name is not None:
logical_path = os.path.join(name, logical_path)
paths.append((logical_path, physical_path))
def add_manifest_file(log_phy_path: Tuple[str, str]) -> None:
logical_path, physical_path = log_phy_path
self._add_local_file(logical_path, physical_path)
import multiprocessing.dummy # this uses threads
num_threads = 8
pool = multiprocessing.dummy.Pool(num_threads)
pool.map(add_manifest_file, paths)
pool.close()
pool.join()
termlog("Done. %.1fs" % (time.time() - start_time), prefix=False)
def add_reference(
self,
uri: Union[ArtifactEntry, str],
name: Optional[str] = None,
checksum: bool = True,
max_objects: Optional[int] = None,
) -> Sequence[ArtifactEntry]:
self._ensure_can_add()
if name is not None:
name = util.to_forward_slash_path(name)
# This is a bit of a hack, we want to check if the uri is a of the type
# ArtifactEntry which is a private class returned by Artifact.get_path in
# wandb/apis/public.py. If so, then recover the reference URL.
uri_str: str
if isinstance(uri, ArtifactEntry) and uri.parent_artifact() != self:
ref_url_fn = uri.ref_url
uri_str = ref_url_fn()
elif isinstance(uri, str):
uri_str = uri
url = urlparse(str(uri_str))
if not url.scheme:
raise ValueError(
"References must be URIs. To reference a local file, use file://"
)
manifest_entries = self._storage_policy.store_reference(
self, uri_str, name=name, checksum=checksum, max_objects=max_objects
)
for entry in manifest_entries:
self._manifest.add_entry(entry)
return manifest_entries
def add(self, obj: data_types.WBValue, name: str) -> ArtifactEntry:
self._ensure_can_add()
name = util.to_forward_slash_path(name)
# This is a "hack" to automatically rename tables added to
# the wandb /media/tables directory to their sha-based name.
# TODO: figure out a more appropriate convention.
is_tmp_name = name.startswith("media/tables")
# Validate that the object is one of the correct wandb.Media types
# TODO: move this to checking subclass of wandb.Media once all are
# generally supported
allowed_types = [
data_types.Bokeh,
data_types.JoinedTable,
data_types.PartitionedTable,
data_types.Table,
data_types.Classes,
data_types.ImageMask,
data_types.BoundingBoxes2D,
data_types.Audio,
data_types.Image,
data_types.Video,
data_types.Html,
data_types.Object3D,
data_types.Molecule,
data_types._SavedModel,
]
if not any(isinstance(obj, t) for t in allowed_types):
raise ValueError(
"Found object of type {}, expected one of {}.".format(
obj.__class__, allowed_types
)
)
obj_id = id(obj)
if obj_id in self._added_objs:
return self._added_objs[obj_id].entry
# If the object is coming from another artifact, save it as a reference
ref_path = obj._get_artifact_entry_ref_url()
if ref_path is not None:
return self.add_reference(ref_path, type(obj).with_suffix(name))[0]
val = obj.to_json(self)
name = obj.with_suffix(name)
entry = self._manifest.get_entry_by_path(name)
if entry is not None:
return entry
def do_write(f: IO) -> None:
import json
# TODO: Do we need to open with utf-8 codec?
f.write(json.dumps(val, sort_keys=True))
if is_tmp_name:
file_path = os.path.join(ARTIFACT_TMP.name, str(id(self)), name)
folder_path, _ = os.path.split(file_path)
if not os.path.exists(folder_path):
os.makedirs(folder_path)
with open(file_path, "w") as tmp_f:
do_write(tmp_f)
else:
with self.new_file(name) as f:
file_path = f.name
do_write(f)
# Note, we add the file from our temp directory.
# It will be added again later on finalize, but succeed since
# the checksum should match
entry = self.add_file(file_path, name, is_tmp_name)
self._added_objs[obj_id] = _AddedObj(entry, obj)
if obj._artifact_target is None:
obj._set_artifact_target(self, entry.path)
if is_tmp_name:
if os.path.exists(file_path):
os.remove(file_path)
return entry
def get_path(self, name: str) -> ArtifactEntry:
if self._logged_artifact:
return self._logged_artifact.get_path(name)
raise ValueError(
"Cannot load paths from an artifact before it has been logged or in offline mode"
)
def get(self, name: str) -> data_types.WBValue:
if self._logged_artifact:
return self._logged_artifact.get(name)
raise ValueError(
"Cannot call get on an artifact before it has been logged or in offline mode"
)
def download(self, root: str = None, recursive: bool = False) -> str:
if self._logged_artifact:
return self._logged_artifact.download(root=root, recursive=recursive)
raise ValueError(
"Cannot call download on an artifact before it has been logged or in offline mode"
)
def checkout(self, root: Optional[str] = None) -> str:
if self._logged_artifact:
return self._logged_artifact.checkout(root=root)
raise ValueError(
"Cannot call checkout on an artifact before it has been logged or in offline mode"
)
def verify(self, root: Optional[str] = None) -> bool:
if self._logged_artifact:
return self._logged_artifact.verify(root=root)
raise ValueError(
"Cannot call verify on an artifact before it has been logged or in offline mode"
)
def save(
self,
project: Optional[str] = None,
settings: Optional["wandb.wandb_sdk.wandb_settings.Settings"] = None,
) -> None:
"""
Persists any changes made to the artifact. If currently in a run, that run will
log this artifact. If not currently in a run, a run of type "auto" will be created
to track this artifact.
Arguments:
project: (str, optional) A project to use for the artifact in the case that a run is not already in context
settings: (wandb.Settings, optional) A settings object to use when initializing an
automatic run. Most commonly used in testing harness.
Returns:
None
"""
if self._incremental:
with wandb_lib.telemetry.context() as tel:
tel.feature.artifact_incremental = True
if self._logged_artifact:
return self._logged_artifact.save()
else:
if wandb.run is None:
if settings is None:
settings = wandb.Settings(silent="true")
with wandb.init(
project=project, job_type="auto", settings=settings
) as run:
# redoing this here because in this branch we know we didn't
# have the run at the beginning of the method
if self._incremental:
with wandb_lib.telemetry.context(run=run) as tel:
tel.feature.artifact_incremental = True
run.log_artifact(self)
else:
wandb.run.log_artifact(self)
def delete(self) -> None:
if self._logged_artifact:
return self._logged_artifact.delete()
raise ValueError(
"Cannot call delete on an artifact before it has been logged or in offline mode"
)
def wait(self) -> ArtifactInterface:
if self._logged_artifact:
return self._logged_artifact.wait()
raise ValueError(
"Cannot call wait on an artifact before it has been logged or in offline mode"
)
def get_added_local_path_name(self, local_path: str) -> Optional[str]:
"""
Get the artifact relative name of a file added by a local filesystem path.
Arguments:
local_path: (str) The local path to resolve into an artifact relative name.
Returns:
str: The artifact relative name.
Examples:
Basic usage
```
artifact = wandb.Artifact('my_dataset', type='dataset')
artifact.add_file('path/to/file.txt', name='artifact/path/file.txt')
# Returns `artifact/path/file.txt`:
name = artifact.get_added_local_path_name('path/to/file.txt')
```
"""
entry = self._added_local_paths.get(local_path, None)
if entry is None:
return None
return entry.path
def finalize(self) -> None:
"""
Marks this artifact as final, which disallows further additions to the artifact.
This happens automatically when calling `log_artifact`.
Returns:
None
"""
if self._final:
return self._file_entries
# mark final after all files are added
self._final = True
self._digest = self._manifest.digest()
def json_encode(self) -> Dict[str, Any]:
if not self._logged_artifact:
raise ValueError(
"Cannot json encode artifact before it has been logged or in offline mode."
)
return util.artifact_to_json(self)
def _ensure_can_add(self) -> None:
if self._final:
raise ValueError("Can't add to finalized artifact.")
def _add_local_file(
self, name: str, path: str, digest: Optional[str] = None
) -> ArtifactEntry:
digest = digest or md5_file_b64(path)
size = os.path.getsize(path)
name = util.to_forward_slash_path(name)
cache_path, hit, cache_open = self._cache.check_md5_obj_path(digest, size)
if not hit:
with cache_open() as f:
shutil.copyfile(path, f.name)
entry = ArtifactManifestEntry(
name,
None,
digest=digest,
size=size,
local_path=cache_path,
)
self._manifest.add_entry(entry)
self._added_local_paths[path] = entry
return entry
def __setitem__(self, name: str, item: data_types.WBValue) -> ArtifactEntry:
return self.add(item, name)
def __getitem__(self, name: str) -> Optional[data_types.WBValue]:
return self.get(name)
class ArtifactManifestV1(ArtifactManifest):
@classmethod
def version(cls) -> int:
return 1
@classmethod
def from_manifest_json(
cls, artifact: ArtifactInterface, manifest_json: Dict
) -> "ArtifactManifestV1":
if manifest_json["version"] != cls.version():
raise ValueError(
"Expected manifest version 1, got %s" % manifest_json["version"]
)
storage_policy_name = manifest_json["storagePolicy"]
storage_policy_config = manifest_json.get("storagePolicyConfig", {})
storage_policy_cls = StoragePolicy.lookup_by_name(storage_policy_name)
if storage_policy_cls is None:
raise ValueError('Failed to find storage policy "%s"' % storage_policy_name)
entries: Mapping[str, ArtifactManifestEntry]
entries = {
name: ArtifactManifestEntry(
path=name,
digest=val["digest"],
birth_artifact_id=val.get("birthArtifactID"),
ref=val.get("ref"),
size=val.get("size"),
extra=val.get("extra"),
local_path=val.get("local_path"),
)
for name, val in manifest_json["contents"].items()
}
return cls(
artifact, storage_policy_cls.from_config(storage_policy_config), entries
)
def __init__(
self,
artifact: ArtifactInterface,
storage_policy: "WandbStoragePolicy",
entries: Optional[Mapping[str, ArtifactEntry]] = None,
) -> None:
super().__init__(artifact, storage_policy, entries=entries)
def to_manifest_json(self) -> Dict:
"""This is the JSON that's stored in wandb_manifest.json
If include_local is True we also include the local paths to files. This is
used to represent an artifact that's waiting to be saved on the current
system. We don't need to include the local paths in the artifact manifest
contents.
"""
contents = {}
for entry in sorted(self.entries.values(), key=lambda k: k.path):
json_entry: Dict[str, Any] = {
"digest": entry.digest,
}
if entry.birth_artifact_id:
json_entry["birthArtifactID"] = entry.birth_artifact_id
if entry.ref:
json_entry["ref"] = entry.ref
if entry.extra:
json_entry["extra"] = entry.extra
if entry.size is not None:
json_entry["size"] = entry.size
contents[entry.path] = json_entry
return {
"version": self.__class__.version(),
"storagePolicy": self.storage_policy.name(),
"storagePolicyConfig": self.storage_policy.config() or {},
"contents": contents,
}
def digest(self) -> str:
hasher = hashlib.md5()
hasher.update(b"wandb-artifact-manifest-v1\n")
for (name, entry) in sorted(self.entries.items(), key=lambda kv: kv[0]):
hasher.update(f"{name}:{entry.digest}\n".encode())
return hasher.hexdigest()
class ArtifactManifestEntry(ArtifactEntry):
def __init__(
self,
path: str,
ref: Optional[str],
digest: str,
birth_artifact_id: Optional[str] = None,
size: Optional[int] = None,
extra: Dict = None,
local_path: Optional[str] = None,
):
if local_path is not None and size is None:
raise AssertionError(
"programming error, size required when local_path specified"
)
self.path = util.to_forward_slash_path(path)
self.ref = ref # This is None for files stored in the artifact.
self.digest = digest
self.birth_artifact_id = birth_artifact_id
self.size = size
self.extra = extra or {}
# This is not stored in the manifest json, it's only used in the process
# of saving
self.local_path = local_path
def ref_target(self) -> str:
if self.ref is None:
raise ValueError("Only reference entries support ref_target().")
return self.ref
def __repr__(self) -> str:
if self.ref is not None:
summary = f"ref: {self.ref}/{self.path}"
else:
summary = "digest: %s" % self.digest
return "<ManifestEntry %s>" % summary
class WandbStoragePolicy(StoragePolicy):
@classmethod
def name(cls) -> str:
return "wandb-storage-policy-v1"
@classmethod
def from_config(cls, config: Dict) -> "WandbStoragePolicy":
return cls(config=config)
def __init__(self, config: Dict = None) -> None:
self._cache = get_artifacts_cache()
self._config = config or {}
self._session = requests.Session()
adapter = requests.adapters.HTTPAdapter(
max_retries=_REQUEST_RETRY_STRATEGY,
pool_connections=_REQUEST_POOL_CONNECTIONS,
pool_maxsize=_REQUEST_POOL_MAXSIZE,
)
self._session.mount("http://", adapter)
self._session.mount("https://", adapter)
s3 = S3Handler()
gcs = GCSHandler()
http = HTTPHandler(self._session)
https = HTTPHandler(self._session, scheme="https")
artifact = WBArtifactHandler()
local_artifact = WBLocalArtifactHandler()
file_handler = LocalFileHandler()
self._api = InternalApi()
self._handler = MultiHandler(
handlers=[
s3,
gcs,
http,
https,
artifact,
local_artifact,
file_handler,
],
default_handler=TrackingHandler(),
)
def config(self) -> Dict:
return self._config
def load_file(
self, artifact: ArtifactInterface, name: str, manifest_entry: ArtifactEntry
) -> str:
path, hit, cache_open = self._cache.check_md5_obj_path(
manifest_entry.digest,
manifest_entry.size if manifest_entry.size is not None else 0,
)
if hit:
return path
response = self._session.get(
self._file_url(self._api, artifact.entity, manifest_entry),
auth=("api", self._api.api_key),
stream=True,
)
response.raise_for_status()
with cache_open(mode="wb") as file:
for data in response.iter_content(chunk_size=16 * 1024):
file.write(data)
return path
def store_reference(
self,
artifact: ArtifactInterface,
path: str,
name: Optional[str] = None,
checksum: bool = True,
max_objects: Optional[int] = None,
) -> Sequence[ArtifactEntry]:
return self._handler.store_path(
artifact, path, name=name, checksum=checksum, max_objects=max_objects
)
def load_reference(
self,
artifact: ArtifactInterface,
name: str,
manifest_entry: ArtifactEntry,
local: bool = False,
) -> str:
return self._handler.load_path(artifact, manifest_entry, local)
def _file_url(
self, api: InternalApi, entity_name: str, manifest_entry: ArtifactEntry
) -> str:
storage_layout = self._config.get("storageLayout", StorageLayout.V1)
storage_region = self._config.get("storageRegion", "default")
md5_hex = util.bytes_to_hex(base64.b64decode(manifest_entry.digest))
if storage_layout == StorageLayout.V1:
return "{}/artifacts/{}/{}".format(
api.settings("base_url"), entity_name, md5_hex
)
elif storage_layout == StorageLayout.V2:
return "{}/artifactsV2/{}/{}/{}/{}".format(
api.settings("base_url"),
storage_region,
entity_name,
quote(
manifest_entry.birth_artifact_id
if manifest_entry.birth_artifact_id is not None
else ""
),
md5_hex,
)
else:
raise Exception(f"unrecognized storage layout: {storage_layout}")
def store_file(
self,
artifact_id: str,
artifact_manifest_id: str,
entry: ArtifactEntry,
preparer: "StepPrepare",
progress_callback: Optional["progress.ProgressFn"] = None,
) -> bool:
# write-through cache
cache_path, hit, cache_open = self._cache.check_md5_obj_path(
entry.digest, entry.size if entry.size is not None else 0
)
if not hit and entry.local_path is not None:
with cache_open() as f:
shutil.copyfile(entry.local_path, f.name)
entry.local_path = cache_path
resp = preparer.prepare(
lambda: {
"artifactID": artifact_id,
"artifactManifestID": artifact_manifest_id,
"name": entry.path,
"md5": entry.digest,