Setting the file. One moment. Optimize Recommendation · AWS AI ML · aws/agent-toolkit-for-aws · Skills Docs70
Creating Amazon Aurora Db Cluster With Instances
93
Routing Traffic With Route53 And CloudFront
Resilience Program Design
Creating API Gateway Stage
(opens in a new tab)
references/model-deployment/code_templates/optimize-recommendation.py
Python·144 lines·6 KB
16
from
sagemaker.core
import
Attribution, set_attribution
17from sagemaker.serve import ModelBuilder
18from sagemaker.serve.ai_inference_recommender import Workload
19
20set_attribution(Attribution.SAGEMAKER_AGENT_PLUGIN)
21
22MODEL_S3_URI = "[MODEL_S3_URI]"
23ROLE_ARN = "[ROLE_ARN]"
24S3_OUTPUT_LOCATION = "[S3_OUTPUT_LOCATION]"
25RECOMMENDATION_JOB_NAME = "[RECOMMENDATION_JOB_NAME]"
26WORKLOAD_CONFIG_NAME = "[WORKLOAD_CONFIG_NAME]"
27PERFORMANCE_TARGET = "[PERFORMANCE_METRIC]" # "cost", "ttft-ms", or "throughput"
28TOKENIZER = "[TOKENIZER]"
29
30# Cell 3: Define the Workload
31
32workload = Workload.synthetic(
33 tokenizer=TOKENIZER,
34 prompt_input_tokens_mean=[INPUT_TOKENS_MEAN],
35 prompt_input_tokens_stddev=[INPUT_TOKENS_STDDEV],
36 output_tokens_mean=[OUTPUT_TOKENS_MEAN],
37 output_tokens_stddev=[OUTPUT_TOKENS_STDDEV],
38 concurrency=[CONCURRENCY],
39 request_count=[REQUEST_COUNT],
40)
41# For throughput + optimization, a dataset is required. Build the workload from
42# a dataset instead of synthetic prompts. Inspect the data to detect its schema;
43# custom_dataset_type is an OPTIONAL hint naming that schema ("openai-chat",
44# "openai-completions", "sharegpt", "sagemaker-datacapture") — omit it to let
45# AIPerf auto-detect. If the format is unsupported, convert it first with the
46# dataset-transformation skill.
47# workload = Workload.from_dataset("[DATASET_S3_URI]", tokenizer=TOKENIZER,
48# custom_dataset_type="openai-chat", # optional; from the schema you detected
49# prompt_input_tokens_mean=[INPUT_TOKENS_MEAN],
50# concurrency=[CONCURRENCY], request_count=[REQUEST_COUNT])
51
52# Cell 4: Run the Recommendation Job
53
54# Model source A — your own HuggingFace-format weights in S3 (the default path):
55model_builder = ModelBuilder(model_path=MODEL_S3_URI, role_arn=ROLE_ARN)
56
57# Model source B — a SageMaker JumpStart base model (no S3 copy of your own).
58# build() resolves the JumpStart artifacts to their cache S3 URI, which the
59# recommendation job reads. Works for UNGATED JumpStart models; a GATED model
60# resolves to a private cache your role can't read and the job fails with an
61# "Access denied" / "Invalid ModelSource.S3.S3Uri" error — in that case stage
62# the weights to your own S3 (see references/optimization/huggingface-to-s3.md)
63# and use source A instead. Use this INSTEAD of the line above:
64# from sagemaker.core.jumpstart.configs import JumpStartConfig
65# from sagemaker.core.training.configs import Compute
66# model_builder = ModelBuilder.from_jumpstart_config(
67# jumpstart_config=JumpStartConfig(model_id="[JUMPSTART_MODEL_ID]", model_version="*"),
68# compute=Compute(instance_type="[INSTANCE_TYPE]", instance_count=1),
69# role_arn=ROLE_ARN,
70# )
71# model_builder.build() # required: resolves the JumpStart model's S3 artifacts
72
73job = model_builder.generate_deployment_recommendations(
74 workload=workload,
75 performance_target=PERFORMANCE_TARGET,
76 output_path=S3_OUTPUT_LOCATION,
77 job_name=RECOMMENDATION_JOB_NAME,
78 workload_config_name=WORKLOAD_CONFIG_NAME,
79 # instance_types=["ml.g6.12xlarge"], # optional: up to 3 candidates (latency/throughput only)
80 # advanced_optimization=False, # optional: default True (kernel tuning, speculative decoding)
81 # framework="VLLM", # optional: "VLLM" or "LMI"; default auto-selected
82 wait=True,
83)
84print(f"Recommendation job {job.get_name()} finished: {job.ai_recommendation_job_status}")
85
86# Cell 5: Review Recommendations
87
88recommendations = model_builder.recommendations
89print(recommendations)
90
91# Cell 6: Deploy Top Recommendation
92
93# Only include this cell if the user wants to deploy after reviewing results.
94# Deploys the top-ranked recommendation (index 0). Pass recommendation_index=N
95# to deploy a different row, or recommendation_spec_name="..." to pick by name.
96#
97# A recommendation's ModelPackage is created unapproved, so deploy() would raise
98# unless the package is approved first. auto_approve=True approves it in place as
99# part of this deploy. This bypasses manual-approval governance on the package's
100# model package group — appropriate here because the user is deploying their own
101# recommendation. Remove auto_approve and approve the ModelPackage through your
102# normal process if that governance must be preserved.
103ENDPOINT_NAME = "[ENDPOINT_NAME]"
104endpoint = model_builder.deploy(
105 endpoint_name=ENDPOINT_NAME,
106 recommendation_index=0,
107 role=ROLE_ARN,
108 auto_approve=True,
109 wait=True,
110)
111print(f"Endpoint {endpoint.endpoint_name} status: {endpoint.endpoint_status}")
112
113# Deploy from a recommendation job run in a different session (no in-memory
114# model_builder — reconstruct it from the job name) — use INSTEAD of the block
115# above when the recommendation job was run elsewhere (another session or a
116# teammate):
117# model_builder = ModelBuilder.from_recommendation_job("[RECOMMENDATION_JOB_NAME]")
118# endpoint = model_builder.deploy(
119# endpoint_name="[ENDPOINT_NAME]",
120# recommendation_index=0,
121# role=ROLE_ARN,
122# auto_approve=True,
123# wait=True,
124# )
125# print(f"Endpoint {endpoint.endpoint_name} status: {endpoint.endpoint_status}")
126
127# Cell 7: Save Manifest
128# Save manifest - record output of workflow step for future reference
129from pathlib import Path
130manifest_dir = Path("[PROJECT_DIR]") / "manifests"
131manifest_dir.mkdir(parents=True, exist_ok=True)
132manifest_path = manifest_dir / f"recommendation-{RECOMMENDATION_JOB_NAME}.json"
133# Record a model-source-appropriate identifier: MODEL_S3_URI for source A (S3 weights),
134# or the JumpStart model id for source B (uncomment the appropriate line below).
135manifest_path.write_text(json.dumps({
136 "recommendation_job_name": RECOMMENDATION_JOB_NAME,
137 "model_source": {"type": "s3", "model_s3_uri": MODEL_S3_URI},
138 # For a JumpStart-sourced run, use this instead of the line above:
139 # "model_source": {"type": "jumpstart", "model_id": "[JUMPSTART_MODEL_ID]"},
140 "workload_config_name": WORKLOAD_CONFIG_NAME,
141 "performance_target": PERFORMANCE_TARGET,
142 "status": job.ai_recommendation_job_status,
143}, indent=2))
144print(f"Manifest saved: {manifest_path}")