-
Notifications
You must be signed in to change notification settings - Fork 354
/
Copy pathtest_training_jobs.py
8580 lines (7592 loc) · 342 KB
/
test_training_jobs.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.
#
from distutils import core
import copy
import os
import functools
import importlib
import logging
import pathlib
import pytest
import subprocess
import shutil
import sys
import tarfile
import tempfile
import uuid
from unittest import mock
from unittest.mock import patch
from google.cloud import aiplatform
from google.cloud.aiplatform import base
from google.cloud.aiplatform import datasets
from google.cloud.aiplatform import explain
from google.cloud.aiplatform import initializer
from google.cloud.aiplatform import schema
from google.cloud.aiplatform import training_jobs
from google.cloud.aiplatform import utils
from google.cloud.aiplatform.utils import source_utils
from google.cloud.aiplatform.utils import worker_spec_utils
from google.cloud.aiplatform.compat.services import (
job_service_client,
model_service_client,
pipeline_service_client,
)
from google.cloud.aiplatform.compat.types import (
custom_job as gca_custom_job,
dataset as gca_dataset,
encryption_spec as gca_encryption_spec,
env_var as gca_env_var,
io as gca_io,
job_state as gca_job_state,
model as gca_model,
pipeline_state as gca_pipeline_state,
training_pipeline as gca_training_pipeline,
)
from google.cloud import storage
from google.protobuf import json_format
from google.protobuf import struct_pb2
from google.protobuf import duration_pb2 # type: ignore
import constants as test_constants
_TEST_BUCKET_NAME = "test-bucket"
_TEST_GCS_PATH_WITHOUT_BUCKET = "path/to/folder"
_TEST_GCS_PATH = f"{_TEST_BUCKET_NAME}/{_TEST_GCS_PATH_WITHOUT_BUCKET}"
_TEST_GCS_PATH_WITH_TRAILING_SLASH = f"{_TEST_GCS_PATH}/"
_TEST_LOCAL_SCRIPT_FILE_NAME = (
test_constants.TrainingJobConstants._TEST_LOCAL_SCRIPT_FILE_NAME
)
_TEST_TEMPDIR = tempfile.mkdtemp()
_TEST_LOCAL_SCRIPT_FILE_PATH = os.path.join(_TEST_TEMPDIR, _TEST_LOCAL_SCRIPT_FILE_NAME)
_TEST_PYTHON_SOURCE = """
print('hello world')
"""
_TEST_REQUIREMENTS = test_constants.TrainingJobConstants._TEST_REQUIREMENTS
_TEST_DATASET_DISPLAY_NAME = "test-dataset-display-name"
_TEST_DATASET_NAME = "test-dataset-name"
_TEST_DISPLAY_NAME = "test-display-name"
_TEST_METADATA_SCHEMA_URI_TABULAR = schema.dataset.metadata.tabular
_TEST_TRAINING_CONTAINER_IMAGE = (
test_constants.TrainingJobConstants._TEST_TRAINING_CONTAINER_IMAGE
)
_TEST_TRAINING_CONTAINER_CMD = ["python3", "task.py"]
_TEST_SERVING_CONTAINER_IMAGE = (
test_constants.TrainingJobConstants._TEST_TRAINING_CONTAINER_IMAGE
)
_TEST_SERVING_CONTAINER_PREDICTION_ROUTE = (
test_constants.TrainingJobConstants._TEST_SERVING_CONTAINER_PREDICTION_ROUTE
)
_TEST_SERVING_CONTAINER_HEALTH_ROUTE = (
test_constants.TrainingJobConstants._TEST_SERVING_CONTAINER_HEALTH_ROUTE
)
_TEST_MODULE_NAME = test_constants.TrainingJobConstants._TEST_MODULE_NAME
_TEST_METADATA_SCHEMA_URI_NONTABULAR = schema.dataset.metadata.image
_TEST_ANNOTATION_SCHEMA_URI = schema.dataset.annotation.image.classification
_TEST_BASE_OUTPUT_DIR = "gs://test-base-output-dir"
_TEST_SERVICE_ACCOUNT = test_constants.ProjectConstants._TEST_SERVICE_ACCOUNT
_TEST_BIGQUERY_DESTINATION = "bq://my-project"
_TEST_RUN_ARGS = test_constants.TrainingJobConstants._TEST_RUN_ARGS
_TEST_REPLICA_COUNT = test_constants.TrainingJobConstants._TEST_REPLICA_COUNT
_TEST_MACHINE_TYPE = test_constants.TrainingJobConstants._TEST_MACHINE_TYPE
_TEST_MACHINE_TYPE_TPU = test_constants.TrainingJobConstants._TEST_MACHINE_TYPE_TPU
_TEST_MACHINE_TYPE_TPU_V5E = (
test_constants.TrainingJobConstants._TEST_MACHINE_TYPE_TPU_V5E
)
_TEST_REDUCTION_SERVER_REPLICA_COUNT = (
test_constants.TrainingJobConstants._TEST_REDUCTION_SERVER_REPLICA_COUNT
)
_TEST_REDUCTION_SERVER_MACHINE_TYPE = (
test_constants.TrainingJobConstants._TEST_REDUCTION_SERVER_MACHINE_TYPE
)
_TEST_REDUCTION_SERVER_CONTAINER_URI = (
test_constants.TrainingJobConstants._TEST_REDUCTION_SERVER_CONTAINER_URI
)
_TEST_ACCELERATOR_TPU_TYPE = (
test_constants.TrainingJobConstants._TEST_ACCELERATOR_TPU_TYPE
)
_TEST_ACCELERATOR_TYPE = test_constants.TrainingJobConstants._TEST_ACCELERATOR_TYPE
_TEST_INVALID_ACCELERATOR_TYPE = "NVIDIA_DOES_NOT_EXIST"
_TEST_ACCELERATOR_COUNT = test_constants.TrainingJobConstants._TEST_ACCELERATOR_COUNT
_TEST_BOOT_DISK_TYPE_DEFAULT = (
test_constants.TrainingJobConstants._TEST_BOOT_DISK_TYPE_DEFAULT
)
_TEST_BOOT_DISK_SIZE_GB_DEFAULT = (
test_constants.TrainingJobConstants._TEST_BOOT_DISK_SIZE_GB_DEFAULT
)
_TEST_BOOT_DISK_TYPE = test_constants.TrainingJobConstants._TEST_BOOT_DISK_TYPE
_TEST_BOOT_DISK_SIZE_GB = test_constants.TrainingJobConstants._TEST_BOOT_DISK_SIZE_GB
_TEST_MODEL_DISPLAY_NAME = test_constants.TrainingJobConstants._TEST_MODEL_DISPLAY_NAME
_TEST_LABELS = test_constants.ProjectConstants._TEST_LABELS
_TEST_MODEL_LABELS = test_constants.TrainingJobConstants._TEST_MODEL_LABELS
_TEST_TRAINING_FRACTION_SPLIT = (
test_constants.TrainingJobConstants._TEST_TRAINING_FRACTION_SPLIT
)
_TEST_VALIDATION_FRACTION_SPLIT = (
test_constants.TrainingJobConstants._TEST_VALIDATION_FRACTION_SPLIT
)
_TEST_TEST_FRACTION_SPLIT = (
test_constants.TrainingJobConstants._TEST_TEST_FRACTION_SPLIT
)
_TEST_TRAINING_FILTER_SPLIT = "train"
_TEST_VALIDATION_FILTER_SPLIT = "validate"
_TEST_TEST_FILTER_SPLIT = "test"
_TEST_PREDEFINED_SPLIT_COLUMN_NAME = "split"
_TEST_TIMESTAMP_SPLIT_COLUMN_NAME = "timestamp"
_TEST_PROJECT = test_constants.ProjectConstants._TEST_PROJECT
_TEST_LOCATION = test_constants.ProjectConstants._TEST_LOCATION
_TEST_ID = test_constants.TrainingJobConstants._TEST_ID
_TEST_NAME = (
f"projects/{_TEST_PROJECT}/locations/{_TEST_LOCATION}/trainingPipelines/{_TEST_ID}"
)
_TEST_TENSORBOARD_RESOURCE_NAME = (
f"projects/{_TEST_PROJECT}/locations/{_TEST_LOCATION}/tensorboards/{_TEST_ID}"
)
_TEST_CUSTOM_JOB_RESOURCE_NAME = (
f"projects/{_TEST_PROJECT}/locations/{_TEST_LOCATION}/customJobs/{_TEST_ID}"
)
_TEST_MODEL_VERSION_DESCRIPTION = "My version description"
_TEST_MODEL_VERSION_ID = "2"
_TEST_ALT_PROJECT = "test-project-alt"
_TEST_ALT_LOCATION = "europe-west4"
_TEST_NETWORK = test_constants.TrainingJobConstants._TEST_NETWORK
_TEST_MODEL_INSTANCE_SCHEMA_URI = "instance_schema_uri.yaml"
_TEST_MODEL_PARAMETERS_SCHEMA_URI = "parameters_schema_uri.yaml"
_TEST_MODEL_PREDICTION_SCHEMA_URI = "prediction_schema_uri.yaml"
_TEST_MODEL_SERVING_CONTAINER_COMMAND = ["test_command"]
_TEST_MODEL_SERVING_CONTAINER_ARGS = ["test_args"]
_TEST_MODEL_SERVING_CONTAINER_ENVIRONMENT_VARIABLES = {
"learning_rate": 0.01,
"loss_fn": "mse",
}
_TEST_ENVIRONMENT_VARIABLES = (
test_constants.TrainingJobConstants._TEST_ENVIRONMENT_VARIABLES
)
_TEST_MODEL_SERVING_CONTAINER_PORTS = [8888, 10000]
_TEST_MODEL_DESCRIPTION = "test description"
_TEST_OUTPUT_PYTHON_PACKAGE_PATH = (
test_constants.TrainingJobConstants._TEST_OUTPUT_PYTHON_PACKAGE_PATH
)
_TEST_PACKAGE_GCS_URIS = [_TEST_OUTPUT_PYTHON_PACKAGE_PATH] * 2
_TEST_PYTHON_MODULE_NAME = "aiplatform.task"
_TEST_MODEL_NAME = f"projects/{_TEST_PROJECT}/locations/us-central1/models/{_TEST_ID}"
_TEST_PIPELINE_RESOURCE_NAME = (
f"projects/{_TEST_PROJECT}/locations/us-central1/trainingPipelines/{_TEST_ID}"
)
_TEST_CREDENTIALS = test_constants.TrainingJobConstants._TEST_CREDENTIALS
# Explanation Spec
_TEST_EXPLANATION_METADATA = explain.ExplanationMetadata(
inputs={
"features": {
"input_tensor_name": "dense_input",
"encoding": "BAG_OF_FEATURES",
"modality": "numeric",
"index_feature_mapping": ["abc", "def", "ghj"],
}
},
outputs={"medv": {"output_tensor_name": "dense_2"}},
)
_TEST_EXPLANATION_PARAMETERS = explain.ExplanationParameters(
{"sampled_shapley_attribution": {"path_count": 10}}
)
# CMEK encryption
_TEST_DEFAULT_ENCRYPTION_KEY_NAME = "key_default"
_TEST_DEFAULT_ENCRYPTION_SPEC = gca_encryption_spec.EncryptionSpec(
kms_key_name=_TEST_DEFAULT_ENCRYPTION_KEY_NAME
)
_TEST_PIPELINE_ENCRYPTION_KEY_NAME = "key_pipeline"
_TEST_PIPELINE_ENCRYPTION_SPEC = gca_encryption_spec.EncryptionSpec(
kms_key_name=_TEST_PIPELINE_ENCRYPTION_KEY_NAME
)
_TEST_MODEL_ENCRYPTION_KEY_NAME = "key_model"
_TEST_MODEL_ENCRYPTION_SPEC = gca_encryption_spec.EncryptionSpec(
kms_key_name=_TEST_MODEL_ENCRYPTION_KEY_NAME
)
_TEST_TIMEOUT = test_constants.TrainingJobConstants._TEST_TIMEOUT
_TEST_RESTART_JOB_ON_WORKER_RESTART = (
test_constants.TrainingJobConstants._TEST_RESTART_JOB_ON_WORKER_RESTART
)
_TEST_DISABLE_RETRIES = test_constants.TrainingJobConstants._TEST_DISABLE_RETRIES
_TEST_MAX_WAIT_DURATION = test_constants.TrainingJobConstants._TEST_MAX_WAIT_DURATION
_TEST_ENABLE_WEB_ACCESS = test_constants.TrainingJobConstants._TEST_ENABLE_WEB_ACCESS
_TEST_ENABLE_DASHBOARD_ACCESS = True
_TEST_WEB_ACCESS_URIS = test_constants.TrainingJobConstants._TEST_WEB_ACCESS_URIS
_TEST_DASHBOARD_ACCESS_URIS = {"workerpool0-0:8888": "uri"}
_TEST_PERSISTENT_RESOURCE_ID = (
test_constants.PersistentResourceConstants._TEST_PERSISTENT_RESOURCE_ID
)
_TEST_SPOT_STRATEGY = test_constants.TrainingJobConstants._TEST_SPOT_STRATEGY
_TEST_BASE_CUSTOM_JOB_PROTO = gca_custom_job.CustomJob(
job_spec=gca_custom_job.CustomJobSpec(),
)
def _get_custom_job_proto_with_enable_web_access(state=None, name=None, version="v1"):
custom_job_proto = copy.deepcopy(_TEST_BASE_CUSTOM_JOB_PROTO)
custom_job_proto.name = name
custom_job_proto.state = state
custom_job_proto.job_spec.enable_web_access = _TEST_ENABLE_WEB_ACCESS
if state == gca_job_state.JobState.JOB_STATE_RUNNING:
custom_job_proto.web_access_uris = _TEST_WEB_ACCESS_URIS
return custom_job_proto
def _get_custom_job_proto_with_enable_dashboard_access(
state=None, name=None, version="v1"
):
custom_job_proto = copy.deepcopy(_TEST_BASE_CUSTOM_JOB_PROTO)
custom_job_proto.name = name
custom_job_proto.state = state
custom_job_proto.job_spec.enable_dashboard_access = _TEST_ENABLE_DASHBOARD_ACCESS
if state == gca_job_state.JobState.JOB_STATE_RUNNING:
custom_job_proto.web_access_uris = _TEST_DASHBOARD_ACCESS_URIS
return custom_job_proto
def _get_custom_job_proto_with_persistent_resource_id(
state=None, name=None, version="v1"
):
custom_job_proto = copy.deepcopy(_TEST_BASE_CUSTOM_JOB_PROTO)
custom_job_proto.name = name
custom_job_proto.state = state
custom_job_proto.job_spec.persistent_resource_id = _TEST_PERSISTENT_RESOURCE_ID
return custom_job_proto
def _get_custom_job_proto_with_scheduling(state=None, name=None, version="v1"):
custom_job_proto = copy.deepcopy(_TEST_BASE_CUSTOM_JOB_PROTO)
custom_job_proto.name = name
custom_job_proto.state = state
custom_job_proto.job_spec.scheduling.timeout = duration_pb2.Duration(
seconds=_TEST_TIMEOUT
)
custom_job_proto.job_spec.scheduling.restart_job_on_worker_restart = (
_TEST_RESTART_JOB_ON_WORKER_RESTART
)
custom_job_proto.job_spec.scheduling.disable_retries = _TEST_DISABLE_RETRIES
custom_job_proto.job_spec.scheduling.max_wait_duration = duration_pb2.Duration(
seconds=_TEST_MAX_WAIT_DURATION
)
return custom_job_proto
def _get_custom_job_proto_with_spot_strategy(state=None, name=None, version="v1"):
custom_job_proto = copy.deepcopy(_TEST_BASE_CUSTOM_JOB_PROTO)
custom_job_proto.name = name
custom_job_proto.state = state
custom_job_proto.job_spec.scheduling.strategy = _TEST_SPOT_STRATEGY
return custom_job_proto
def local_copy_method(path):
shutil.copy(path, ".")
return pathlib.Path(path).name
@pytest.fixture
def get_training_job_custom_mock():
with patch.object(
pipeline_service_client.PipelineServiceClient, "get_training_pipeline"
) as get_training_job_custom_mock:
get_training_job_custom_mock.return_value = (
gca_training_pipeline.TrainingPipeline(
name=_TEST_PIPELINE_RESOURCE_NAME,
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED,
model_to_upload=gca_model.Model(name=_TEST_MODEL_NAME),
training_task_definition=schema.training_job.definition.custom_task,
)
)
yield get_training_job_custom_mock
@pytest.fixture
def get_training_job_custom_mock_no_model_to_upload():
with patch.object(
pipeline_service_client.PipelineServiceClient, "get_training_pipeline"
) as get_training_job_custom_mock:
get_training_job_custom_mock.return_value = (
gca_training_pipeline.TrainingPipeline(
name=_TEST_PIPELINE_RESOURCE_NAME,
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED,
model_to_upload=None,
training_task_definition=schema.training_job.definition.custom_task,
)
)
yield get_training_job_custom_mock
@pytest.fixture
def get_training_job_tabular_mock():
with patch.object(
pipeline_service_client.PipelineServiceClient, "get_training_pipeline"
) as get_training_job_tabular_mock:
get_training_job_tabular_mock.return_value = (
gca_training_pipeline.TrainingPipeline(
name=_TEST_PIPELINE_RESOURCE_NAME,
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED,
model_to_upload=gca_model.Model(name=_TEST_MODEL_NAME),
training_task_definition=schema.training_job.definition.automl_tabular,
)
)
yield get_training_job_tabular_mock
@pytest.fixture
def mock_client_bucket():
with patch.object(storage.Client, "bucket") as mock_client_bucket:
def blob_side_effect(name, mock_blob, bucket):
mock_blob.name = name
mock_blob.bucket = bucket
return mock_blob
MockBucket = mock.Mock(autospec=storage.Bucket)
MockBucket.name = _TEST_BUCKET_NAME
MockBlob = mock.Mock(autospec=storage.Blob)
MockBucket.blob.side_effect = functools.partial(
blob_side_effect, mock_blob=MockBlob, bucket=MockBucket
)
mock_client_bucket.return_value = MockBucket
yield mock_client_bucket, MockBlob
@pytest.fixture
def mock_get_backing_custom_job_with_enable_web_access():
with patch.object(
job_service_client.JobServiceClient, "get_custom_job"
) as get_custom_job_mock:
get_custom_job_mock.side_effect = [
_get_custom_job_proto_with_enable_web_access(
name=_TEST_CUSTOM_JOB_RESOURCE_NAME,
state=gca_job_state.JobState.JOB_STATE_PENDING,
),
_get_custom_job_proto_with_enable_web_access(
name=_TEST_CUSTOM_JOB_RESOURCE_NAME,
state=gca_job_state.JobState.JOB_STATE_RUNNING,
),
_get_custom_job_proto_with_enable_web_access(
name=_TEST_CUSTOM_JOB_RESOURCE_NAME,
state=gca_job_state.JobState.JOB_STATE_RUNNING,
),
_get_custom_job_proto_with_enable_web_access(
name=_TEST_CUSTOM_JOB_RESOURCE_NAME,
state=gca_job_state.JobState.JOB_STATE_RUNNING,
),
_get_custom_job_proto_with_enable_web_access(
name=_TEST_CUSTOM_JOB_RESOURCE_NAME,
state=gca_job_state.JobState.JOB_STATE_SUCCEEDED,
),
_get_custom_job_proto_with_enable_web_access(
name=_TEST_CUSTOM_JOB_RESOURCE_NAME,
state=gca_job_state.JobState.JOB_STATE_SUCCEEDED,
),
]
yield get_custom_job_mock
@pytest.fixture
def mock_get_backing_custom_job_with_enable_dashboard_access():
with patch.object(
job_service_client.JobServiceClient, "get_custom_job"
) as get_custom_job_mock:
get_custom_job_mock.side_effect = [
_get_custom_job_proto_with_enable_dashboard_access(
name=_TEST_CUSTOM_JOB_RESOURCE_NAME,
state=gca_job_state.JobState.JOB_STATE_PENDING,
),
_get_custom_job_proto_with_enable_dashboard_access(
name=_TEST_CUSTOM_JOB_RESOURCE_NAME,
state=gca_job_state.JobState.JOB_STATE_RUNNING,
),
_get_custom_job_proto_with_enable_dashboard_access(
name=_TEST_CUSTOM_JOB_RESOURCE_NAME,
state=gca_job_state.JobState.JOB_STATE_RUNNING,
),
_get_custom_job_proto_with_enable_dashboard_access(
name=_TEST_CUSTOM_JOB_RESOURCE_NAME,
state=gca_job_state.JobState.JOB_STATE_RUNNING,
),
_get_custom_job_proto_with_enable_dashboard_access(
name=_TEST_CUSTOM_JOB_RESOURCE_NAME,
state=gca_job_state.JobState.JOB_STATE_SUCCEEDED,
),
_get_custom_job_proto_with_enable_dashboard_access(
name=_TEST_CUSTOM_JOB_RESOURCE_NAME,
state=gca_job_state.JobState.JOB_STATE_SUCCEEDED,
),
]
yield get_custom_job_mock
@pytest.fixture
def mock_get_backing_custom_job_with_persistent_resource_id():
with patch.object(
job_service_client.JobServiceClient, "get_custom_job"
) as get_custom_job_mock:
get_custom_job_mock.side_effect = [
_get_custom_job_proto_with_persistent_resource_id(
name=_TEST_CUSTOM_JOB_RESOURCE_NAME,
state=gca_job_state.JobState.JOB_STATE_PENDING,
),
_get_custom_job_proto_with_persistent_resource_id(
name=_TEST_CUSTOM_JOB_RESOURCE_NAME,
state=gca_job_state.JobState.JOB_STATE_RUNNING,
),
_get_custom_job_proto_with_persistent_resource_id(
name=_TEST_CUSTOM_JOB_RESOURCE_NAME,
state=gca_job_state.JobState.JOB_STATE_RUNNING,
),
_get_custom_job_proto_with_persistent_resource_id(
name=_TEST_CUSTOM_JOB_RESOURCE_NAME,
state=gca_job_state.JobState.JOB_STATE_RUNNING,
),
_get_custom_job_proto_with_persistent_resource_id(
name=_TEST_CUSTOM_JOB_RESOURCE_NAME,
state=gca_job_state.JobState.JOB_STATE_SUCCEEDED,
),
_get_custom_job_proto_with_persistent_resource_id(
name=_TEST_CUSTOM_JOB_RESOURCE_NAME,
state=gca_job_state.JobState.JOB_STATE_SUCCEEDED,
),
]
yield get_custom_job_mock
@pytest.mark.skipif(
sys.executable is None, reason="requires python path to invoke subprocess"
)
@pytest.mark.usefixtures("google_auth_mock")
class TestTrainingScriptPythonPackagerHelpers:
def setup_method(self):
importlib.reload(initializer)
importlib.reload(aiplatform)
def test_timestamp_copy_to_gcs_calls_gcs_client_with_bucket(
self, mock_client_bucket
):
mock_client_bucket, mock_blob = mock_client_bucket
gcs_path = utils._timestamped_copy_to_gcs(
local_file_path=_TEST_LOCAL_SCRIPT_FILE_PATH,
gcs_dir=_TEST_BUCKET_NAME,
project=_TEST_PROJECT,
)
local_script_file_name = pathlib.Path(_TEST_LOCAL_SCRIPT_FILE_PATH).name
mock_client_bucket.assert_called_once_with(_TEST_BUCKET_NAME)
mock_client_bucket.return_value.blob.assert_called_once()
blob_arg = mock_client_bucket.return_value.blob.call_args[0][0]
assert blob_arg.startswith("aiplatform-")
assert blob_arg.endswith(_TEST_LOCAL_SCRIPT_FILE_NAME)
mock_blob.upload_from_filename.assert_called_once_with(
_TEST_LOCAL_SCRIPT_FILE_PATH
)
assert gcs_path.endswith(local_script_file_name)
assert gcs_path.startswith(f"gs://{_TEST_BUCKET_NAME}/aiplatform-")
def test_timestamp_copy_to_gcs_calls_gcs_client_with_gcs_path(
self, mock_client_bucket
):
mock_client_bucket, mock_blob = mock_client_bucket
gcs_path = utils._timestamped_copy_to_gcs(
local_file_path=_TEST_LOCAL_SCRIPT_FILE_PATH,
gcs_dir=_TEST_GCS_PATH_WITH_TRAILING_SLASH,
project=_TEST_PROJECT,
)
local_script_file_name = pathlib.Path(_TEST_LOCAL_SCRIPT_FILE_PATH).name
mock_client_bucket.assert_called_once_with(_TEST_BUCKET_NAME)
mock_client_bucket.return_value.blob.assert_called_once()
blob_arg = mock_client_bucket.return_value.blob.call_args[0][0]
assert blob_arg.startswith(f"{_TEST_GCS_PATH_WITHOUT_BUCKET}/aiplatform-")
assert blob_arg.endswith(f"{_TEST_LOCAL_SCRIPT_FILE_NAME}")
mock_blob.upload_from_filename.assert_called_once_with(
_TEST_LOCAL_SCRIPT_FILE_PATH
)
assert gcs_path.startswith(f"gs://{_TEST_GCS_PATH}/aiplatform-")
assert gcs_path.endswith(local_script_file_name)
def test_timestamp_copy_to_gcs_calls_gcs_client_with_trailing_slash(
self, mock_client_bucket
):
mock_client_bucket, mock_blob = mock_client_bucket
gcs_path = utils._timestamped_copy_to_gcs(
local_file_path=_TEST_LOCAL_SCRIPT_FILE_PATH,
gcs_dir=_TEST_GCS_PATH,
project=_TEST_PROJECT,
)
local_script_file_name = pathlib.Path(_TEST_LOCAL_SCRIPT_FILE_PATH).name
mock_client_bucket.assert_called_once_with(_TEST_BUCKET_NAME)
mock_client_bucket.return_value.blob.assert_called_once()
blob_arg = mock_client_bucket.return_value.blob.call_args[0][0]
assert blob_arg.startswith(f"{_TEST_GCS_PATH_WITHOUT_BUCKET}/aiplatform-")
assert blob_arg.endswith(_TEST_LOCAL_SCRIPT_FILE_NAME)
mock_blob.upload_from_filename.assert_called_once_with(
_TEST_LOCAL_SCRIPT_FILE_PATH
)
assert gcs_path.startswith(f"gs://{_TEST_GCS_PATH}/aiplatform-")
assert gcs_path.endswith(local_script_file_name)
def test_timestamp_copy_to_gcs_calls_gcs_client(self, mock_client_bucket):
mock_client_bucket, mock_blob = mock_client_bucket
gcs_path = utils._timestamped_copy_to_gcs(
local_file_path=_TEST_LOCAL_SCRIPT_FILE_PATH,
gcs_dir=_TEST_BUCKET_NAME,
project=_TEST_PROJECT,
)
mock_client_bucket.assert_called_once_with(_TEST_BUCKET_NAME)
mock_client_bucket.return_value.blob.assert_called_once()
mock_blob.upload_from_filename.assert_called_once_with(
_TEST_LOCAL_SCRIPT_FILE_PATH
)
assert gcs_path.endswith(pathlib.Path(_TEST_LOCAL_SCRIPT_FILE_PATH).name)
assert gcs_path.startswith(f"gs://{_TEST_BUCKET_NAME}")
def test_get_python_executable_raises_if_None(self):
with patch.object(sys, "executable", new=None):
with pytest.raises(EnvironmentError):
source_utils._get_python_executable()
def test_get_python_executable_returns_python_executable(self):
assert "python" in source_utils._get_python_executable().lower()
@pytest.mark.skipif(
sys.executable is None, reason="requires python path to invoke subprocess"
)
@pytest.mark.usefixtures("google_auth_mock")
class TestTrainingScriptPythonPackager:
def setup_method(self):
importlib.reload(initializer)
importlib.reload(aiplatform)
with open(_TEST_LOCAL_SCRIPT_FILE_PATH, "w") as fp:
fp.write(_TEST_PYTHON_SOURCE)
def teardown_method(self):
pathlib.Path(_TEST_LOCAL_SCRIPT_FILE_PATH).unlink()
python_package_file = f"{source_utils._TrainingScriptPythonPackager._ROOT_MODULE}-{source_utils._TrainingScriptPythonPackager._SETUP_PY_VERSION}.tar.gz"
if pathlib.Path(python_package_file).is_file():
pathlib.Path(python_package_file).unlink()
subprocess.check_output(
[
"pip3",
"uninstall",
"-y",
source_utils._TrainingScriptPythonPackager._ROOT_MODULE,
]
)
def test_packager_creates_and_copies_python_package(self):
tsp = source_utils._TrainingScriptPythonPackager(_TEST_LOCAL_SCRIPT_FILE_PATH)
tsp.package_and_copy(copy_method=local_copy_method)
assert pathlib.Path(
f"{tsp._ROOT_MODULE}-{tsp._SETUP_PY_VERSION}.tar.gz"
).is_file()
def test_created_package_module_is_installable_and_can_be_run(self):
tsp = source_utils._TrainingScriptPythonPackager(_TEST_LOCAL_SCRIPT_FILE_PATH)
source_dist_path = tsp.package_and_copy(copy_method=local_copy_method)
subprocess.check_output(["pip3", "install", source_dist_path])
module_output = subprocess.check_output(
[source_utils._get_python_executable(), "-m", tsp.module_name]
)
assert "hello world" in module_output.decode()
def test_requirements_are_in_package(self):
tsp = source_utils._TrainingScriptPythonPackager(
_TEST_LOCAL_SCRIPT_FILE_PATH, requirements=_TEST_REQUIREMENTS
)
source_dist_path = tsp.package_and_copy(copy_method=local_copy_method)
with tarfile.open(source_dist_path) as tf:
with tempfile.TemporaryDirectory() as tmpdirname:
setup_py_path = f"{source_utils._TrainingScriptPythonPackager._ROOT_MODULE}-{source_utils._TrainingScriptPythonPackager._SETUP_PY_VERSION}/setup.py"
tf.extract(setup_py_path, path=tmpdirname)
setup_py = core.run_setup(
pathlib.Path(tmpdirname, setup_py_path), stop_after="init"
)
assert _TEST_REQUIREMENTS == setup_py.install_requires
def test_packaging_fails_whith_RuntimeError(self):
with patch("subprocess.Popen") as mock_popen:
mock_subprocess = mock.Mock()
mock_subprocess.communicate.return_value = (b"", b"")
mock_subprocess.returncode = 1
mock_popen.return_value = mock_subprocess
tsp = source_utils._TrainingScriptPythonPackager(
_TEST_LOCAL_SCRIPT_FILE_PATH
)
with pytest.raises(RuntimeError):
tsp.package_and_copy(copy_method=local_copy_method)
def test_package_and_copy_to_gcs_copies_to_gcs(self, mock_client_bucket):
mock_client_bucket, mock_blob = mock_client_bucket
tsp = source_utils._TrainingScriptPythonPackager(_TEST_LOCAL_SCRIPT_FILE_PATH)
gcs_path = tsp.package_and_copy_to_gcs(
gcs_staging_dir=_TEST_BUCKET_NAME, project=_TEST_PROJECT
)
mock_client_bucket.assert_called_once_with(_TEST_BUCKET_NAME)
mock_client_bucket.return_value.blob.assert_called_once()
mock_blob.upload_from_filename.call_args[0][0].endswith(
"/trainer/dist/aiplatform_custom_trainer_script-0.1.tar.gz"
)
assert gcs_path.endswith("-aiplatform_custom_trainer_script-0.1.tar.gz")
assert gcs_path.startswith(f"gs://{_TEST_BUCKET_NAME}")
@pytest.fixture
def mock_pipeline_service_create():
with mock.patch.object(
pipeline_service_client.PipelineServiceClient, "create_training_pipeline"
) as mock_create_training_pipeline:
mock_create_training_pipeline.return_value = (
gca_training_pipeline.TrainingPipeline(
name=_TEST_PIPELINE_RESOURCE_NAME,
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED,
model_to_upload=gca_model.Model(name=_TEST_MODEL_NAME),
)
)
yield mock_create_training_pipeline
@pytest.fixture
def mock_pipeline_service_create_with_version():
with mock.patch.object(
pipeline_service_client.PipelineServiceClient, "create_training_pipeline"
) as mock_create_training_pipeline:
mock_create_training_pipeline.return_value = (
gca_training_pipeline.TrainingPipeline(
name=_TEST_PIPELINE_RESOURCE_NAME,
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED,
model_to_upload=gca_model.Model(
name=_TEST_MODEL_NAME, version_id=_TEST_MODEL_VERSION_ID
),
)
)
yield mock_create_training_pipeline
def make_training_pipeline(state, add_training_task_metadata=True):
return gca_training_pipeline.TrainingPipeline(
name=_TEST_PIPELINE_RESOURCE_NAME,
state=state,
model_to_upload=gca_model.Model(name=_TEST_MODEL_NAME),
training_task_inputs={"tensorboard": _TEST_TENSORBOARD_RESOURCE_NAME},
training_task_metadata=(
{"backingCustomJob": _TEST_CUSTOM_JOB_RESOURCE_NAME}
if add_training_task_metadata
else None
),
)
def make_training_pipeline_with_version(state, add_training_task_metadata=True):
return gca_training_pipeline.TrainingPipeline(
name=_TEST_PIPELINE_RESOURCE_NAME,
state=state,
model_to_upload=gca_model.Model(
name=_TEST_MODEL_NAME, version_id=_TEST_MODEL_VERSION_ID
),
training_task_inputs={"tensorboard": _TEST_TENSORBOARD_RESOURCE_NAME},
training_task_metadata=(
{"backingCustomJob": _TEST_CUSTOM_JOB_RESOURCE_NAME}
if add_training_task_metadata
else None
),
)
def make_training_pipeline_with_no_model_upload(state):
return gca_training_pipeline.TrainingPipeline(
name=_TEST_PIPELINE_RESOURCE_NAME,
state=state,
)
def make_training_pipeline_with_enable_web_access(state):
training_pipeline = gca_training_pipeline.TrainingPipeline(
name=_TEST_PIPELINE_RESOURCE_NAME,
state=state,
training_task_inputs={"enable_web_access": _TEST_ENABLE_WEB_ACCESS},
)
if state == gca_pipeline_state.PipelineState.PIPELINE_STATE_RUNNING:
training_pipeline.training_task_metadata = {
"backingCustomJob": _TEST_CUSTOM_JOB_RESOURCE_NAME
}
return training_pipeline
def make_training_pipeline_with_enable_dashboard_access(state):
training_pipeline = gca_training_pipeline.TrainingPipeline(
name=_TEST_PIPELINE_RESOURCE_NAME,
state=state,
training_task_inputs={"enable_dashboard_access": _TEST_ENABLE_DASHBOARD_ACCESS},
)
if state == gca_pipeline_state.PipelineState.PIPELINE_STATE_RUNNING:
training_pipeline.training_task_metadata = {
"backingCustomJob": _TEST_CUSTOM_JOB_RESOURCE_NAME
}
return training_pipeline
def make_training_pipeline_with_persistent_resource_id(state):
training_pipeline = gca_training_pipeline.TrainingPipeline(
name=_TEST_PIPELINE_RESOURCE_NAME,
state=state,
training_task_inputs={"persistent_resource_id": _TEST_PERSISTENT_RESOURCE_ID},
)
if state == gca_pipeline_state.PipelineState.PIPELINE_STATE_RUNNING:
training_pipeline.training_task_metadata = {
"backingCustomJob": _TEST_CUSTOM_JOB_RESOURCE_NAME
}
return training_pipeline
def make_training_pipeline_with_scheduling(state):
training_pipeline = gca_training_pipeline.TrainingPipeline(
name=_TEST_PIPELINE_RESOURCE_NAME,
state=state,
training_task_inputs={
"timeout": f"{_TEST_TIMEOUT}s",
"restart_job_on_worker_restart": _TEST_RESTART_JOB_ON_WORKER_RESTART,
"disable_retries": _TEST_DISABLE_RETRIES,
"max_wait_duration": f"{_TEST_MAX_WAIT_DURATION}s",
},
)
if state == gca_pipeline_state.PipelineState.PIPELINE_STATE_RUNNING:
training_pipeline.training_task_metadata = {
"backingCustomJob": _TEST_CUSTOM_JOB_RESOURCE_NAME
}
return training_pipeline
def make_training_pipeline_with_spot_strategy(state):
training_pipeline = gca_training_pipeline.TrainingPipeline(
name=_TEST_PIPELINE_RESOURCE_NAME,
state=state,
training_task_inputs={
"scheduling_strategy": _TEST_SPOT_STRATEGY,
},
)
if state == gca_pipeline_state.PipelineState.PIPELINE_STATE_RUNNING:
training_pipeline.training_task_metadata = {
"backingCustomJob": _TEST_CUSTOM_JOB_RESOURCE_NAME
}
return training_pipeline
@pytest.fixture
def mock_pipeline_service_get(make_call=make_training_pipeline):
with mock.patch.object(
pipeline_service_client.PipelineServiceClient, "get_training_pipeline"
) as mock_get_training_pipeline:
mock_get_training_pipeline.side_effect = [
make_call(
gca_pipeline_state.PipelineState.PIPELINE_STATE_RUNNING,
add_training_task_metadata=False,
),
make_call(
gca_pipeline_state.PipelineState.PIPELINE_STATE_RUNNING,
),
make_call(gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED),
make_call(gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED),
make_call(gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED),
make_call(gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED),
make_call(gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED),
make_call(gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED),
make_call(gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED),
make_call(gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED),
]
yield mock_get_training_pipeline
@pytest.fixture
def mock_pipeline_service_get_with_enable_web_access():
with mock.patch.object(
pipeline_service_client.PipelineServiceClient, "get_training_pipeline"
) as mock_get_training_pipeline:
mock_get_training_pipeline.side_effect = [
make_training_pipeline_with_enable_web_access(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_PENDING,
),
make_training_pipeline_with_enable_web_access(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_RUNNING,
),
make_training_pipeline_with_enable_web_access(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_RUNNING,
),
make_training_pipeline_with_enable_web_access(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_RUNNING,
),
make_training_pipeline_with_enable_web_access(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED,
),
make_training_pipeline_with_enable_web_access(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED,
),
]
yield mock_get_training_pipeline
@pytest.fixture
def mock_pipeline_service_get_with_enable_dashboard_access():
with mock.patch.object(
pipeline_service_client.PipelineServiceClient, "get_training_pipeline"
) as mock_get_training_pipeline:
mock_get_training_pipeline.side_effect = [
make_training_pipeline_with_enable_dashboard_access(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_PENDING,
),
make_training_pipeline_with_enable_dashboard_access(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_RUNNING,
),
make_training_pipeline_with_enable_dashboard_access(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_RUNNING,
),
make_training_pipeline_with_enable_dashboard_access(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_RUNNING,
),
make_training_pipeline_with_enable_dashboard_access(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED,
),
make_training_pipeline_with_enable_dashboard_access(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED,
),
]
yield mock_get_training_pipeline
@pytest.fixture
def mock_pipeline_service_get_with_persistent_resource_id():
with mock.patch.object(
pipeline_service_client.PipelineServiceClient, "get_training_pipeline"
) as mock_get_training_pipeline:
mock_get_training_pipeline.side_effect = [
make_training_pipeline_with_persistent_resource_id(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_PENDING,
),
make_training_pipeline_with_persistent_resource_id(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_RUNNING,
),
make_training_pipeline_with_persistent_resource_id(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_RUNNING,
),
make_training_pipeline_with_persistent_resource_id(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_RUNNING,
),
make_training_pipeline_with_persistent_resource_id(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED,
),
make_training_pipeline_with_persistent_resource_id(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED,
),
]
yield mock_get_training_pipeline
@pytest.fixture
def mock_pipeline_service_get_with_scheduling():
with mock.patch.object(
pipeline_service_client.PipelineServiceClient, "get_training_pipeline"
) as mock_get_training_pipeline:
mock_get_training_pipeline.side_effect = [
make_training_pipeline_with_scheduling(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_PENDING,
),
make_training_pipeline_with_scheduling(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_RUNNING,
),
make_training_pipeline_with_scheduling(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_RUNNING,
),
make_training_pipeline_with_scheduling(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_RUNNING,
),
make_training_pipeline_with_scheduling(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED,
),
make_training_pipeline_with_scheduling(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED,
),
]
yield mock_get_training_pipeline
@pytest.fixture
def mock_pipeline_service_get_with_spot_strategy():
with mock.patch.object(
pipeline_service_client.PipelineServiceClient, "get_training_pipeline"
) as mock_get_training_pipeline:
mock_get_training_pipeline.side_effect = [
make_training_pipeline_with_spot_strategy(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_PENDING,
),
make_training_pipeline_with_spot_strategy(
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_RUNNING,
),