Guide · AWS SageMaker · Batch Transform · Offline Inference · MCP Tools
SageMaker Batch Transform from MCP Server Tools
SageMaker Batch Transform runs inference on a large dataset stored in S3 without requiring a persistent endpoint — it spins up compute, processes all the input files, writes predictions to S3, and terminates the instances when done. The key operational difference from real-time inference is cost: Batch Transform charges only for the duration of the job, making it cheaper than keeping an endpoint alive for infrequent large-batch workloads. The two most important parameters are SplitType (how SageMaker breaks large input files into individual records for the model container) and BatchStrategy (whether the container processes one record at a time or multiple records per request). Getting this combination wrong is the most common failure mode: a JSON input file treated as one giant record instead of one-record-per-line. Beyond splitting, DataProcessing lets you join the original input data to the predictions output — so the output file contains both features and the model's score, not just the score. For training the model that powers the transform job see SageMaker Training Jobs; for versioning it before deployment see SageMaker Model Registry; for real-time inference on the same model see SageMaker Endpoints.
TL;DR
Create a SageMaker Model from training job artifacts first (sagemaker.create_model). Then call sagemaker.create_transform_job. Set SplitType: "Line" for newline-delimited JSON/CSV. Poll sagemaker.describe_transform_job(TransformJobName=name)["TransformJobStatus"] — terminal states are Completed, Failed, Stopped. Output files appear in TransformOutput.S3OutputPath with an .out suffix appended to each input filename.
- SageMaker Training Jobs — train the model that powers the transform job
- SageMaker Model Registry — version and approve models before batch scoring
- SageMaker Processing Jobs — post-processing transform output with custom logic
- SageMaker Endpoints — real-time inference on the same model
- SageMaker Async Inference — single-request async inference with S3 output
Prerequisite — create a SageMaker Model first
Unlike training jobs which use TrainingImage directly, Batch Transform requires a SageMaker Model object created from training job artifacts. The Model combines a container image URI and an S3 path to model artifacts:
import boto3
sagemaker = boto3.client("sagemaker", region_name="us-east-1")
ROLE_ARN = "arn:aws:iam::123456789012:role/SageMakerExecutionRole"
IMAGE_URI = "683313688378.dkr.ecr.us-east-1.amazonaws.com/sagemaker-xgboost:1.7-1"
def create_model_from_training_job(
model_name: str,
training_job_name: str,
) -> str:
"""
Create a SageMaker Model from a completed training job's artifacts.
Returns the ModelName.
"""
# Get model artifacts URI from the completed training job
training_desc = sagemaker.describe_training_job(
TrainingJobName=training_job_name
)
model_data_url = training_desc["ModelArtifacts"]["S3ModelArtifacts"]
sagemaker.create_model(
ModelName=model_name,
PrimaryContainer={
"Image": IMAGE_URI,
"ModelDataUrl": model_data_url,
"Environment": {
"SAGEMAKER_CONTAINER_LOG_LEVEL": "20",
"SAGEMAKER_PROGRAM": "inference.py", # for custom inference code
},
},
ExecutionRoleArn=ROLE_ARN,
Tags=[{"Key": "source-training-job", "Value": training_job_name}],
)
return model_name
def create_model_from_artifacts(
model_name: str,
model_artifacts_s3_uri: str,
) -> str:
"""Create a SageMaker Model from an explicit S3 URI (e.g., model.tar.gz)."""
sagemaker.create_model(
ModelName=model_name,
PrimaryContainer={
"Image": IMAGE_URI,
"ModelDataUrl": model_artifacts_s3_uri,
},
ExecutionRoleArn=ROLE_ARN,
)
return model_name
ModelDataUrl must be the S3 URI of a model.tar.gz file — the compressed archive of model artifacts. SageMaker downloads and extracts this archive into /opt/ml/model/ inside the container before serving. For XGBoost and other built-in algorithms, the training job produces this archive automatically in OutputDataConfig.S3OutputPath.
Model names must be unique per account+region. If you're creating models from multiple training job runs, include the training job name or a version identifier in the model name: f"xgboost-churn-{training_job_name}".
CreateTransformJob — full parameter anatomy
A complete batch transform job call with the most important parameters explained:
BUCKET = "my-ml-bucket"
def launch_batch_transform_job(
job_name: str,
model_name: str,
input_s3_uri: str,
output_s3_prefix: str,
) -> dict:
"""
MCP tool handler: score a large dataset with a trained model.
Input: newline-delimited JSON file(s) in S3.
Output: predictions written to S3 with .out suffix.
"""
response = sagemaker.create_transform_job(
TransformJobName=job_name,
ModelName=model_name,
# Input configuration
TransformInput={
"DataSource": {
"S3DataSource": {
"S3DataType": "S3Prefix",
"S3Uri": input_s3_uri,
}
},
"ContentType": "application/jsonlines",
"CompressionType": "None", # or "Gzip"
# SplitType controls how input files are broken into records:
# "None" — entire file is one record (use for small files only)
# "Line" — split on newlines (for CSV and JSON Lines)
# "RecordIO" — RecordIO-encoded records (for some built-in algorithms)
# "TFRecord" — TensorFlow TFRecord format
"SplitType": "Line",
},
# Output configuration
TransformOutput={
"S3OutputPath": output_s3_prefix,
"Accept": "application/jsonlines",
"AssembleWith": "Line", # join output records with newlines
# "KmsKeyId": "arn:aws:kms:..." for encrypted output
},
# Compute resources
TransformResources={
"InstanceType": "ml.m5.xlarge",
"InstanceCount": 1,
},
# How many records to send per container request:
# "SingleRecord" — one record per request (safest, lowest throughput)
# "MultiRecord" — pack as many records as MaxPayloadInMB allows
BatchStrategy="MultiRecord",
# Max payload size per container request (MB, default 6)
MaxPayloadInMB=6,
# How many concurrent requests to send to the container
MaxConcurrentTransforms=4,
# Wall-clock timeout
ModelClientConfig={
"InvocationsTimeoutInSeconds": 600,
"InvocationsMaxRetries": 3,
},
Tags=[{"Key": "mcp-tool", "Value": "batch-score"}],
)
return {
"transform_job_arn": response["TransformJobArn"],
"job_name": job_name,
"output_s3_prefix": output_s3_prefix,
}
BatchStrategy: "MultiRecord" with SplitType: "Line" is the highest-throughput combination for JSON Lines and CSV inputs: SageMaker packs as many newline-delimited records into each container request as fit within MaxPayloadInMB, then sends requests concurrently up to MaxConcurrentTransforms. For models that do not support batch input (the container returns one prediction per request), use BatchStrategy: "SingleRecord" — this sends one record per request and assembles the responses in order.
MaxPayloadInMB defaults to 6 MB. For models with large inputs (e.g., image embeddings or long text sequences), you may need to increase this. The maximum value is 100 MB. If a single record exceeds MaxPayloadInMB, the job fails with a ClientError.
Polling transform job status
import time
TERMINAL_TRANSFORM_STATES = {"Completed", "Failed", "Stopped"}
def wait_for_transform_job(job_name: str, poll_interval: int = 30) -> dict:
"""
Poll DescribeTransformJob until a terminal state is reached.
Returns the final job description.
"""
while True:
desc = sagemaker.describe_transform_job(TransformJobName=job_name)
status = desc["TransformJobStatus"]
if status in TERMINAL_TRANSFORM_STATES:
if status == "Failed":
raise RuntimeError(
f"Transform job {job_name} failed: "
f"{desc.get('FailureReason', 'unknown reason')}"
)
return desc
time.sleep(poll_interval)
def get_transform_output_prefix(job_name: str) -> str:
"""Return the S3 output prefix after a completed transform job."""
desc = sagemaker.describe_transform_job(TransformJobName=job_name)
if desc["TransformJobStatus"] != "Completed":
raise ValueError(f"Job {job_name} is not Completed")
return desc["TransformOutput"]["S3OutputPath"]
def list_transform_output_files(output_prefix: str) -> list[str]:
"""
List output files in the transform output prefix.
Each input file produces one output file with '.out' appended to the name.
"""
s3 = boto3.client("s3")
bucket, prefix = output_prefix.replace("s3://", "").split("/", 1)
response = s3.list_objects_v2(Bucket=bucket, Prefix=prefix)
return [
f"s3://{bucket}/{obj['Key']}"
for obj in response.get("Contents", [])
if obj["Key"].endswith(".out")
]
Output file naming is deterministic: for each input file at key s3://bucket/input/data.jsonl, the output file is s3://output-prefix/data.jsonl.out. The .out suffix is always appended to the full filename including any existing extension. This makes it straightforward to map input to output files programmatically by appending .out.
If the input is an S3 prefix containing multiple files, each file produces a corresponding .out file in the output prefix, maintaining the relative key structure. For example, s3://bucket/input/2024/01/data.csv with output prefix s3://bucket/output/ produces s3://bucket/output/data.csv.out — note that only the filename (not the intermediate path segments) is preserved in the output.
DataProcessing — join input data to predictions
The DataProcessing parameter lets you use JMESPath expressions to filter the input sent to the model and join the original input data to the prediction output — producing an output file that contains both features and scores:
# Input JSON Lines file — each line is one record:
# {"id": "user-123", "features": [1.2, 0.5, 3.1], "label": 1}
# {"id": "user-456", "features": [0.8, 2.1, 1.9], "label": 0}
# Without DataProcessing:
# Model receives full record including "id" and "label" fields.
# Output: just the prediction score (e.g., {"predicted_label": 1, "score": 0.92})
# With DataProcessing:
# - InputFilter: send only "features" field to the model
# - JoinSource + OutputFilter: join input to output for context
sagemaker.create_transform_job(
TransformJobName=job_name,
ModelName=model_name,
TransformInput={
"DataSource": {
"S3DataSource": {
"S3DataType": "S3Prefix",
"S3Uri": f"s3://{BUCKET}/input/",
}
},
"ContentType": "application/json",
"SplitType": "Line",
},
TransformOutput={
"S3OutputPath": f"s3://{BUCKET}/output/",
"Accept": "application/json",
"AssembleWith": "Line",
},
TransformResources={
"InstanceType": "ml.m5.large",
"InstanceCount": 1,
},
# DataProcessing controls input filtering and output joining
DataProcessing={
# JMESPath expression: what to send to the model container
# "$" = send entire record (default)
# "$.features" = send only the "features" array
"InputFilter": "$.features",
# JoinSource: merge original input into output for context
# "Input" = merge original record with model output
# "None" = don't merge (output is model response only)
"JoinSource": "Input",
# JMESPath expression on the MERGED record: what to include in output
# After joining, the merged record is:
# {"id": "user-123", "features": [...], "label": 1, "SageMakerOutput": {"predicted_label": 1, "score": 0.92}}
# OutputFilter selects which fields to keep:
"OutputFilter": "$[['id', 'label', 'SageMakerOutput']]",
# Resulting output line:
# {"id": "user-123", "label": 1, "SageMakerOutput": {"predicted_label": 1, "score": 0.92}}
},
)
# Example: keep only the original ID and the prediction score
# "OutputFilter": "$[['id', 'SageMakerOutput.score']]"
# For CSV inputs, use column index syntax:
# "InputFilter": "$[1:]" — send all columns except the first (ID column)
# "OutputFilter": "$[0, -1]" — keep first column and last column (prediction)
InputFilter reduces what gets sent to the model, which matters if your input records contain fields the model doesn't use (like IDs, timestamps, or ground truth labels) — sending unnecessary fields wastes bandwidth and can confuse models that expect exact feature counts. JoinSource: "Input" merges the original record into the output so you can correlate predictions back to the original IDs without a separate join step.
JMESPath syntax in InputFilter and OutputFilter supports field access ($.features), array slicing ($[1:]), and multi-field selection ($[['id', 'score']]). For CSV inputs, use numeric column indices ($[2:5] for columns 2–4). The special key SageMakerOutput refers to the model container's response after joining — this is how you reference the prediction values in OutputFilter.
Handling large datasets with multiple input files
def launch_batch_transform_multi_instance(
job_name: str,
model_name: str,
input_prefix: str,
output_prefix: str,
file_count: int,
) -> dict:
"""
Score thousands of files in parallel using multiple transform instances.
Each instance processes a subset of files concurrently.
"""
# Rule of thumb: use roughly 1 instance per 10 GB of input data
# For very large jobs, test with 1 instance first to validate correctness,
# then scale up for throughput.
instance_count = max(1, min(100, file_count // 100))
response = sagemaker.create_transform_job(
TransformJobName=job_name,
ModelName=model_name,
TransformInput={
"DataSource": {
"S3DataSource": {
"S3DataType": "S3Prefix",
"S3Uri": input_prefix,
}
},
"ContentType": "text/csv",
"SplitType": "Line",
},
TransformOutput={
"S3OutputPath": output_prefix,
"Accept": "text/csv",
"AssembleWith": "Line",
},
TransformResources={
"InstanceType": "ml.c5.4xlarge",
"InstanceCount": instance_count,
},
BatchStrategy="MultiRecord",
MaxPayloadInMB=6,
MaxConcurrentTransforms=10, # concurrent container requests per instance
)
return {
"transform_job_arn": response["TransformJobArn"],
"instance_count": instance_count,
}
def stop_transform_job(job_name: str) -> bool:
"""Stop a running transform job."""
desc = sagemaker.describe_transform_job(TransformJobName=job_name)
if desc["TransformJobStatus"] not in {"InProgress", "Stopping"}:
return False
sagemaker.stop_transform_job(TransformJobName=job_name)
return True
When InstanceCount > 1, SageMaker distributes input files across instances — each instance processes a subset of files and writes its output files to the same S3OutputPath prefix. Files are distributed at the file level, not the record level, so records within a single file always go to the same instance. For balanced distribution, pre-split very large files into smaller ones (100 MB to 1 GB each) before the transform job.
Increasing MaxConcurrentTransforms raises the number of concurrent requests sent to the model container on each instance. For CPU-bound containers, set this to the number of CPU cores on the instance type (ml.c5.4xlarge has 16 vCPUs; MaxConcurrentTransforms=16 saturates it). For GPU containers, set it to 1–4 depending on how well the model batches requests internally.
Batch transform vs real-time endpoints vs async inference
Three SageMaker patterns serve different throughput and latency requirements:
# Use Batch Transform when:
# - You have a large dataset (thousands to billions of records) in S3
# - You don't need predictions immediately (latency of minutes to hours is OK)
# - You want to minimize cost (no idle endpoint costs between runs)
# - You can tolerate per-job startup overhead (~2–5 minutes for instance provisioning)
# Use Real-Time Endpoints when:
# - An MCP tool needs a prediction within milliseconds of a user request
# - Request rate is high enough to justify a persistent endpoint
# - You need sub-second latency
# Use Async Inference when:
# - Single large requests that take 1–15 minutes (e.g., long document, video)
# - You want an endpoint that can scale to zero between requests
# - You need S3-based output but for individual requests, not bulk files
# Cost comparison (approximate, us-east-1, ml.m5.xlarge):
# Real-time endpoint: ~$0.20/hour × 24h = $4.80/day (always on)
# Batch Transform: ~$0.20/hour × 2h (job duration) = $0.40/run
# Async Inference: ~$0.20/hour × (active processing time only), scales to zero
# Decision: if you run less than 2 inferences/hour, batch or async is cheaper.
def choose_inference_pattern(
requests_per_hour: float,
max_acceptable_latency_seconds: float,
) -> str:
if max_acceptable_latency_seconds < 10:
return "real_time_endpoint"
elif max_acceptable_latency_seconds < 900:
return "async_inference"
else:
if requests_per_hour > 100:
return "real_time_endpoint"
return "batch_transform"
Key gotchas
- A SageMaker Model must exist before CreateTransformJob — training job name alone is not enough. You cannot pass a training job name directly to a transform job. You must first call
create_modelwith the training job's model artifact S3 URI. Skipping this step producesValidationException: Model "my-training-job" does not exist. - SplitType "None" sends the entire file as one record. For a 100 MB CSV file, this sends a 100 MB payload to the container in a single request, almost always causing a container timeout or memory error. Use
SplitType: "Line"for newline-delimited formats (CSV, JSON Lines). The default is"None"— always set this explicitly. - BatchStrategy "MultiRecord" requires the container to handle batch input. For custom inference code, the container must accept a payload containing multiple records (not just one) and return multiple predictions. If your container returns only one prediction per request regardless of input size, use
BatchStrategy: "SingleRecord"— otherwise predictions get truncated to the first record. - Output file naming appends ".out" to the full input filename including path segments. Input key
s3://bucket/input/subdir/data.csvwith output prefixs3://bucket/output/producess3://bucket/output/data.csv.out(the subdir is stripped). But if two input files in different subdirs have the same filename (subdir1/data.csvandsubdir2/data.csv), their outputs collide atdata.csv.out. Ensure input filenames are unique across subdirs, or use a flat prefix structure. - MaxPayloadInMB applies to the total payload sent to the container, not individual records. With
BatchStrategy: "MultiRecord"andSplitType: "Line", SageMaker packs records until the payload reachesMaxPayloadInMB. If a single record exceeds this limit, the job fails withClientError: Exceeded MaxPayloadInMB. IncreaseMaxPayloadInMB(up to 100) or pre-split large records. - Transform jobs do not reuse existing output files. If you rerun a transform job with the same output prefix, it overwrites existing
.outfiles for input files it processes. Use versioned output prefixes to preserve previous job outputs:f"s3://{BUCKET}/output/{job_name}/". - ModelClientConfig.InvocationsTimeoutInSeconds defaults to 600 seconds. For models that process a large MultiRecord batch slowly, the container request can time out before producing output. If your container needs longer per-batch processing, increase this value. The maximum is 3600 seconds.
- Stopping a transform job may leave partial output files. Records processed before the stop command are written to S3; unprocessed input files have no corresponding
.outfile. Partial output files from files that were mid-processing when the stop occurred may also exist. After stopping, verify output completeness by comparing input file count to output file count before consuming results.