/
serializers.py
1358 lines (1100 loc) · 48.5 KB
/
serializers.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
# -*- coding: utf-8 -*-
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# pylint: disable=line-too-long, bad-continuation,protected-access
"""Defines the Serializer classes."""
import dataclasses
import functools
import json
import os
import pathlib
import pickle
import shutil
import tempfile
from typing import Any, Dict, Optional, Union
import uuid
from google.cloud.aiplatform.utils import gcs_utils
from vertexai.preview._workflow.shared import constants
from vertexai.preview._workflow.shared import (
data_serializer_utils,
supported_frameworks,
)
from vertexai.preview._workflow.serialization_engine import (
serializers_base,
)
from packaging import version
try:
import cloudpickle
except ImportError:
cloudpickle = None
SERIALIZATION_METADATA_FRAMEWORK_KEY = "framework"
# TODO(b/272263750): use the centralized module and usage pattern to guard these
# imports
# pylint: disable=g-import-not-at-top
try:
import pandas as pd
import bigframes as bf
PandasData = pd.DataFrame
BigframesData = bf.dataframe.DataFrame
except ImportError:
pd = None
bf = None
PandasData = Any
BigframesData = Any
try:
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
PandasData = pd.DataFrame
except ImportError:
pd = None
pa = None
pq = None
PandasData = Any
try:
import sklearn
SklearnEstimator = sklearn.base.BaseEstimator
except ImportError:
sklearn = None
SklearnEstimator = Any
try:
from tensorflow import keras
import tensorflow as tf
KerasModel = keras.models.Model
TFDataset = tf.data.Dataset
except ImportError:
keras = None
tf = None
KerasModel = Any
TFDataset = Any
try:
import torch
TorchModel = torch.nn.Module
TorchDataLoader = torch.utils.data.DataLoader
TorchTensor = torch.tensor
except ImportError:
torch = None
TorchModel = Any
TorchDataLoader = Any
TorchTensor = Any
try:
import lightning.pytorch as pl
LightningTrainer = pl.Trainer
except ImportError:
pl = None
LightningTrainer = Any
Types = Union[
PandasData,
BigframesData,
SklearnEstimator,
KerasModel,
TorchModel,
LightningTrainer,
]
_LIGHTNING_ROOT_DIR = "/vertex_lightning_root_dir/"
SERIALIZATION_METADATA_FILENAME = "serialization_metadata"
# Map tf major.minor version to tfio version from https://pypi.org/project/tensorflow-io/
_TFIO_VERSION_DICT = {
"2.3": "0.16.0", # Align with testing_extra_require: tensorflow >= 2.3.0
"2.4": "0.17.1",
"2.5": "0.19.1",
"2.6": "0.21.0",
"2.7": "0.23.1",
"2.8": "0.25.0",
"2.9": "0.26.0",
"2.10": "0.27.0",
"2.11": "0.31.0",
"2.12": "0.32.0",
"2.13": "0.34.0", # TODO(b/295580335): Support TF 2.13
}
def get_uri_prefix(gcs_uri: str) -> str:
"""Gets the directory of the gcs_uri.
Example:
1) file uri:
_get_uri_prefix("gs://<bucket>/directory/file.extension") == "gs://
<bucket>/directory/"
2) folder uri:
_get_uri_prefix("gs://<bucket>/parent_dir/dir") == "gs://<bucket>/
parent_dir/"
Args:
gcs_uri: A string starting with "gs://" that represent a gcs uri.
Returns:
The parent gcs directory in string format.
"""
# For tensorflow, the uri may be "gs://my-bucket/saved_model/"
if gcs_uri.endswith("/"):
gcs_uri = gcs_uri[:-1]
gcs_pathlibpath = pathlib.Path(gcs_uri)
file_name = gcs_pathlibpath.name
return gcs_uri[: -len(file_name)]
def get_metadata_path_from_file_gcs_uri(gcs_uri: str) -> str:
gcs_pathlibpath = pathlib.Path(gcs_uri)
prefix = get_uri_prefix(gcs_uri=gcs_uri)
return os.path.join(
prefix,
f"{SERIALIZATION_METADATA_FILENAME}_{gcs_pathlibpath.stem}.json",
)
def _get_metadata(gcs_uri: str) -> Dict[str, Any]:
metadata_file = get_metadata_path_from_file_gcs_uri(gcs_uri)
if metadata_file.startswith("gs://"):
with tempfile.NamedTemporaryFile() as temp_file:
gcs_utils.download_file_from_gcs(metadata_file, temp_file.name)
with open(temp_file.name, mode="rb") as f:
metadata = json.load(f)
else:
with open(metadata_file, "rb") as f:
metadata = json.load(f)
return metadata
def _is_valid_gcs_path(path: str) -> bool:
"""checks if a path is a valid gcs path.
Args:
path (str):
Required. A file path.
Returns:
A boolean that indicates whether the path is a valid gcs path.
"""
return path.startswith(("gs://", "/gcs/", "gcs/"))
def _load_torch_model(path: str, map_location: "torch.device") -> TorchModel:
try:
return torch.load(path, map_location=map_location)
except Exception:
return torch.load(path, map_location=torch.device("cpu"))
class KerasModelSerializationMetadata(serializers_base.SerializationMetadata):
save_format: str = "keras"
def to_dict(self):
dct = super().to_dict()
dct.update({"save_format": self.save_format})
return dct
def _get_temp_file_or_dir(is_file: bool = True, file_suffix: Optional[str] = None):
return (
tempfile.NamedTemporaryFile(suffix=file_suffix)
if is_file
else tempfile.TemporaryDirectory()
)
class KerasModelSerializer(serializers_base.Serializer):
"""A serializer for tensorflow.keras.models.Model objects."""
_metadata: KerasModelSerializationMetadata = KerasModelSerializationMetadata(
serializer="KerasModelSerializer"
)
def serialize(
self, to_serialize: KerasModel, gcs_path: str, **kwargs
) -> str: # pytype: disable=invalid-annotation
"""Serializes a tensorflow.keras.models.Model to a gcs path.
Args:
to_serialize (keras.models.Model):
Required. A Keras Model object.
gcs_path (str):
Required. A GCS uri that the model will be saved to.
Returns:
The GCS uri.
Raises:
ValueError: if `gcs_path` is not a valid GCS uri.
"""
save_format = kwargs.get("save_format", "keras")
if not _is_valid_gcs_path(gcs_path):
raise ValueError(f"Invalid gcs path: {gcs_path}")
KerasModelSerializer._metadata.dependencies = (
supported_frameworks._get_deps_if_tensorflow_model(to_serialize)
)
KerasModelSerializer._metadata.save_format = save_format
if not gcs_path.endswith(".keras") and save_format == "keras":
gcs_path = gcs_path + ".keras"
if not gcs_path.endswith(".h5") and save_format == "h5":
gcs_path = gcs_path + ".h5"
is_file = save_format != "tf"
if gcs_path.startswith("gs://"):
# For tf (saved_model) format, the serialized data is a directory,
# while for keras and h5 formats, the serialized data is a file.
with _get_temp_file_or_dir(
is_file=is_file, file_suffix=f".{save_format}"
) as temp_file_or_dir:
to_serialize.save(
temp_file_or_dir.name if is_file else temp_file_or_dir,
save_format=save_format,
)
gcs_utils.upload_to_gcs(
temp_file_or_dir.name if is_file else temp_file_or_dir, gcs_path
)
else:
to_serialize.save(gcs_path, save_format=save_format)
return gcs_path
def deserialize(self, serialized_gcs_path: str, **kwargs) -> KerasModel:
"""Deserialize a tensorflow.keras.models.Model given the gcs file name.
Args:
serialized_gcs_path (str):
Required. A GCS path to the serialized file.
Returns:
A Keras Model.
Raises:
ValueError: if `serialized_gcs_path` is not a valid GCS uri.
ImportError: if tensorflow is not installed.
"""
del kwargs
if not _is_valid_gcs_path(serialized_gcs_path):
raise ValueError(f"Invalid gcs path: {serialized_gcs_path}")
metadata = _get_metadata(serialized_gcs_path)
# For backward compatibility, if the metadata doesn't contain
# save_format, we assume the model was saved as saved_model format.
save_format = metadata.get("save_format", "tf")
try:
from tensorflow import keras
if save_format == "keras" and not serialized_gcs_path.endswith(".keras"):
serialized_gcs_path = serialized_gcs_path + ".keras"
if save_format == "h5" and not serialized_gcs_path.endswith(".h5"):
serialized_gcs_path = serialized_gcs_path + ".h5"
# For tf (saved_model) format, the serialized data is a directory,
# while for keras and h5 formats, the serialized data is a file.
is_file = save_format != "tf"
if serialized_gcs_path.startswith("gs://"):
with _get_temp_file_or_dir(
is_file=is_file, file_suffix=f".{save_format}"
) as temp_file_or_dir:
if is_file:
gcs_utils.download_file_from_gcs(
serialized_gcs_path, temp_file_or_dir.name
)
return keras.models.load_model(temp_file_or_dir.name)
else:
gcs_utils.download_from_gcs(
serialized_gcs_path, temp_file_or_dir
)
return keras.models.load_model(temp_file_or_dir)
else:
return keras.models.load_model(serialized_gcs_path)
except ImportError as e:
raise ImportError("tensorflow is not installed.") from e
class KerasHistoryCallbackSerializer(serializers_base.Serializer):
"""A serializer for tensorflow.keras.callbacks.History objects."""
_metadata: serializers_base.SerializationMetadata = (
serializers_base.SerializationMetadata(
serializer="KerasHistoryCallbackSerializer"
)
)
def serialize(self, to_serialize, gcs_path: str, **kwargs):
"""Serializes a keras History callback to a gcs path.
Args:
to_serialize (keras.callbacks.History):
Required. A History object.
gcs_path (str):
Required. A GCS uri that History object will be saved to.
Returns:
The GCS uri.
Raises:
ValueError: if `gcs_path` is not a valid GCS uri.
"""
del kwargs
if not _is_valid_gcs_path(gcs_path):
raise ValueError(f"Invalid gcs path: {gcs_path}")
KerasHistoryCallbackSerializer._metadata.dependencies = ["cloudpickle"]
to_serialize_dict = to_serialize.__dict__
del to_serialize_dict["model"]
with open(gcs_path, "wb") as f:
cloudpickle.dump(to_serialize_dict, f)
return gcs_path
def deserialize(self, serialized_gcs_path: str, **kwargs):
"""Deserialize a keras.callbacks.History given the gcs file name.
Args:
serialized_gcs_path (str):
Required. A GCS path to the serialized file.
Returns:
A keras.callbacks.History object.
Raises:
ValueError: if `serialized_gcs_path` is not a valid GCS uri.
"""
if not _is_valid_gcs_path(serialized_gcs_path):
raise ValueError(f"Invalid gcs path: {serialized_gcs_path}")
model = kwargs.get("model", None)
# Only "model" is needed.
del kwargs
history_dict = {}
if serialized_gcs_path.startswith("gs://"):
with tempfile.NamedTemporaryFile() as temp_file:
gcs_utils.download_file_from_gcs(serialized_gcs_path, temp_file.name)
with open(temp_file.name, mode="rb") as f:
history_dict = cloudpickle.load(f)
else:
with open(serialized_gcs_path, mode="rb") as f:
history_dict = cloudpickle.load(f)
history_obj = keras.callbacks.History()
for attr_name, attr_value in history_dict.items():
setattr(history_obj, attr_name, attr_value)
if model:
history_obj.set_model(model)
return history_obj
class SklearnEstimatorSerializer(serializers_base.Serializer):
"""A serializer that uses pickle to save/load sklearn estimators."""
_metadata: serializers_base.SerializationMetadata = (
serializers_base.SerializationMetadata(serializer="SklearnEstimatorSerializer")
)
def serialize(self, to_serialize: SklearnEstimator, gcs_path: str, **kwargs) -> str:
"""Serializes a sklearn estimator to a gcs path.
Args:
to_serialize (sklearn.base.BaseEstimator):
Required. A sklearn estimator.
gcs_path (str):
Required. A GCS uri that the estimator will be saved to.
Returns:
The GCS uri.
Raises:
ValueError: if `gcs_path` is not a valid GCS uri.
"""
del kwargs
if not _is_valid_gcs_path(gcs_path):
raise ValueError(f"Invalid gcs path: {gcs_path}")
SklearnEstimatorSerializer._metadata.dependencies = (
supported_frameworks._get_deps_if_sklearn_model(to_serialize)
)
serialized = pickle.dumps(to_serialize, protocol=constants.PICKLE_PROTOCOL)
serializers_base.write_and_upload_data(data=serialized, gcs_filename=gcs_path)
return gcs_path
def deserialize(self, serialized_gcs_path: str, **kwargs) -> SklearnEstimator:
"""Deserialize a sklearn estimator given the gcs file name.
Args:
serialized_gcs_path (str):
Required. A GCS path to the serialized file.
Returns:
A sklearn estimator.
Raises:
ValueError: if `serialized_gcs_path` is not a valid GCS uri.
"""
del kwargs
if not _is_valid_gcs_path(serialized_gcs_path):
raise ValueError(f"Invalid gcs path: {serialized_gcs_path}")
if serialized_gcs_path.startswith("gs://"):
with tempfile.NamedTemporaryFile() as temp_file:
gcs_utils.download_file_from_gcs(serialized_gcs_path, temp_file.name)
with open(temp_file.name, mode="rb") as f:
obj = pickle.load(f)
else:
with open(serialized_gcs_path, mode="rb") as f:
obj = pickle.load(f)
return obj
class TorchModelSerializer(serializers_base.Serializer):
"""A serializer for torch.nn.Module objects."""
_metadata: serializers_base.SerializationMetadata = (
serializers_base.SerializationMetadata(serializer="TorchModelSerializer")
)
def serialize(self, to_serialize: TorchModel, gcs_path: str, **kwargs) -> str:
"""Serializes a torch.nn.Module to a gcs path.
Args:
to_serialize (torch.nn.Module):
Required. A PyTorch model object.
gcs_path (str):
Required. A GCS uri that the model will be saved to.
Returns:
The GCS uri.
Raises:
ValueError: if `gcs_path` is not a valid GCS uri.
"""
del kwargs
if not _is_valid_gcs_path(gcs_path):
raise ValueError(f"Invalid gcs path: {gcs_path}")
TorchModelSerializer._metadata.dependencies = (
supported_frameworks._get_deps_if_torch_model(to_serialize)
)
if gcs_path.startswith("gs://"):
with tempfile.NamedTemporaryFile() as temp_file:
torch.save(
to_serialize,
temp_file.name,
pickle_module=cloudpickle,
pickle_protocol=constants.PICKLE_PROTOCOL,
)
gcs_utils.upload_to_gcs(temp_file.name, gcs_path)
else:
torch.save(
to_serialize,
gcs_path,
pickle_module=cloudpickle,
pickle_protocol=constants.PICKLE_PROTOCOL,
)
return gcs_path
def deserialize(self, serialized_gcs_path: str, **kwargs) -> TorchModel:
"""Deserialize a torch.nn.Module given the gcs file name.
Args:
serialized_gcs_path (str):
Required. A GCS path to the serialized file.
Returns:
A torch.nn.Module model.
Raises:
ValueError: if `serialized_gcs_path` is not a valid GCS uri.
ImportError: if torch is not installed.
"""
del kwargs
if not _is_valid_gcs_path(serialized_gcs_path):
raise ValueError(f"Invalid gcs path: {serialized_gcs_path}")
try:
import torch
except ImportError as e:
raise ImportError("torch is not installed.") from e
map_location = (
torch._GLOBAL_DEVICE_CONTEXT.device
if torch._GLOBAL_DEVICE_CONTEXT
else None
)
if serialized_gcs_path.startswith("gs://"):
with tempfile.NamedTemporaryFile() as temp_file:
gcs_utils.download_file_from_gcs(serialized_gcs_path, temp_file.name)
model = _load_torch_model(temp_file.name, map_location=map_location)
else:
model = _load_torch_model(serialized_gcs_path, map_location=map_location)
return model
# TODO(b/289386023) Add unit tests for LightningTrainerSerialzier
class LightningTrainerSerializer(serializers_base.Serializer):
"""A serializer for lightning.pytorch.Trainer objects."""
_metadata: serializers_base.SerializationMetadata = (
serializers_base.SerializationMetadata(serializer="LightningTrainerSerializer")
)
def _serialize_to_local(self, to_serialize: LightningTrainer, path: str):
"""Serializes a lightning.pytorch.Trainer to a local path.
Args:
to_serialize (lightning.pytorch.Trainer):
Required. A lightning trainer object.
path (str):
Required. A local_path that the trainer will be saved to.
"""
# In remote environment, we store local accelerator connector and default root
# dir as attributes when we deserialize the trainer. And we need to serialize
# them in order to retrieve in local environment.
if getattr(to_serialize, "_vertex_local_accelerator_connector", None):
with open(f"{path}/local_accelerator_connector", "wb") as f:
cloudpickle.dump(
to_serialize._vertex_local_accelerator_connector,
f,
protocol=constants.PICKLE_PROTOCOL,
)
delattr(to_serialize, "_vertex_local_accelerator_connector")
else:
with open(f"{path}/local_accelerator_connector", "wb") as f:
cloudpickle.dump(
to_serialize._accelerator_connector,
f,
protocol=constants.PICKLE_PROTOCOL,
)
if getattr(to_serialize, "_vertex_local_default_root_dir", None):
with open(f"{path}/local_default_root_dir", "wb") as f:
cloudpickle.dump(
to_serialize._vertex_local_default_root_dir,
f,
protocol=constants.PICKLE_PROTOCOL,
)
delattr(to_serialize, "_vertex_local_default_root_dir")
else:
with open(f"{path}/local_default_root_dir", "wb") as f:
cloudpickle.dump(
to_serialize._default_root_dir,
f,
protocol=constants.PICKLE_PROTOCOL,
)
with open(f"{path}/trainer", "wb") as f:
cloudpickle.dump(to_serialize, f, protocol=constants.PICKLE_PROTOCOL)
if os.path.exists(to_serialize.logger.root_dir):
shutil.copytree(
to_serialize.logger.root_dir,
f"{path}/{to_serialize.logger.name}",
dirs_exist_ok=True,
)
def serialize(self, to_serialize: LightningTrainer, gcs_path: str, **kwargs) -> str:
"""Serializes a lightning.pytorch.Trainer to a gcs path.
Args:
to_serialize (lightning.pytorch.Trainer):
Required. A lightning trainer object.
gcs_path (str):
Required. A GCS uri that the trainer will be saved to.
Returns:
The GCS uri.
Raises:
ValueError: if `gcs_path` is not a valid GCS uri.
"""
del kwargs
if not _is_valid_gcs_path(gcs_path):
raise ValueError(f"Invalid gcs path: {gcs_path}")
LightningTrainerSerializer._metadata.dependencies = (
supported_frameworks._get_deps_if_lightning_model(to_serialize)
+ supported_frameworks._get_cloudpickle_deps()
)
if gcs_path.startswith("gs://"):
with tempfile.TemporaryDirectory() as temp_dir:
self._serialize_to_local(to_serialize, temp_dir)
gcs_utils.upload_to_gcs(temp_dir, gcs_path)
else:
os.makedirs(gcs_path)
self._serialize_to_local(to_serialize, gcs_path)
return gcs_path
def _deserialize_from_local(self, path: str) -> LightningTrainer:
"""Deserialize a lightning.pytorch.Trainer given a local path.
Args:
path (str):
Required. A local path to the serialized trainer.
Returns:
A lightning.pytorch.Trainer object.
"""
with open(f"{path}/trainer", "rb") as f:
trainer = cloudpickle.load(f)
if os.getenv("_IS_VERTEX_REMOTE_TRAINING") == "True":
# Store the logs in the cwd of remote environment.
trainer._default_root_dir = _LIGHTNING_ROOT_DIR
for logger in trainer.loggers:
# for TensorBoardLogger
if getattr(logger, "_root_dir", None):
logger._root_dir = trainer.default_root_dir
# for CSVLogger
if getattr(logger, "_save_dir", None):
logger._save_dir = trainer.default_root_dir
# Store local accelerator connector and root dir as attributes, so that
# we can retrieve them in local environment.
with open(f"{path}/local_accelerator_connector", "rb") as f:
trainer._vertex_local_accelerator_connector = cloudpickle.load(f)
with open(f"{path}/local_default_root_dir", "rb") as f:
trainer._vertex_local_default_root_dir = cloudpickle.load(f)
else:
with open(f"{path}/local_accelerator_connector", "rb") as f:
trainer._accelerator_connector = cloudpickle.load(f)
with open(f"{path}/local_default_root_dir", "rb") as f:
trainer._default_root_dir = cloudpickle.load(f)
for logger in trainer.loggers:
if getattr(logger, "_root_dir", None):
logger._root_dir = trainer.default_root_dir
if getattr(logger, "_save_dir", None):
logger._save_dir = trainer.default_root_dir
for callback in trainer.checkpoint_callbacks:
callback.dirpath = os.path.join(
trainer.default_root_dir,
callback.dirpath.replace(_LIGHTNING_ROOT_DIR, ""),
)
if callback.best_model_path:
callback.best_model_path = os.path.join(
trainer.default_root_dir,
callback.best_model_path.replace(_LIGHTNING_ROOT_DIR, ""),
)
if callback.kth_best_model_path:
callback.kth_best_model_path = os.path.join(
trainer.default_root_dir,
callback.kth_best_model_path.replace(_LIGHTNING_ROOT_DIR, ""),
)
if callback.last_model_path:
callback.last_model_path = os.path.join(
trainer.default_root_dir,
callback.last_model_path.replace(_LIGHTNING_ROOT_DIR, ""),
)
if os.path.exists(f"{path}/{trainer.logger.name}"):
shutil.copytree(
f"{path}/{trainer.logger.name}",
trainer.logger.root_dir,
dirs_exist_ok=True,
)
return trainer
def deserialize(self, serialized_gcs_path: str, **kwargs) -> LightningTrainer:
"""Deserialize a lightning.pytorch.Trainer given the gcs path.
Args:
serialized_gcs_path (str):
Required. A GCS path to the serialized file.
Returns:
A lightning.pytorch.Trainer object.
Raises:
ValueError: if `serialized_gcs_path` is not a valid GCS uri.
"""
del kwargs
if not _is_valid_gcs_path(serialized_gcs_path):
raise ValueError(f"Invalid gcs path: {serialized_gcs_path}")
if serialized_gcs_path.startswith("gs://"):
with tempfile.TemporaryDirectory() as temp_dir:
gcs_utils.download_from_gcs(serialized_gcs_path, temp_dir)
trainer = self._deserialize_from_local(temp_dir)
else:
trainer = self._deserialize_from_local(serialized_gcs_path)
return trainer
class TorchDataLoaderSerializer(serializers_base.Serializer):
"""A serializer for torch.utils.data.DataLoader objects."""
_metadata: serializers_base.SerializationMetadata = (
serializers_base.SerializationMetadata(serializer="TorchDataLoaderSerializer")
)
def _serialize_to_local(self, to_serialize: TorchDataLoader, path: str):
"""Serializes a torch.utils.data.DataLoader to a local path.
Args:
to_serialize (torch.utils.data.DataLoader):
Required. A pytorch dataloader object.
path (str):
Required. A local_path that the dataloader will be saved to.
"""
# save objects by cloudpickle
with open(f"{path}/dataset.cpkl", "wb") as f:
cloudpickle.dump(
to_serialize.dataset, f, protocol=constants.PICKLE_PROTOCOL
)
with open(f"{path}/collate_fn.cpkl", "wb") as f:
cloudpickle.dump(
to_serialize.collate_fn, f, protocol=constants.PICKLE_PROTOCOL
)
with open(f"{path}/worker_init_fn.cpkl", "wb") as f:
cloudpickle.dump(
to_serialize.worker_init_fn, f, protocol=constants.PICKLE_PROTOCOL
)
# save (str, int, float, bool) values into a json file
pass_through_args = {
"num_workers": to_serialize.num_workers,
"pin_memory": to_serialize.pin_memory,
"timeout": to_serialize.timeout,
"prefetch_factor": to_serialize.prefetch_factor,
"persistent_workers": to_serialize.persistent_workers,
"pin_memory_device": to_serialize.pin_memory_device,
}
# dataloader.generator is a torch.Generator object that defined in c++
# it cannot be serialized by cloudpickle, so we store its device information
# and re-instaintiate a new Generator object with this device when deserializing
pass_through_args["generator_device"] = (
to_serialize.generator.device.type if to_serialize.generator else None
)
# batch_sampler option is mutually exclusive with batch_size, shuffle,
# sampler, and drop_last.
# for default batch sampler we store batch_size, drop_last, and sampler object
# but not batch sampler object.
if isinstance(to_serialize.batch_sampler, torch.utils.data.BatchSampler):
pass_through_args["batch_size"] = to_serialize.batch_size
pass_through_args["drop_last"] = to_serialize.drop_last
with open(f"{path}/sampler.cpkl", "wb") as f:
cloudpickle.dump(
to_serialize.sampler, f, protocol=constants.PICKLE_PROTOCOL
)
# otherwise we only serialize batch sampler and skip batch_size, drop_last,
# and sampler object.
else:
with open(f"{path}/batch_sampler.cpkl", "wb") as f:
cloudpickle.dump(
to_serialize.batch_sampler, f, protocol=constants.PICKLE_PROTOCOL
)
with open(f"{path}/pass_through_args.json", "w") as f:
json.dump(pass_through_args, f)
def serialize(self, to_serialize: TorchDataLoader, gcs_path: str, **kwargs) -> str:
"""Serializes a torch.utils.data.DataLoader to a gcs path.
Args:
to_serialize (torch.utils.data.DataLoader):
Required. A pytorch dataloader object.
gcs_path (str):
Required. A GCS uri that the dataloader will be saved to.
Returns:
The GCS uri.
Raises:
ValueError: if `gcs_path` is not a valid GCS uri.
"""
del kwargs
if not _is_valid_gcs_path(gcs_path):
raise ValueError(f"Invalid gcs path: {gcs_path}")
TorchDataLoaderSerializer._metadata.dependencies = (
supported_frameworks._get_deps_if_torch_dataloader(to_serialize)
)
if gcs_path.startswith("gs://"):
with tempfile.TemporaryDirectory() as temp_dir:
self._serialize_to_local(to_serialize, temp_dir)
gcs_utils.upload_to_gcs(temp_dir, gcs_path)
else:
os.makedirs(gcs_path)
self._serialize_to_local(to_serialize, gcs_path)
return gcs_path
def _deserialize_from_local(self, path: str) -> TorchDataLoader:
"""Deserialize a torch.utils.data.DataLoader given a local path.
Args:
path (str):
Required. A local path to the serialized dataloader.
Returns:
A torch.utils.data.DataLoader object.
Raises:
ImportError: if torch is not installed.
"""
try:
import torch
except ImportError as e:
raise ImportError(
f"torch is not installed and required to deserialize the file from {path}."
) from e
with open(f"{path}/pass_through_args.json", "r") as f:
kwargs = json.load(f)
# re-instantiate Generator
if kwargs["generator_device"] is not None:
kwargs["generator"] = torch.Generator(
kwargs["generator_device"] if torch.cuda.is_available() else "cpu"
)
kwargs.pop("generator_device")
with open(f"{path}/dataset.cpkl", "rb") as f:
kwargs["dataset"] = cloudpickle.load(f)
with open(f"{path}/collate_fn.cpkl", "rb") as f:
kwargs["collate_fn"] = cloudpickle.load(f)
with open(f"{path}/worker_init_fn.cpkl", "rb") as f:
kwargs["worker_init_fn"] = cloudpickle.load(f)
try:
with open(f"{path}/sampler.cpkl", "rb") as f:
kwargs["sampler"] = cloudpickle.load(f)
except FileNotFoundError:
pass
try:
with open(f"{path}/batch_sampler.cpkl", "rb") as f:
kwargs["batch_sampler"] = cloudpickle.load(f)
except FileNotFoundError:
pass
return torch.utils.data.DataLoader(**kwargs)
def deserialize(self, serialized_gcs_path: str, **kwargs) -> TorchDataLoader:
"""Deserialize a torch.utils.data.DataLoader given the gcs path.
Args:
serialized_gcs_path (str):
Required. A GCS path to the serialized file.
Returns:
A torch.utils.data.DataLoader object.
Raises:
ValueError: if `serialized_gcs_path` is not a valid GCS uri.
ImportError: if torch is not installed.
"""
del kwargs
if not _is_valid_gcs_path(serialized_gcs_path):
raise ValueError(f"Invalid gcs path: {serialized_gcs_path}")
if serialized_gcs_path.startswith("gs://"):
with tempfile.TemporaryDirectory() as temp_dir:
gcs_utils.download_from_gcs(serialized_gcs_path, temp_dir)
dataloader = self._deserialize_from_local(temp_dir)
else:
dataloader = self._deserialize_from_local(serialized_gcs_path)
return dataloader
class TFDatasetSerializer(serializers_base.Serializer):
"""Serializer responsible for serializing/deserializing a tf.data.Dataset."""
_metadata: serializers_base.SerializationMetadata = (
serializers_base.SerializationMetadata(serializer="TFDatasetSerializer")
)
def serialize(self, to_serialize: TFDataset, gcs_path: str, **kwargs) -> str:
del kwargs
if not _is_valid_gcs_path(gcs_path):
raise ValueError(f"Invalid gcs path: {gcs_path}")
TFDatasetSerializer._metadata.dependencies = (
supported_frameworks._get_deps_if_tensorflow_model(to_serialize)
)
try:
to_serialize.save(gcs_path)
except AttributeError:
tf.data.experimental.save(to_serialize, gcs_path)
return gcs_path
def deserialize(self, serialized_gcs_path: str, **kwargs) -> TFDataset:
del kwargs
try:
deserialized = tf.data.Dataset.load(serialized_gcs_path)
except AttributeError:
deserialized = tf.data.experimental.load(serialized_gcs_path)
return deserialized
class PandasDataSerializer(serializers_base.Serializer):
"""Serializer for pandas DataFrames."""
_metadata: serializers_base.SerializationMetadata = (
serializers_base.SerializationMetadata(serializer="PandasDataSerializer")
)
def serialize(self, to_serialize: PandasData, gcs_path: str, **kwargs) -> str:
del kwargs
if not _is_valid_gcs_path(gcs_path):
raise ValueError(f"Invalid gcs path: {gcs_path}")
PandasDataSerializer._metadata.dependencies = (
supported_frameworks._get_deps_if_pandas_dataframe(to_serialize)
)
if gcs_path.startswith("gs://"):
with tempfile.NamedTemporaryFile() as temp_file:
to_serialize.to_parquet(temp_file.name)
temp_file.flush()
temp_file.seek(0)