-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathexecution.py
More file actions
1464 lines (1197 loc) · 65.2 KB
/
execution.py
File metadata and controls
1464 lines (1197 loc) · 65.2 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
"""SageMaker Evaluation Execution Module.
This module provides classes for managing evaluation executions.
"""
from __future__ import absolute_import
# Standard library imports
import json
import logging
import os
import time
import uuid
from datetime import datetime
from typing import Any, Dict, List, Literal, Optional
# Third-party imports
from botocore.exceptions import ClientError
from pydantic import BaseModel, Field
from sagemaker.core.common_utils import TagsDict
from sagemaker.core.helper.session_helper import Session
from sagemaker.core.resources import Pipeline, PipelineExecution
from sagemaker.core.resources import Tag as ResourceTag # For Tag.get_all()
from sagemaker.core.shapes import Tag # For Pipeline.create() tags parameter
from sagemaker.core.telemetry.telemetry_logging import _telemetry_emitter
from sagemaker.core.telemetry.constants import Feature
# Local imports
from .constants import (
_TAG_SAGEMAKER_MODEL_EVALUATION,
EvalType,
_get_pipeline_name,
_get_pipeline_name_prefix,
)
logger = logging.getLogger(__name__)
def _create_evaluation_pipeline(
eval_type: EvalType,
role_arn: str,
pipeline_definition: str,
session: Optional[Any] = None,
region: Optional[str] = None,
tags: Optional[List[TagsDict]] = [],
) -> Any:
"""Helper method to create a SageMaker pipeline for evaluation.
Re-renders pipeline_definition with actual pipeline_name before creating.
Args:
eval_type (EvalType): Type of evaluation.
role_arn (str): IAM role ARN for pipeline execution.
pipeline_definition (str): JSON pipeline definition (Jinja2 template).
session (Optional[Any]): SageMaker session object.
region (Optional[str]): AWS region.
tags (Optional[List[TagsDict]]): List of tags to include in pipeline
Returns:
Any: Created Pipeline instance (ready for execution).
"""
from jinja2 import Template
pipeline_name = _get_pipeline_name(eval_type)
client_request_token = str(uuid.uuid4())
logger.info(f"Creating new pipeline: {pipeline_name}")
# Re-render pipeline definition with actual pipeline_name
template = Template(pipeline_definition)
resolved_pipeline_definition = template.render(pipeline_name=pipeline_name)
# Create tags for the pipeline
# Note: Tags must be Tag objects, not dicts, for Pydantic validation to pass
tag_objects = []
# Add evaluation tag
tag_objects.append(Tag(key=_TAG_SAGEMAKER_MODEL_EVALUATION, value="true"))
# Process any additional tags passed in
if tags:
for i, tag_item in enumerate(tags):
try:
if hasattr(tag_item, '__class__') and 'Tag' in tag_item.__class__.__name__:
# Already a Tag object
tag_objects.append(tag_item)
elif isinstance(tag_item, dict):
# Convert dict to Tag object - handle both lowercase and capitalized keys
key = tag_item.get("key") or tag_item.get("Key")
value = tag_item.get("value") or tag_item.get("Value")
if key and value:
tag_objects.append(Tag(key=str(key), value=str(value)))
else:
logger.warning(f"Skipping invalid tag at index {i}: {tag_item}")
else:
logger.warning(f"Skipping unsupported tag type at index {i}: {type(tag_item)}")
except Exception as e:
logger.warning(f"Error processing tag at index {i}: {e}")
logger.info(f"Creating pipeline with {len(tag_objects)} tags")
pipeline = Pipeline.create(
pipeline_name=pipeline_name,
client_request_token=client_request_token,
role_arn=role_arn,
pipeline_definition=resolved_pipeline_definition,
pipeline_display_name=f"EvaluationPipeline-{eval_type.value}",
pipeline_description=f"Pipeline for {eval_type.value} evaluation jobs",
tags=tag_objects,
session=session,
region=region
)
logger.info(f"Successfully created pipeline: {pipeline_name}")
# Wait for pipeline to be ready before returning
logger.info(f"Waiting for pipeline {pipeline_name} to be ready...")
try:
pipeline.wait_for_status(target_status="Active", poll=5, timeout=300) # Wait up to 5 minutes
logger.info(f"Pipeline {pipeline_name} is now active and ready for execution")
except Exception as e:
logger.warning(f"Failed to wait for pipeline status: {e}. Pipeline may still be initializing...")
return pipeline
def _clean_unassigned_value(value: Any) -> Any:
"""Clean Unassigned object by converting to None.
Args:
value (Any): Value that may be an Unassigned object.
Returns:
Any: None if value is Unassigned, otherwise returns the value unchanged.
"""
if value is not None and hasattr(value, '__class__'):
if 'Unassigned' in value.__class__.__name__:
return None
return value
def _clean_unassigned_from_dict(data: Dict[str, Any]) -> Dict[str, Any]:
"""Clean Unassigned objects from nested dict before pydantic validation.
Args:
data (Dict[str, Any]): Dictionary that may contain Unassigned objects.
Returns:
Dict[str, Any]: Cleaned dictionary with Unassigned objects replaced with None.
"""
if data.get('status', {}).get('failure_reason') is not None:
data['status']['failure_reason'] = _clean_unassigned_value(data['status']['failure_reason'])
return data
def _extract_eval_type_from_arn(arn: str) -> Optional[EvalType]:
"""Helper method to extract evaluation type from pipeline or execution ARN.
Extracts eval type from new naming pattern: SagemakerEvaluation-[EvalType]-[uuid]
Args:
arn (str): Pipeline ARN or Pipeline Execution ARN.
Pipeline ARN format: arn:aws:sagemaker:region:account:pipeline/pipeline-name
Execution ARN format: arn:aws:sagemaker:region:account:pipeline/pipeline-name/execution/execution-id
Returns:
Optional[EvalType]: EvalType if found, None otherwise.
"""
try:
# Split ARN and extract pipeline name
arn_parts = arn.split('/')
if len(arn_parts) >= 2:
# For execution ARN, pipeline name is at index -3
# For pipeline ARN, pipeline name is at index -1
pipeline_name = arn_parts[-3] if len(arn_parts) >= 4 else arn_parts[-1]
# Check pattern: SagemakerEvaluation-{EvalType}-{uuid}
for eval_type in EvalType:
prefix = _get_pipeline_name_prefix(eval_type)
if pipeline_name.startswith(prefix):
logger.debug(f"Extracted eval_type: {eval_type.value} from ARN: {arn}")
return eval_type
logger.warning(f"Could not extract eval_type from ARN: {arn}")
return None
except Exception as e:
logger.warning(f"Error extracting eval_type from ARN {arn}: {str(e)}")
return None
def _get_or_create_pipeline(
eval_type: EvalType,
pipeline_definition: str,
role_arn: str,
session: Optional[Session] = None,
region: Optional[str] = None,
create_tags: Optional[List[TagsDict]] = [],
) -> Pipeline:
"""Get existing pipeline or create/update it.
Searches for existing pipeline using Pipeline.get_all with pipeline_name_prefix.
Validates tag using Tag.get_all and updates if found. Otherwise creates new pipeline with UUID.
Re-renders pipeline_definition with actual pipeline_name before create/update.
Args:
eval_type: Type of evaluation
pipeline_definition: JSON pipeline definition (Jinja2 template)
role_arn: IAM role ARN for pipeline execution
session: Boto3 session (optional)
region: AWS region (optional)
create_tags (Optional[List[TagsDict]]): List of tags to include in pipeline
Returns:
Pipeline instance (existing updated or newly created)
Raises:
ClientError: If AWS service call fails
"""
from jinja2 import Template
pipeline_name_prefix = _get_pipeline_name_prefix(eval_type)
try:
# Use Pipeline.get_all with pipeline_name_prefix to find existing pipelines
pipelines = Pipeline.get_all(
pipeline_name_prefix=pipeline_name_prefix,
session=session,
region=region
)
# Check each pipeline for the required tag
for pipeline in pipelines:
pipeline_arn = pipeline.pipeline_arn
# Get tags using ResourceTag.get_all
tags_list = ResourceTag.get_all(resource_arn=pipeline_arn, session=session, region=region)
tags = {tag.key: tag.value for tag in tags_list}
# Validate tag
if tags.get(_TAG_SAGEMAKER_MODEL_EVALUATION) == "true":
pipeline_name = pipeline.pipeline_name
logger.info(f"Found existing pipeline: {pipeline_name}")
# Re-render pipeline definition with actual pipeline_name
template = Template(pipeline_definition)
resolved_pipeline_definition = template.render(pipeline_name=pipeline_name)
# Update pipeline with latest definition
logger.info(f"Updating pipeline {pipeline_name} with latest definition")
pipeline.update(
pipeline_definition=resolved_pipeline_definition,
role_arn=role_arn,
pipeline_description=f"Pipeline for {eval_type.value} evaluation jobs (updated)"
)
logger.info(f"Successfully updated pipeline: {pipeline_name}")
return pipeline
# No matching pipeline found, create new one
logger.info(f"No existing pipeline found with prefix {pipeline_name_prefix}, creating new one")
return _create_evaluation_pipeline(eval_type, role_arn, pipeline_definition, session, region, create_tags)
except ClientError as e:
error_code = e.response['Error']['Code']
if "ResourceNotFound" in error_code:
return _create_evaluation_pipeline(eval_type, role_arn, pipeline_definition, session, region, create_tags)
else:
raise
except Exception as e:
# If search fails for other reasons, try to create
logger.info(f"Error searching for pipeline ({str(e)}), attempting to create new pipeline")
return _create_evaluation_pipeline(eval_type, role_arn, pipeline_definition, session, region, create_tags)
def _start_pipeline_execution(
pipeline_name: str,
name: str,
session: Optional[Session] = None,
region: Optional[str] = None
) -> str:
"""Start pipeline execution using boto3 client.
Extracted for testability - can be mocked independently in tests.
Args:
pipeline_name: Name of the pipeline to execute
name: Base name for the execution
session: Boto3 session (optional)
region: AWS region (optional)
Returns:
ARN of the started pipeline execution
Raises:
ClientError: If AWS service call fails
"""
import os
import boto3
execution_display_name = f"{name}-{int(time.time())}"
endpoint_url = os.environ.get('SAGEMAKER_ENDPOINT')
# Get boto3 client
if session:
sm_client = session.client('sagemaker', region_name=region, endpoint_url=endpoint_url)
else:
sm_client = boto3.client('sagemaker', region_name=region, endpoint_url=endpoint_url)
# Start pipeline execution
logger.info(f"Starting pipeline execution: {execution_display_name}")
response = sm_client.start_pipeline_execution(
PipelineName=pipeline_name,
PipelineExecutionDisplayName=execution_display_name,
PipelineExecutionDescription=f"Evaluation execution: {name}",
PipelineParameters=[], # Empty since all values are pre-substituted
ClientRequestToken=str(uuid.uuid4())
)
execution_arn = response['PipelineExecutionArn']
logger.info(f"Pipeline execution started: {execution_arn}")
return execution_arn
def _create_execution_from_pipeline_execution(
pe: PipelineExecution,
eval_type: EvalType
) -> 'EvaluationPipelineExecution':
"""Create EvaluationPipelineExecution from PipelineExecution.
Handles failure_reason Unassigned objects and sets basic properties.
Extracted for testability - used by both get() and get_all().
Args:
pe: PipelineExecution object from sagemaker_core
eval_type: Type of evaluation
Returns:
EvaluationPipelineExecution with basic properties set
"""
name = pe.pipeline_execution_arn.split('/')[-1] if pe.pipeline_execution_arn else 'unknown'
# Handle failure_reason which might be an Unassigned object
failure_reason = pe.failure_reason
if failure_reason is not None and hasattr(failure_reason, '__class__'):
if 'Unassigned' in failure_reason.__class__.__name__:
failure_reason = None
execution = EvaluationPipelineExecution(
arn=pe.pipeline_execution_arn,
name=name,
status=PipelineExecutionStatus(
overall_status=pe.pipeline_execution_status or 'Unknown',
failure_reason=failure_reason
),
last_modified_time=pe.last_modified_time,
eval_type=eval_type
)
# Store the internal pipeline execution reference
execution._pipeline_execution = pe
return execution
def _extract_output_s3_location_from_steps(raw_steps: List[Any], session: Optional[Any] = None, region: Optional[str] = None) -> Optional[str]:
"""Helper method to extract S3 output location from training job's OutputDataConfig.
Finds the first evaluation training step (EvaluateCustomModel or EvaluateBaseModel),
gets its training job ARN, and uses boto3 DescribeTrainingJob to retrieve the S3 output path.
Args:
raw_steps: List of PipelineExecutionStep objects from SageMaker
session: Boto3 session (optional)
region: AWS region (optional)
Returns:
S3 output location from OutputDataConfig if found, None otherwise
"""
try:
import boto3
import os
# Get endpoint URL from environment variable (for beta endpoint support)
endpoint_url = os.environ.get('SAGEMAKER_ENDPOINT')
# Get SageMaker client with optional endpoint URL
if session:
sm_client = session.client('sagemaker', region_name=region, endpoint_url=endpoint_url)
else:
sm_client = boto3.client('sagemaker', region_name=region, endpoint_url=endpoint_url)
for step in raw_steps:
step_name = getattr(step, 'step_name', '')
# Look for evaluation training steps (custom or base)
if 'EvaluateCustomModel' in step_name or 'EvaluateBaseModel' in step_name:
metadata = getattr(step, 'metadata', None)
if metadata and hasattr(metadata, 'training_job'):
training_job_meta = metadata.training_job
# Get training job name from ARN
if hasattr(training_job_meta, 'arn'):
training_job_name = training_job_meta.arn.split('/')[-1]
try:
# Use boto3 DescribeTrainingJob (avoids pydantic validation issues)
response = sm_client.describe_training_job(TrainingJobName=training_job_name)
# Get OutputDataConfig.S3OutputPath
if 'OutputDataConfig' in response and 'S3OutputPath' in response['OutputDataConfig']:
s3_output_path = response['OutputDataConfig']['S3OutputPath']
logger.info(f"Extracted s3_output_path from training job {training_job_name}: {s3_output_path}")
return s3_output_path
except ClientError as e:
logger.warning(f"Failed to describe training job {training_job_name}: {e}")
continue
except Exception as e:
logger.warning(f"Error describing training job {training_job_name}: {e}")
continue
logger.debug("Could not extract s3_output_path from pipeline steps")
return None
except Exception as e:
logger.warning(f"Error extracting s3_output_path from steps: {str(e)}")
return None
class StepDetail(BaseModel):
"""Pipeline step details for tracking execution progress.
Represents the status and timing information for a single step
in a SageMaker pipeline execution.
Parameters:
name (str): Name of the pipeline step.
status (str): Status of the step (Completed, Executing, Waiting, Failed).
start_time (Optional[str]): ISO format timestamp when step started.
end_time (Optional[str]): ISO format timestamp when step ended.
display_name (Optional[str]): Human-readable display name for the step.
failure_reason (Optional[str]): Detailed reason if the step failed.
"""
name: str = Field(..., description="Name of the pipeline step")
status: str = Field(..., description="Status of the step (Completed, Executing, Waiting, Failed)")
start_time: Optional[str] = Field(None, description="Step start time")
end_time: Optional[str] = Field(None, description="Step end time")
display_name: Optional[str] = Field(None, description="Display name for the step")
failure_reason: Optional[str] = Field(None, description="Reason for failure if step failed")
job_arn: Optional[str] = Field(None, description="ARN of the underlying job (training, processing, transform, etc.)")
class PipelineExecutionStatus(BaseModel):
"""Combined pipeline execution status with step details and failure reason.
Aggregates the overall execution status along with detailed information
about individual pipeline steps and any failure reasons.
Parameters:
overall_status (str): Overall execution status (Starting, Executing, Completed, Failed, etc.).
step_details (List[StepDetail]): List of individual pipeline step details.
failure_reason (Optional[str]): Detailed reason if the execution failed.
"""
overall_status: str = Field(..., description="Overall execution status (Starting, Running, Completed, Failed, etc.)")
step_details: List[StepDetail] = Field(default_factory=list, description="List of pipeline step details")
failure_reason: Optional[str] = Field(None, description="Reason for failure if execution failed")
class EvaluationPipelineExecution(BaseModel):
"""Manages SageMaker pipeline-based evaluation execution lifecycle.
This class wraps SageMaker Pipeline execution to provide a simplified
interface for running, monitoring, and managing evaluation jobs. Users
typically don't instantiate this class directly, but receive instances
from evaluator classes.
Example:
.. code:: python
from sagemaker.train.evaluate import BenchmarkEvaluator
from sagemaker.train.evaluate.execution import EvaluationPipelineExecution
# Start evaluation through evaluator
evaluator = BenchmarkEvaluator(...)
execution = evaluator.evaluate()
# Monitor execution
print(f"Status: {execution.status.overall_status}")
print(f"Steps: {len(execution.status.step_details)}")
# Wait for completion
execution.wait()
# Display results
execution.show_results()
# Retrieve past executions
all_executions = list(EvaluationPipelineExecution.get_all())
specific_execution = EvaluationPipelineExecution.get(arn="arn:...")
Parameters:
arn (Optional[str]): ARN of the pipeline execution.
name (str): Name of the evaluation execution.
status (PipelineExecutionStatus): Combined status with step details and failure reason.
last_modified_time (Optional[datetime]): Last modification timestamp.
eval_type (Optional[EvalType]): Type of evaluation (BENCHMARK, CUSTOM_SCORER, LLM_AS_JUDGE).
s3_output_path (Optional[str]): S3 location where evaluation results are stored.
steps (List[Dict[str, Any]]): Raw step information from SageMaker.
"""
# Fields set by underlying SageMaker pipeline operations
arn: Optional[str] = Field(None, description="ARN of the pipeline execution")
name: str = Field(..., description="Name of the evaluation execution")
status: PipelineExecutionStatus = Field(default_factory=lambda: PipelineExecutionStatus(overall_status="Unknown"), description="Combined status, step details, and failure reason")
last_modified_time: Optional[datetime] = Field(None, description="Last modification timestamp")
eval_type: Optional[EvalType] = Field(None, description="Evaluation type")
s3_output_path: Optional[str] = Field(None, description="S3 location where evaluation results are stored")
# Additional fields for internal use
steps: List[Dict[str, Any]] = Field(default_factory=list, description="Raw step information from SageMaker")
class Config:
arbitrary_types_allowed = True
def __init__(self, **data):
super().__init__(**data)
self._pipeline_execution: Optional[Any] = None
@classmethod
@_telemetry_emitter(feature=Feature.MODEL_CUSTOMIZATION, func_name="EvaluationPipelineExecution.start")
def start(
cls,
eval_type: EvalType,
name: str,
pipeline_definition: str,
role_arn: str,
s3_output_path: Optional[str] = None,
session: Optional[Session] = None,
region: Optional[str] = None,
tags: Optional[List[TagsDict]] = [],
) -> 'EvaluationPipelineExecution':
"""Create sagemaker pipeline execution. Optionally creates pipeline.
Args:
eval_type (EvalType): Type of evaluation (BENCHMARK, CUSTOM_SCORER, LLM_AS_JUDGE).
name (str): Name for the evaluation execution.
pipeline_definition (str): Complete rendered pipeline definition as JSON string.
role_arn (str): IAM role ARN for pipeline execution.
s3_output_path (Optional[str]): S3 location where evaluation results are stored.
session (Optional[Session]): Boto3 session for API calls.
region (Optional[str]): AWS region for the pipeline.
tags (Optional[List[TagsDict]]): List of tags to include in pipeline
Returns:
EvaluationPipelineExecution: Started pipeline execution instance.
Raises:
ValueError: If pipeline_definition is not valid JSON.
ClientError: If AWS service call fails.
"""
# Validate pipeline_definition is valid JSON
import json
try:
json.loads(pipeline_definition)
except json.JSONDecodeError as e:
raise ValueError(f"Invalid pipeline definition JSON: {e}")
# Create execution instance
execution = cls(
name=name,
eval_type=eval_type,
status=PipelineExecutionStatus(overall_status="Starting"),
s3_output_path=s3_output_path
)
try:
# Get or create pipeline (handles update logic internally)
pipeline = _get_or_create_pipeline(
eval_type=eval_type,
pipeline_definition=pipeline_definition,
role_arn=role_arn,
session=session,
region=region,
create_tags=tags,
)
# Start pipeline execution via boto3
# Use the actual pipeline name from the created/updated pipeline object
pipeline_name = pipeline.pipeline_name
execution.arn = _start_pipeline_execution(
pipeline_name=pipeline_name,
name=name,
session=session,
region=region
)
# Get the pipeline execution object for future operations
execution._pipeline_execution = PipelineExecution.get(
pipeline_execution_arn=execution.arn,
session=session,
region=region
)
# Update execution with initial execution details
execution.status.overall_status = execution._pipeline_execution.pipeline_execution_status or "Executing"
execution.last_modified_time = execution._pipeline_execution.creation_time or datetime.now()
except ClientError as e:
error_code = e.response['Error']['Code']
error_message = e.response['Error']['Message']
logger.error(f"AWS service error when starting pipeline execution: {error_message}")
execution.status.overall_status = "Failed"
execution.status.failure_reason = f"AWS service error: {error_message}"
except Exception as e:
logger.error(f"Unexpected error when starting pipeline execution: {str(e)}")
execution.status.overall_status = "Failed"
execution.status.failure_reason = f"Unexpected error: {str(e)}"
# Convert to appropriate subclass based on eval_type
return execution._convert_to_subclass(eval_type)
@classmethod
@_telemetry_emitter(feature=Feature.MODEL_CUSTOMIZATION, func_name="EvaluationPipelineExecution.get_all")
def get_all(
cls,
eval_type: Optional[EvalType] = None,
session: Optional[Session] = None,
region: Optional[str] = None
):
"""Get all pipeline executions, optionally filtered by evaluation type.
Searches for existing pipelines using prefix and tag validation,
then retrieves executions from those pipelines.
Args:
eval_type (Optional[EvalType]): Evaluation type to filter by (e.g., EvalType.BENCHMARK).
If None, returns executions from all evaluation pipelines.
session (Optional[Session]): Boto3 session. Will be inferred if not provided.
region (Optional[str]): AWS region. Will be inferred if not provided.
Yields:
EvaluationPipelineExecution: Pipeline execution instances.
Example:
.. code:: python
# Get all evaluation executions as iterator
iter = EvaluationPipelineExecution.get_all()
all_executions = list(iter)
# Get only benchmark evaluations
iter = EvaluationPipelineExecution.get_all(eval_type=EvalType.BENCHMARK)
benchmark_executions = list(iter)
"""
try:
# Determine which eval type(s) to search for
eval_types_to_check = [eval_type] if eval_type else list(EvalType)
for et in eval_types_to_check:
pipeline_name_prefix = _get_pipeline_name_prefix(et)
try:
# Search for pipelines with the prefix
pipelines = Pipeline.get_all(
pipeline_name_prefix=pipeline_name_prefix,
session=session,
region=region
)
# Check each pipeline for the required tag and get its executions
for pipeline in pipelines:
try:
pipeline_arn = pipeline.pipeline_arn
# Get tags using ResourceTag.get_all
tags_list = ResourceTag.get_all(resource_arn=pipeline_arn, session=session, region=region)
tags = {tag.key: tag.value for tag in tags_list}
# Validate tag - only process evaluation pipelines
if tags.get(_TAG_SAGEMAKER_MODEL_EVALUATION) != "true":
logger.debug(f"Skipping pipeline {pipeline.pipeline_name} - missing required tag")
continue
pipeline_name = pipeline.pipeline_name
logger.debug(f"Found evaluation pipeline: {pipeline_name}")
# Get all executions for this pipeline
pipeline_executions = PipelineExecution.get_all(
pipeline_name=pipeline_name,
session=session,
region=region
)
# Convert each PipelineExecution to EvaluationPipelineExecution
for pe in pipeline_executions:
# Create execution from pipeline execution
execution = _create_execution_from_pipeline_execution(pe, et)
# Enrich with step details and S3 path
execution._enrich_with_step_details(session, region)
# Convert to appropriate subclass based on eval_type
execution = execution._convert_to_subclass(et)
yield execution
except Exception as e:
logger.warning(f"Error processing pipeline {pipeline.pipeline_name}: {str(e)}")
continue
except ClientError as e:
error_code = e.response['Error']['Code']
# If no pipelines found with prefix, skip to next eval type
if "ResourceNotFound" in error_code or "ValidationException" in error_code:
logger.debug(f"No pipelines found with prefix {pipeline_name_prefix}")
continue
else:
logger.warning(f"Error searching for pipelines with prefix {pipeline_name_prefix}: {e}")
continue
except Exception as e:
logger.warning(f"Error processing eval type {et.value}: {str(e)}")
continue
except Exception as e:
logger.error(f"Unexpected error when listing pipeline executions: {str(e)}")
@classmethod
@_telemetry_emitter(feature=Feature.MODEL_CUSTOMIZATION, func_name="EvaluationPipelineExecution.get")
def get(
cls,
arn: str,
session: Optional[Session] = None,
region: Optional[str] = None
) -> 'EvaluationPipelineExecution':
"""Get a sagemaker pipeline execution instance by ARN.
Args:
arn (str): ARN of the pipeline execution.
session (Optional[Session]): Boto3 session. Will be inferred if not provided.
region (Optional[str]): AWS region. Will be inferred if not provided.
Returns:
EvaluationPipelineExecution: Retrieved pipeline execution instance.
Raises:
ClientError: If AWS service call fails.
Example:
.. code:: python
# Get execution by ARN
arn = "arn:aws:sagemaker:us-west-2:123456789012:pipeline/eval-pipeline/execution/abc123"
execution = EvaluationPipelineExecution.get(arn=arn)
print(execution.status.overall_status)
"""
# Create execution instance with basic info
name = arn.split('/')[-1]
execution = cls(
arn=arn,
name=name,
status=PipelineExecutionStatus(overall_status="Unknown")
)
# Try to determine eval_type from execution ARN early (as fallback for error cases)
execution.eval_type = _extract_eval_type_from_arn(arn)
try:
# Get pipeline execution details and store internally
execution._pipeline_execution = PipelineExecution.get(
pipeline_execution_arn=arn,
session=session,
region=region
)
# Update execution with pipeline execution details
execution.status.overall_status = execution._pipeline_execution.pipeline_execution_status or "Unknown"
execution.status.failure_reason = _clean_unassigned_value(execution._pipeline_execution.failure_reason)
execution.last_modified_time = execution._pipeline_execution.last_modified_time
# Enrich with step details and S3 path
execution._enrich_with_step_details(session, region)
# Determine eval_type from pipeline ARN (preferred method)
pipeline_arn = execution._pipeline_execution.pipeline_arn if execution._pipeline_execution else None
determined_eval_type = execution._determine_eval_type(pipeline_arn)
if determined_eval_type:
execution.eval_type = determined_eval_type
except ClientError as e:
error_code = e.response['Error']['Code']
error_message = e.response['Error']['Message']
logger.error(f"AWS service error when getting pipeline execution: {error_message}")
execution.status.overall_status = "Error"
execution.status.failure_reason = f"AWS service error: {error_code}:{error_message}"
# eval_type already set from execution ARN fallback above
except Exception as e:
logger.error(f"Unexpected error when getting pipeline execution details: {str(e)}")
execution.status.overall_status = "Error"
execution.status.failure_reason = f"Unexpected error: {str(e)}"
# eval_type already set from execution ARN fallback above
# Convert to appropriate subclass based on eval_type
return execution._convert_to_subclass(execution.eval_type)
@_telemetry_emitter(feature=Feature.MODEL_CUSTOMIZATION, func_name="EvaluationPipelineExecution.refresh")
def refresh(self) -> None:
"""Describe a pipeline execution and update job status"""
if not self._pipeline_execution:
return
try:
# Refresh the pipeline execution instance
self._pipeline_execution.refresh()
# Update status from refreshed pipeline execution
self.status.overall_status = self._pipeline_execution.pipeline_execution_status or "Unknown"
self.status.failure_reason = _clean_unassigned_value(self._pipeline_execution.failure_reason)
self.last_modified_time = self._pipeline_execution.last_modified_time
# Get updated pipeline execution steps with proper session/region handling
steps_iterator = self._pipeline_execution.get_all_steps()
raw_steps = list(steps_iterator)
self._update_step_details_from_raw_steps(raw_steps)
except ClientError as e:
error_code = e.response['Error']['Code']
error_message = e.response['Error']['Message']
logger.error(f"AWS service error when refreshing pipeline execution: {error_message}")
except Exception as e:
logger.error(f"Unexpected error when refreshing pipeline execution: {str(e)}")
@_telemetry_emitter(feature=Feature.MODEL_CUSTOMIZATION, func_name="EvaluationPipelineExecution.stop")
def stop(self) -> None:
"""Stop a pipeline execution"""
if not self.arn:
return
try:
# TODO: Move to sagemaker_core PipelineExecution.stop() when session handling is fixed
# For now, use boto3 directly to stop the pipeline execution
import os
import boto3
endpoint_url = os.environ.get('SAGEMAKER_ENDPOINT')
# Get boto3 client - extract from pipeline execution if available
if self._pipeline_execution and hasattr(self._pipeline_execution, '_session'):
session = self._pipeline_execution._session
if hasattr(session, 'boto_session'):
sm_client = session.boto_session.client('sagemaker', endpoint_url=endpoint_url)
else:
sm_client = session.client('sagemaker', endpoint_url=endpoint_url)
else:
# Fallback to default boto3 client
sm_client = boto3.client('sagemaker', endpoint_url=endpoint_url)
# Stop the pipeline execution using boto3
sm_client.stop_pipeline_execution(
PipelineExecutionArn=self.arn
)
# Update status
self.status.overall_status = "Stopping"
logger.info(f"Stopping pipeline execution: {self.arn}")
# Refresh to get updated status
self.refresh()
except ClientError as e:
error_code = e.response['Error']['Code']
error_message = e.response['Error']['Message']
logger.error(f"AWS service error when stopping pipeline execution: {error_message}")
except Exception as e:
logger.error(f"Unexpected error when stopping pipeline execution: {str(e)}")
@_telemetry_emitter(feature=Feature.MODEL_CUSTOMIZATION, func_name="EvaluationPipelineExecution.wait")
def wait(
self,
target_status: Literal["Executing", "Stopping", "Stopped", "Failed", "Succeeded"] = "Succeeded",
poll: int = 5,
timeout: Optional[int] = None
) -> None:
"""Wait for a pipeline execution to reach certain status.
This method provides a hybrid implementation that works in both Jupyter notebooks
and terminal environments, with appropriate visual feedback for each.
Args:
target_status: The status to wait for
poll: The number of seconds to wait between each poll
timeout: The maximum number of seconds to wait before timing out
"""
if not self._pipeline_execution:
return
start_time = time.time()
# Detect if running in Jupyter
is_jupyter = False
try:
from IPython import get_ipython
ipython = get_ipython()
if ipython is not None and 'IPKernelApp' in ipython.config:
is_jupyter = True
from IPython.display import display, HTML, clear_output
except Exception:
pass
if is_jupyter:
# Jupyter notebook experience with rich library
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.text import Text
from rich.layout import Layout
from rich.console import Group
# Create console with Jupyter support
console = Console(force_jupyter=True)
while True:
clear_output(wait=True)
self.refresh()
current_status = self.status.overall_status
elapsed = time.time() - start_time
# Create header table with pipeline name link
header_table = Table(show_header=False, box=None, padding=(0, 1))
header_table.add_column("Property", style="cyan bold", width=20)
header_table.add_column("Value", style="dim", overflow="fold")
# Extract pipeline name and exec_id from execution ARN
pipeline_name = None
exec_id = ''
if self.arn:
arn_parts = self.arn.split('/')
if len(arn_parts) >= 4:
pipeline_name = arn_parts[-3]
exec_id = arn_parts[-1]
# Use execution display name if available, fall back to self.name
display_name = self.name
if self._pipeline_execution:
dn = getattr(self._pipeline_execution, 'pipeline_execution_display_name', None)
if dn and not (hasattr(dn, '__class__') and 'Unassigned' in dn.__class__.__name__):
display_name = dn
header_table.add_row("Evaluation Job", str(display_name))
# Build links row
links = []
try:
from sagemaker.core.utils.utils import SageMakerClient
from sagemaker.train.common_utils.metrics_visualizer import _is_in_studio, _get_studio_base_url
if pipeline_name and _is_in_studio():
region = SageMakerClient().region_name
base = _get_studio_base_url(region)
if base:
pipeline_url = f"{base}/jobs/evaluation/detail?pipeline_name={pipeline_name}&execution_id={exec_id}"
links.append(f"[bright_blue underline][link={pipeline_url}]🔗 Pipeline Execution (Studio)[/link][/bright_blue underline]")
except Exception:
pass
if links:
header_table.add_row("Links", " | ".join(links))
# Create main status table
status_table = Table(show_header=False, box=None, padding=(0, 1))
status_table.add_column("Property", style="cyan bold", width=20)
status_table.add_column("Value", style="dim")
status_table.add_row("Overall Status", f"[bold][orange3]{current_status}[/][/]")
status_table.add_row("Target Status", f"[bold yellow]{target_status}[/bold yellow]")
status_table.add_row("Elapsed Time", f"[bold bright_red]{elapsed:.1f}s[/bold bright_red]")
if self.status.failure_reason:
status_table.add_row("Failure Reason", f"[red]{self.status.failure_reason}[/red]")
# Create steps table if steps exist
if self.status.step_details:
has_failures = any(step.failure_reason for step in self.status.step_details)
steps_table = Table(show_header=True, header_style="bold magenta", box=None, padding=(0, 1))
steps_table.add_column("Step Name", style="cyan", width=30)
steps_table.add_column("Status", style="yellow", width=15)
steps_table.add_column("Duration", style="green", width=12)
failed_steps = []
job_arn_entries = []
for step in self.status.step_details:
duration = ""
if step.start_time and step.end_time:
try:
from datetime import datetime
start = datetime.fromisoformat(step.start_time.replace('Z', '+00:00'))
end = datetime.fromisoformat(step.end_time.replace('Z', '+00:00'))
duration_seconds = (end - start).total_seconds()
duration = f"{duration_seconds:.1f}s"
except Exception:
duration = "N/A"