-
Notifications
You must be signed in to change notification settings - Fork 448
Expand file tree
/
Copy pathexperiment_run_resource.py
More file actions
1605 lines (1375 loc) · 61.9 KB
/
experiment_run_resource.py
File metadata and controls
1605 lines (1375 loc) · 61.9 KB
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.
"""Vertex Experiment Run class."""
from collections import abc
import concurrent.futures
import functools
from typing import Any, Callable, Dict, List, Optional, Set, Union
from google.api_core import exceptions
from google.auth import credentials as auth_credentials
from google.cloud.aiplatform import base
from google.cloud.aiplatform import initializer
from google.cloud.aiplatform import pipeline_jobs
from google.cloud.aiplatform import jobs
from google.cloud.aiplatform.compat.types import artifact as gca_artifact
from google.cloud.aiplatform.compat.types import execution as gca_execution
from google.cloud.aiplatform.compat.types import (
tensorboard_time_series as gca_tensorboard_time_series,
)
from google.cloud.aiplatform.metadata import artifact
from google.cloud.aiplatform.metadata import constants
from google.cloud.aiplatform.metadata import context
from google.cloud.aiplatform.metadata import execution
from google.cloud.aiplatform.metadata import experiment_resources
from google.cloud.aiplatform.metadata import metadata
from google.cloud.aiplatform.metadata import _models
from google.cloud.aiplatform.metadata import resource
from google.cloud.aiplatform.metadata import utils as metadata_utils
from google.cloud.aiplatform.metadata.schema import utils as schema_utils
from google.cloud.aiplatform.metadata.schema.google import (
artifact_schema as google_artifact_schema,
)
from google.cloud.aiplatform.tensorboard import tensorboard_resource
from google.cloud.aiplatform.utils import rest_utils
from google.protobuf import timestamp_pb2
_LOGGER = base.Logger(__name__)
def _format_experiment_run_resource_id(experiment_name: str, run_name: str) -> str:
"""Formats the the experiment run resource id.
It is a concatenation of experiment name and run name.
Args:
experiment_name (str): Name of the experiment which is it's resource id.
run_name (str): Name of the run.
Returns:
The resource id to be used with this run.
"""
return f"{experiment_name}-{run_name}"
def _v1_not_supported(method: Callable) -> Callable:
"""Helpers wrapper for backward compatibility. Raises when using an API not support for legacy runs."""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if isinstance(self._metadata_node, execution.Execution):
raise NotImplementedError(
f"{self._run_name} is an Execution run created during Vertex Experiment Preview and does not support"
f" {method.__name__}. Please create a new Experiment run to use this method."
)
else:
return method(self, *args, **kwargs)
return wrapper
class ExperimentRun(
experiment_resources._ExperimentLoggable,
experiment_loggable_schemas=(
experiment_resources._ExperimentLoggableSchema(
title=constants.SYSTEM_EXPERIMENT_RUN, type=context.Context
),
# backwards compatibility with Preview Experiment runs
experiment_resources._ExperimentLoggableSchema(
title=constants.SYSTEM_RUN, type=execution.Execution
),
),
):
"""A Vertex AI Experiment run."""
def __init__(
self,
run_name: str,
experiment: Union[experiment_resources.Experiment, str],
*,
project: Optional[str] = None,
location: Optional[str] = None,
credentials: Optional[auth_credentials.Credentials] = None,
):
"""
```py
my_run = aiplatform.ExperimentRun('my-run', experiment='my-experiment')
```
Args:
run_name (str):
Required. The name of this run.
experiment (Union[experiment_resources.Experiment, str]):
Required. The name or instance of this experiment.
project (str):
Optional. Project where this experiment run is located. Overrides project set in
aiplatform.init.
location (str):
Optional. Location where this experiment run is located. Overrides location set in
aiplatform.init.
credentials (auth_credentials.Credentials):
Optional. Custom credentials used to retrieve this experiment run. Overrides
credentials set in aiplatform.init.
"""
self._experiment = self._get_experiment(
experiment=experiment,
project=project,
location=location,
credentials=credentials,
)
self._run_name = run_name
run_id = _format_experiment_run_resource_id(
experiment_name=self._experiment.name, run_name=run_name
)
metadata_args = dict(
project=project,
location=location,
credentials=credentials,
)
def _get_context() -> context.Context:
with experiment_resources._SetLoggerLevel(resource):
run_context = context.Context(
**{**metadata_args, "resource_name": run_id}
)
if run_context.schema_title != constants.SYSTEM_EXPERIMENT_RUN:
raise ValueError(
f"Run {run_name} must be of type {constants.SYSTEM_EXPERIMENT_RUN}"
f" but is of type {run_context.schema_title}"
)
return run_context
try:
self._metadata_node = _get_context()
except exceptions.NotFound as context_not_found:
try:
# backward compatibility
self._v1_resolve_experiment_run(
{
**metadata_args,
"execution_name": run_id,
}
)
except exceptions.NotFound:
raise context_not_found
else:
self._backing_tensorboard_run = self._lookup_tensorboard_run_artifact()
# initially set to None. Will initially update from resource then track locally.
self._largest_step: Optional[int] = None
def _v1_resolve_experiment_run(self, metadata_args: Dict[str, Any]):
"""Resolves preview Experiment.
Args:
metadata_args (Dict[str, Any): Arguments to pass to Execution constructor.
"""
def _get_execution():
with experiment_resources._SetLoggerLevel(resource):
run_execution = execution.Execution(**metadata_args)
if run_execution.schema_title != constants.SYSTEM_RUN:
# note this will raise the context not found exception in the constructor
raise exceptions.NotFound("Experiment run not found.")
return run_execution
self._metadata_node = _get_execution()
self._metadata_metric_artifact = self._v1_get_metric_artifact()
def _v1_get_metric_artifact(self) -> artifact.Artifact:
"""Resolves metric artifact for backward compatibility.
Returns:
Instance of Artifact that represents this run's metric artifact.
"""
metadata_args = dict(
artifact_name=self._v1_format_artifact_name(self._metadata_node.name),
project=self.project,
location=self.location,
credentials=self.credentials,
)
with experiment_resources._SetLoggerLevel(resource):
metric_artifact = artifact.Artifact(**metadata_args)
if metric_artifact.schema_title != constants.SYSTEM_METRICS:
# note this will raise the context not found exception in the constructor
raise exceptions.NotFound("Experiment run not found.")
return metric_artifact
@staticmethod
def _v1_format_artifact_name(run_id: str) -> str:
"""Formats resource id of legacy metric artifact for this run."""
return f"{run_id}-metrics"
def _get_context(self) -> context.Context:
"""Returns this metadata context that represents this run.
Returns:
Context instance of this run.
"""
return self._metadata_node
@property
def resource_id(self) -> str:
"""The resource ID of this experiment run's Metadata context.
The resource ID is the final part of the resource name:
``projects/{project}/locations/{location}/metadataStores/{metadatastore}/contexts/{resource ID}``
"""
return self._metadata_node.name
@property
def name(self) -> str:
"""This run's name used to identify this run within it's Experiment."""
return self._run_name
@property
def resource_name(self) -> str:
"""This run's Metadata context resource name.
In the format: ``projects/{project}/locations/{location}/metadataStores/{metadatastore}/contexts/{context}``
"""
return self._metadata_node.resource_name
@property
def project(self) -> str:
"""The project that this experiment run is located in."""
return self._metadata_node.project
@property
def location(self) -> str:
"""The location that this experiment is located in."""
return self._metadata_node.location
@property
def credentials(self) -> auth_credentials.Credentials:
"""The credentials used to access this experiment run."""
return self._metadata_node.credentials
@property
def state(self) -> gca_execution.Execution.State:
"""The state of this run."""
if self._is_legacy_experiment_run():
return self._metadata_node.state
else:
return getattr(
gca_execution.Execution.State,
self._metadata_node.metadata[constants._STATE_KEY],
)
@staticmethod
def _get_experiment(
experiment: Optional[Union[experiment_resources.Experiment, str]] = None,
project: Optional[str] = None,
location: Optional[str] = None,
credentials: Optional[auth_credentials.Credentials] = None,
) -> experiment_resources.Experiment:
"""Helper method ot get the experiment by name(str) or instance.
Args:
experiment(str):
Optional. The name of this experiment. Defaults to experiment set in aiplatform.init if not provided.
project (str):
Optional. Project where this experiment is located. Overrides project set in
aiplatform.init.
location (str):
Optional. Location where this experiment is located. Overrides location set in
aiplatform.init.
credentials (auth_credentials.Credentials):
Optional. Custom credentials used to retrieve this experiment. Overrides
credentials set in aiplatform.init.
Raises:
ValueError if experiment is None and experiment has not been set using aiplatform.init.
"""
experiment = experiment or initializer.global_config.experiment
if not experiment:
raise ValueError(
"experiment must be provided or experiment should be set using aiplatform.init"
)
if not isinstance(experiment, experiment_resources.Experiment):
experiment = experiment_resources.Experiment(
experiment_name=experiment,
project=project,
location=location,
credentials=credentials,
)
return experiment
def _is_backing_tensorboard_run_artifact(self, artifact: artifact.Artifact) -> bool:
"""Helper method to confirm tensorboard run metadata artifact is this run's tensorboard artifact.
Args:
artifact (artifact.Artifact): Required. Instance of metadata Artifact.
Returns:
bool whether the provided artifact is this run's TensorboardRun's artifact.
"""
return all(
[
artifact.metadata.get(constants._VERTEX_EXPERIMENT_TRACKING_LABEL),
artifact.name == self._tensorboard_run_id(self._metadata_node.name),
artifact.schema_title
== constants._TENSORBOARD_RUN_REFERENCE_ARTIFACT.schema_title,
]
)
def _is_legacy_experiment_run(self) -> bool:
"""Helper method that return True if this is a legacy experiment run."""
return isinstance(self._metadata_node, execution.Execution)
def update_state(self, state: gca_execution.Execution.State):
"""Update the state of this experiment run.
```py
my_run = aiplatform.ExperimentRun('my-run', experiment='my-experiment')
my_run.update_state(state=aiplatform.gapic.Execution.State.COMPLETE)
```
Args:
state (aiplatform.gapic.Execution.State): State of this run.
"""
if self._is_legacy_experiment_run():
self._metadata_node.update(state=state)
else:
self._metadata_node.update(metadata={constants._STATE_KEY: state.name})
def _lookup_tensorboard_run_artifact(
self,
) -> Optional[experiment_resources._VertexResourceWithMetadata]:
"""Helpers method to resolve this run's TensorboardRun Artifact if it exists.
Returns:
Tuple of Tensorboard Run Artifact and TensorboardRun is it exists.
"""
with experiment_resources._SetLoggerLevel(resource):
try:
tensorboard_run_artifact = artifact.Artifact(
artifact_name=self._tensorboard_run_id(self._metadata_node.name),
project=self._metadata_node.project,
location=self._metadata_node.location,
credentials=self._metadata_node.credentials,
)
except exceptions.NotFound:
tensorboard_run_artifact = None
if tensorboard_run_artifact and self._is_backing_tensorboard_run_artifact(
tensorboard_run_artifact
):
return experiment_resources._VertexResourceWithMetadata(
resource=tensorboard_resource.TensorboardRun(
tensorboard_run_artifact.metadata[
constants.GCP_ARTIFACT_RESOURCE_NAME_KEY
]
),
metadata=tensorboard_run_artifact,
)
@classmethod
def get(
cls,
run_name: str,
*,
experiment: Optional[Union[experiment_resources.Experiment, str]] = None,
project: Optional[str] = None,
location: Optional[str] = None,
credentials: Optional[auth_credentials.Credentials] = None,
) -> Optional["ExperimentRun"]:
"""Gets experiment run if one exists with this run_name.
Args:
run_name (str):
Required. The name of this run.
experiment (Union[experiment_resources.Experiment, str]):
Optional. The name or instance of this experiment.
If not set, use the default experiment in `aiplatform.init`
project (str):
Optional. Project where this experiment run is located.
Overrides project set in aiplatform.init.
location (str):
Optional. Location where this experiment run is located.
Overrides location set in aiplatform.init.
credentials (auth_credentials.Credentials):
Optional. Custom credentials used to retrieve this experiment run.
Overrides credentials set in aiplatform.init.
Returns:
Vertex AI experimentRun or None if no resource was found.
"""
experiment = experiment or metadata._experiment_tracker.experiment
if not experiment:
raise ValueError(
"experiment must be provided or "
"experiment should be set using aiplatform.init"
)
try:
return cls(
run_name=run_name,
experiment=experiment,
project=project,
location=location,
credentials=credentials,
)
except exceptions.NotFound:
return None
def _initialize_experiment_run(
self,
node: Union[context.Context, execution.Execution],
experiment: Optional[experiment_resources.Experiment] = None,
lookup_tensorboard_run: bool = True,
):
self._experiment = experiment
self._run_name = node.display_name
self._metadata_node = node
self._largest_step = None
self._backing_tensorboard_run = None
self._metadata_metric_artifact = None
if self._is_legacy_experiment_run():
self._metadata_metric_artifact = self._v1_get_metric_artifact()
if not self._is_legacy_experiment_run() and lookup_tensorboard_run:
self._backing_tensorboard_run = self._lookup_tensorboard_run_artifact()
if not self._backing_tensorboard_run:
self._assign_to_experiment_backing_tensorboard()
@classmethod
def list(
cls,
*,
experiment: Optional[Union[experiment_resources.Experiment, str]] = None,
project: Optional[str] = None,
location: Optional[str] = None,
credentials: Optional[auth_credentials.Credentials] = None,
) -> List["ExperimentRun"]:
"""List the experiment runs for a given aiplatform.Experiment.
```py
my_runs = aiplatform.ExperimentRun.list(experiment='my-experiment')
```
Args:
experiment (Union[aiplatform.Experiment, str]):
Optional. The experiment name or instance to list the experiment run from. If not provided,
will use the experiment set in aiplatform.init.
project (str):
Optional. Project where this experiment is located. Overrides project set in
aiplatform.init.
location (str):
Optional. Location where this experiment is located. Overrides location set in
aiplatform.init.
credentials (auth_credentials.Credentials):
Optional. Custom credentials used to retrieve this experiment. Overrides
credentials set in aiplatform.init.
Returns:
List of experiment runs.
"""
experiment = cls._get_experiment(
experiment=experiment,
project=project,
location=location,
credentials=credentials,
)
metadata_args = dict(
project=experiment._metadata_context.project,
location=experiment._metadata_context.location,
credentials=experiment._metadata_context.credentials,
)
filter_str = metadata_utils._make_filter_string(
schema_title=constants.SYSTEM_EXPERIMENT_RUN,
parent_contexts=[experiment.resource_name],
)
run_contexts = context.Context.list(filter=filter_str, **metadata_args)
filter_str = metadata_utils._make_filter_string(
schema_title=constants.SYSTEM_RUN, in_context=[experiment.resource_name]
)
run_executions = execution.Execution.list(filter=filter_str, **metadata_args)
def _create_experiment_run(context: context.Context) -> ExperimentRun:
this_experiment_run = cls.__new__(cls)
this_experiment_run._initialize_experiment_run(context, experiment)
return this_experiment_run
def _create_v1_experiment_run(
execution: execution.Execution,
) -> ExperimentRun:
this_experiment_run = cls.__new__(cls)
this_experiment_run._initialize_experiment_run(execution, experiment)
return this_experiment_run
if run_contexts or run_executions:
with concurrent.futures.ThreadPoolExecutor(
max_workers=max([len(run_contexts), len(run_executions)])
) as executor:
submissions = [
executor.submit(_create_experiment_run, context)
for context in run_contexts
]
experiment_runs = [submission.result() for submission in submissions]
submissions = [
executor.submit(_create_v1_experiment_run, execution)
for execution in run_executions
]
for submission in submissions:
experiment_runs.append(submission.result())
return experiment_runs
else:
return []
@classmethod
def _query_experiment_row(
cls,
node: Union[context.Context, execution.Execution],
experiment: Optional[experiment_resources.Experiment] = None,
include_time_series: bool = True,
) -> experiment_resources._ExperimentRow:
"""Retrieves the runs metric and parameters into an experiment run row.
Args:
node (Union[context._Context, execution.Execution]):
Required. Metadata node instance that represents this run.
experiment:
Optional. Experiment associated with this run.
include_time_series (bool):
Optional. Whether or not to include time series metrics in df.
Default is True.
Returns:
Experiment run row that represents this run.
"""
this_experiment_run = cls.__new__(cls)
this_experiment_run._initialize_experiment_run(
node, experiment=experiment, lookup_tensorboard_run=include_time_series
)
row = experiment_resources._ExperimentRow(
experiment_run_type=node.schema_title,
name=node.display_name,
)
row.params = this_experiment_run.get_params()
row.metrics = this_experiment_run.get_metrics()
row.state = this_experiment_run.get_state()
if include_time_series:
row.time_series_metrics = (
this_experiment_run._get_latest_time_series_metric_columns()
)
return row
def _get_logged_pipeline_runs(self) -> List[context.Context]:
"""Returns Pipeline Run contexts logged to this Experiment Run.
Returns:
List of Pipeline system.PipelineRun contexts.
"""
service_request_args = dict(
project=self._metadata_node.project,
location=self._metadata_node.location,
credentials=self._metadata_node.credentials,
)
filter_str = metadata_utils._make_filter_string(
schema_title=constants.SYSTEM_PIPELINE_RUN,
parent_contexts=[self._metadata_node.resource_name],
)
return context.Context.list(filter=filter_str, **service_request_args)
def _get_latest_time_series_metric_columns(self) -> Dict[str, Union[float, int]]:
"""Determines the latest step for each time series metric.
Returns:
Dictionary mapping time series metric key to the latest step of that metric.
"""
if self._backing_tensorboard_run:
time_series_metrics = (
self._backing_tensorboard_run.resource.read_time_series_data()
)
return {
display_name: data.values[-1].scalar.value
for display_name, data in time_series_metrics.items()
if (
data.values
and data.value_type
== gca_tensorboard_time_series.TensorboardTimeSeries.ValueType.SCALAR
)
}
return {}
def _log_pipeline_job(self, pipeline_job: pipeline_jobs.PipelineJob):
"""Associate this PipelineJob's Context to the current ExperimentRun Context as a child context.
Args:
pipeline_job (pipeline_jobs.PipelineJob):
Required. The PipelineJob to associate.
"""
pipeline_job_context = pipeline_job._get_context()
self._metadata_node.add_context_children([pipeline_job_context])
@_v1_not_supported
def log(
self,
*,
pipeline_job: Optional[pipeline_jobs.PipelineJob] = None,
):
"""Log a Vertex Resource to this experiment run.
```py
my_run = aiplatform.ExperimentRun('my-run', experiment='my-experiment')
my_job = aiplatform.PipelineJob(...)
my_job.submit()
my_run.log(my_job)
```
Args:
pipeline_job (aiplatform.PipelineJob): Optional. A Vertex PipelineJob.
"""
if pipeline_job:
self._log_pipeline_job(pipeline_job=pipeline_job)
@staticmethod
def _validate_run_id(run_id: str):
"""Validates the run id.
Args:
run_id(str): Required. The run id to validate.
Raises:
ValueError if run id is too long.
"""
if len(run_id) > constants._EXPERIMENT_RUN_MAX_LENGTH:
raise ValueError(
f"Length of Experiment ID and Run ID cannot be greater than {constants._EXPERIMENT_RUN_MAX_LENGTH}. "
f"{run_id} is of length {len(run_id)}"
)
@classmethod
def create(
cls,
run_name: str,
*,
experiment: Optional[Union[experiment_resources.Experiment, str]] = None,
tensorboard: Optional[Union[tensorboard_resource.Tensorboard, str]] = None,
state: gca_execution.Execution.State = gca_execution.Execution.State.RUNNING,
project: Optional[str] = None,
location: Optional[str] = None,
credentials: Optional[auth_credentials.Credentials] = None,
) -> "ExperimentRun":
"""Creates a new experiment run in Vertex AI Experiments.
```py
my_run = aiplatform.ExperimentRun.create('my-run', experiment='my-experiment')
```
Args:
run_name (str): Required. The name of this run.
experiment (Union[aiplatform.Experiment, str]):
Optional. The name or instance of the experiment to create this run under.
If not provided, will default to the experiment set in `aiplatform.init`.
tensorboard (Union[aiplatform.Tensorboard, str]):
Optional. The resource name or instance of Vertex Tensorboard to use as the backing
Tensorboard for time series metric logging. If not provided, will default to the
the backing tensorboard of parent experiment if set. Must be in same project and location
as this experiment run.
state (aiplatform.gapic.Execution.State):
Optional. The state of this run. Defaults to RUNNING.
project (str):
Optional. Project where this experiment will be created. Overrides project set in
aiplatform.init.
location (str):
Optional. Location where this experiment will be created. Overrides location set in
aiplatform.init.
credentials (auth_credentials.Credentials):
Optional. Custom credentials used to create this experiment. Overrides
credentials set in aiplatform.init.
Returns:
The newly created experiment run.
"""
experiment = cls._get_experiment(
experiment, project=project, location=location, credentials=credentials
)
run_id = _format_experiment_run_resource_id(
experiment_name=experiment.name, run_name=run_name
)
cls._validate_run_id(run_id)
def _create_context():
with experiment_resources._SetLoggerLevel(resource):
return context.Context._create(
resource_id=run_id,
display_name=run_name,
schema_title=constants.SYSTEM_EXPERIMENT_RUN,
schema_version=constants.SCHEMA_VERSIONS[
constants.SYSTEM_EXPERIMENT_RUN
],
metadata={
constants._PARAM_KEY: {},
constants._METRIC_KEY: {},
constants._STATE_KEY: state.name,
},
project=project,
location=location,
credentials=credentials,
)
metadata_context = _create_context()
if metadata_context is None:
raise RuntimeError(
f"Experiment Run with name {run_name} in {experiment.name} already exists."
)
experiment_run = cls.__new__(cls)
experiment_run._experiment = experiment
experiment_run._run_name = metadata_context.display_name
experiment_run._metadata_node = metadata_context
experiment_run._backing_tensorboard_run = None
experiment_run._largest_step = None
try:
if tensorboard:
cls._assign_backing_tensorboard(
self=experiment_run,
tensorboard=tensorboard,
project=project,
location=location,
)
else:
cls._assign_to_experiment_backing_tensorboard(self=experiment_run)
except Exception as e:
metadata_context.delete()
raise e
experiment_run._associate_to_experiment(experiment)
return experiment_run
def _assign_to_experiment_backing_tensorboard(self):
"""Assigns parent Experiment backing tensorboard resource to this Experiment Run."""
backing_tensorboard_resource = (
self._experiment.get_backing_tensorboard_resource()
)
if backing_tensorboard_resource:
self.assign_backing_tensorboard(tensorboard=backing_tensorboard_resource)
def _assign_backing_tensorboard(
self,
tensorboard: Union[tensorboard_resource.Tensorboard, str],
project: Optional[str] = None,
location: Optional[str] = None,
):
"""Assign tensorboard as the backing tensorboard to this run.
Args:
tensorboard (Union[tensorboard_resource.Tensorboard, str]):
Required. Tensorboard instance or resource name.
"""
if isinstance(tensorboard, str):
tensorboard = tensorboard_resource.Tensorboard(
tensorboard,
project=project,
location=location,
credentials=self._metadata_node.credentials,
)
tensorboard_resource_name_parts = tensorboard._parse_resource_name(
tensorboard.resource_name
)
tensorboard_experiment_resource_name = (
tensorboard_resource.TensorboardExperiment._format_resource_name(
experiment=self._experiment.name, **tensorboard_resource_name_parts
)
)
try:
tensorboard_experiment = tensorboard_resource.TensorboardExperiment(
tensorboard_experiment_resource_name,
credentials=tensorboard.credentials,
)
except exceptions.NotFound:
with experiment_resources._SetLoggerLevel(tensorboard_resource):
tensorboard_experiment = (
tensorboard_resource.TensorboardExperiment.create(
tensorboard_experiment_id=self._experiment.name,
display_name=self._experiment.name,
tensorboard_name=tensorboard.resource_name,
project=project,
location=location,
credentials=tensorboard.credentials,
labels=constants._VERTEX_EXPERIMENT_TB_EXPERIMENT_LABEL,
)
)
tensorboard_experiment_name_parts = tensorboard_experiment._parse_resource_name(
tensorboard_experiment.resource_name
)
tensorboard_run_resource_name = (
tensorboard_resource.TensorboardRun._format_resource_name(
run=self._run_name, **tensorboard_experiment_name_parts
)
)
try:
tensorboard_run = tensorboard_resource.TensorboardRun(
tensorboard_run_resource_name
)
except exceptions.NotFound:
with experiment_resources._SetLoggerLevel(tensorboard_resource):
tensorboard_run = tensorboard_resource.TensorboardRun.create(
tensorboard_run_id=self._run_name,
tensorboard_experiment_name=tensorboard_experiment.resource_name,
project=project,
location=location,
credentials=tensorboard.credentials,
)
gcp_resource_url = rest_utils.make_gcp_resource_rest_url(tensorboard_run)
with experiment_resources._SetLoggerLevel(resource):
tensorboard_run_metadata_artifact = artifact.Artifact._create(
uri=gcp_resource_url,
resource_id=self._tensorboard_run_id(self._metadata_node.name),
metadata={
"resourceName": tensorboard_run.resource_name,
constants._VERTEX_EXPERIMENT_TRACKING_LABEL: True,
},
schema_title=constants._TENSORBOARD_RUN_REFERENCE_ARTIFACT.schema_title,
schema_version=constants._TENSORBOARD_RUN_REFERENCE_ARTIFACT.schema_version,
state=gca_artifact.Artifact.State.LIVE,
project=project,
location=location,
)
self._metadata_node.add_artifacts_and_executions(
artifact_resource_names=[tensorboard_run_metadata_artifact.resource_name]
)
self._backing_tensorboard_run = (
experiment_resources._VertexResourceWithMetadata(
resource=tensorboard_run, metadata=tensorboard_run_metadata_artifact
)
)
@staticmethod
def _tensorboard_run_id(run_id: str) -> str:
"""Helper method to format the tensorboard run artifact resource id for a run.
Args:
run_id: The resource id of the experiment run.
Returns:
Resource id for the associated tensorboard run artifact.
"""
return f"{run_id}{constants._TB_RUN_ARTIFACT_POST_FIX_ID}"
@_v1_not_supported
def assign_backing_tensorboard(
self, tensorboard: Union[tensorboard_resource.Tensorboard, str]
):
"""Assigns tensorboard as backing tensorboard to support timeseries metrics logging for this run.
Args:
tensorboard (Union[aiplatform.Tensorboard, str]):
Required. Tensorboard instance or resource name.
"""
backing_tensorboard = self._lookup_tensorboard_run_artifact()
if backing_tensorboard:
raise ValueError(
f"Experiment run {self._run_name} already associated to tensorboard resource {backing_tensorboard.resource.resource_name}.\n"
f"To delete backing tensorboard run, execute the following:\n"
f'tensorboard_run_artifact = aiplatform.metadata.artifact.Artifact(artifact_name=f"{self._tensorboard_run_id(self._metadata_node.name)}")\n'
f'tensorboard_run_resource = aiplatform.TensorboardRun(tensorboard_run_artifact.metadata["resourceName"])\n'
f"tensorboard_run_resource.delete()\n"
f"tensorboard_run_artifact.delete()"
)
self._assign_backing_tensorboard(tensorboard=tensorboard)
def _get_latest_time_series_step(self) -> int:
"""Gets latest time series step of all time series from Tensorboard resource.
Returns:
Latest step of all time series metrics.
"""
data = self._backing_tensorboard_run.resource.read_time_series_data()
return max(ts.values[-1].step if ts.values else 0 for ts in data.values())
@_v1_not_supported
def log_time_series_metrics(
self,
metrics: Dict[str, float],
step: Optional[int] = None,
wall_time: Optional[timestamp_pb2.Timestamp] = None,
):
"""Logs time series metrics to backing TensorboardRun of this Experiment Run.
```py
run.log_time_series_metrics({'accuracy': 0.9}, step=10)
```
Args:
metrics (Dict[str, Union[str, float]]):
Required. Dictionary of where keys are metric names and values are metric values.
step (int):
Optional. Step index of this data point within the run.
If not provided, the latest
step amongst all time series metrics already logged will be used.
wall_time (timestamp_pb2.Timestamp):
Optional. Wall clock timestamp when this data point is
generated by the end user.
If not provided, this will be generated based on the value from time.time()
Raises:
RuntimeError: If current experiment run doesn't have a backing Tensorboard resource.
"""
if not self._backing_tensorboard_run:
self._assign_to_experiment_backing_tensorboard()
if not self._backing_tensorboard_run:
raise RuntimeError(
"Please set this experiment run with backing tensorboard resource to use log_time_series_metrics."
)
self._soft_create_time_series(metric_keys=set(metrics.keys()))
if step is None:
step = self._largest_step or self._get_latest_time_series_step()
step += 1
self._largest_step = step
self._backing_tensorboard_run.resource.write_tensorboard_scalar_data(
time_series_data=metrics, step=step, wall_time=wall_time
)
def _soft_create_time_series(self, metric_keys: Set[str]):
"""Creates TensorboardTimeSeries for the metric keys if one currently does not exist.
Args:
metric_keys (Set[str]): Keys of the metrics.
"""
if any(
key
not in self._backing_tensorboard_run.resource._time_series_display_name_to_id_mapping
for key in metric_keys
):
self._backing_tensorboard_run.resource._sync_time_series_display_name_to_id_mapping()
for key in metric_keys:
if (