Guide · Amazon Bedrock · Model Distillation · Customization Job
Bedrock Model Distillation Customization Job — hyperparameters, epochs, batchSize, IAM role
Amazon Bedrock Model Distillation customization job hyperparameters are passed as Record<string, string> — all values are strings, even numeric ones — and the keys differ from what many ML practitioners expect from PyTorch or Keras. Four hyperparameter pitfalls surface repeatedly: epochCount is a string like "2", not a number — sending 2 (integer) returns a ValidationException: hyperParameters values must be strings; learningRateMultiplier is a multiplier applied to the base's default learning rate, not an absolute rate — a value of "1.0" means "use the default", not "use rate 1.0"; earlyStoppingPatience and earlyStoppingThreshold together control early stopping — both must be set or neither, or the job rejects the combination; and when maxResponseLengthForInference in teacherModelConfig is set too low, the teacher model's completions are truncated before the student sees full training targets, degrading output quality. For training data format see distillation training data; for end-to-end overview see distillation overview.
TL;DR
All hyperparameter values are strings. Start with epochCount: "2", batchSize: "1", learningRateMultiplier: "1.0". Add earlyStoppingThreshold: "0.001" and earlyStoppingPatience: "2" together (never one without the other). Set maxResponseLengthForInference high enough that the teacher's completions aren't truncated — use at least 512 for open-ended tasks, 50 for classification. Poll GetModelCustomizationJobCommand every 60 seconds until status === "Completed".
Hyperparameters reference
The hyperParameters map accepts string values only. Here are all supported keys for distillation jobs with their valid ranges and what they do:
import { CreateModelCustomizationJobCommand } from "@aws-sdk/client-bedrock";
// All hyperParameter values MUST be strings
const hyperParameters: Record<string, string> = {
// Number of full passes over the training dataset
// Range: "1" to "10". Default: "2"
// Higher epochCount = more training time + risk of overfitting
epochCount: "2",
// Training batch size — examples processed together per gradient update
// Range: "1" to "8". Default: "1"
// Larger batch = more stable gradients but needs more memory
batchSize: "1",
// Multiplier on the base model's default learning rate
// Range: "0.1" to "10.0". Default: "1.0"
// 1.0 = use default; < 1.0 = slower learning; > 1.0 = faster learning
learningRateMultiplier: "1.0",
// Minimum loss improvement to count as progress (for early stopping)
// Must be paired with earlyStoppingPatience
// Range: "0.00001" to "0.1". Default: none (early stopping disabled)
earlyStoppingThreshold: "0.001",
// How many epochs with no improvement before stopping
// Must be paired with earlyStoppingThreshold
// Range: "1" to "5". Default: none (early stopping disabled)
earlyStoppingPatience: "2",
};
Setting only earlyStoppingThreshold without earlyStoppingPatience (or vice versa) returns: ValidationException: earlyStoppingThreshold and earlyStoppingPatience must both be set or both omitted. The error message is accurate — treat them as a pair.
Full job creation with all options
A production distillation job call with every configurable field:
import {
BedrockClient,
CreateModelCustomizationJobCommand,
} from "@aws-sdk/client-bedrock";
const bedrockClient = new BedrockClient({ region: "us-east-1" });
const response = await bedrockClient.send(
new CreateModelCustomizationJobCommand({
// --- Identity ---
jobName: "mcp-classifier-distill-2026-11-27",
customModelName: "mcp-classifier-lite-v1",
// --- Distillation type (required) ---
customizationType: "DISTILLATION",
// --- Student base model ---
baseModelIdentifier: "amazon.titan-text-lite-v1:0:4k",
// --- Teacher model config (required for DISTILLATION) ---
teacherModelConfig: {
// Teacher model — the full ARN including region and double-colon
teacherModelIdentifier:
"arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3-sonnet-20240229-v1:0",
// Max tokens the teacher generates per training prompt
// Set this to at least the typical length of a correct answer
// Too low = truncated golden completions = degraded student quality
maxResponseLengthForInference: 256,
},
// --- IAM role ---
roleArn: "arn:aws:iam::123456789012:role/BedrockCustomizationRole",
// --- Training data ---
trainingDataConfig: {
s3Uri: "s3://my-bucket/distill-training/prompts.jsonl",
},
// --- Output model artifacts ---
outputDataConfig: {
s3Uri: "s3://my-bucket/distill-output/mcp-classifier-v1/",
},
// --- Hyperparameters (all values are strings) ---
hyperParameters: {
epochCount: "2",
batchSize: "1",
learningRateMultiplier: "1.0",
earlyStoppingThreshold: "0.001",
earlyStoppingPatience: "2",
},
// --- Optional: validation data for training metrics ---
// validationDataConfig: {
// validators: [{
// s3Uri: "s3://my-bucket/distill-validation/val-prompts.jsonl",
// }],
// },
// --- Optional: custom model KMS encryption ---
// customModelKmsKeyId: "arn:aws:kms:us-east-1:123456789012:key/xxx",
// --- Optional: tags ---
jobTags: [
{ key: "Project", value: "MCPClassifier" },
{ key: "Environment", value: "production" },
],
customModelTags: [
{ key: "Project", value: "MCPClassifier" },
],
})
);
console.log("Job ARN:", response.jobArn);
The optional validationDataConfig accepts a separate JSONL with the same format as training data. If provided, Bedrock evaluates loss on the validation set after each epoch and reports the metrics in the job output. This is useful for detecting overfitting — if training loss keeps decreasing but validation loss starts rising, the student is memorizing training examples rather than generalizing.
Hyperparameter tuning guidance
Unlike neural architecture search, Bedrock distillation hyperparameter tuning is straightforward because the architecture is fixed — you are only choosing training duration and learning rate. The decision tree:
// Decision tree for hyperparameter selection
// 1. epochCount
// - Start with "2" for all tasks
// - Increase to "3" or "4" only if validation loss is still improving at epoch 2
// - Decrease to "1" only if you have a very large dataset (50,000+) or tight cost budget
// 2. batchSize
// - Use "1" for most cases — it is the most stable for small student models
// - Use "2" or "4" only if you have 20,000+ examples and training is noisy
// - Larger batch sizes reduce training time (fewer gradient steps) but require Bedrock to allocate
// more memory, which can extend queue time
// 3. learningRateMultiplier
// - "1.0" for all tasks initially
// - Increase to "2.0" if training loss barely decreases after epoch 1
// (learning rate too low for the student model to adapt)
// - Decrease to "0.5" if training loss oscillates wildly between steps
// (learning rate too high — overshooting)
// 4. maxResponseLengthForInference (in teacherModelConfig, not hyperParameters)
// - For classification (single word/phrase output): 50-100 tokens
// - For extraction (structured JSON output): 512-1024 tokens
// - For summarization: 1024-2048 tokens
// - For open-ended generation: 2048-4096 tokens
const recommendedDefaults = {
epochCount: "2",
batchSize: "1",
learningRateMultiplier: "1.0",
// early stopping disabled by default — enable when using validation data
};
Getting job details with GetModelCustomizationJob
The GetModelCustomizationJobCommand response contains detailed fields beyond just the status:
import {
BedrockClient,
GetModelCustomizationJobCommand,
} from "@aws-sdk/client-bedrock";
async function inspectDistillationJob(jobArn: string) {
const job = await bedrockClient.send(
new GetModelCustomizationJobCommand({ jobIdentifier: jobArn })
);
console.log({
// Core status
status: job.status, // "InProgress" | "Completed" | "Failed" | "Stopping" | "Stopped"
jobName: job.jobName,
creationTime: job.creationTime,
endTime: job.endTime, // set when job finishes (Completed, Failed, or Stopped)
// Model ARNs
baseModelArn: job.baseModelArn, // the student base
outputModelArn: job.outputModelArn, // the distilled model (only when Completed)
outputModelKmsKeyArn: job.outputModelKmsKeyArn,
// Failure details (only set when status === "Failed")
failureMessage: job.failureMessage,
// Training metrics (available during and after training)
trainingMetrics: job.trainingMetrics, // { trainingLoss: number }
validationMetrics: job.validationMetrics, // [ { validationLoss: number } ]
// Output location
outputDataConfig: job.outputDataConfig, // { s3Uri: string }
});
// Check if the custom model is ready
if (job.status === "Completed") {
console.log("Custom model ARN:", job.outputModelArn);
console.log("Final training loss:", job.trainingMetrics?.trainingLoss);
}
if (job.status === "Failed") {
console.error("Job failed:", job.failureMessage);
}
}
The trainingMetrics.trainingLoss at job completion gives a rough signal of training quality: a final loss near 0 may indicate overfitting; a loss that barely decreased from the initial value may indicate the learning rate was too low or the student model's capacity is insufficient for the task. For the most informative signal, provide validationDataConfig so you can compare training vs. validation loss.
Listing and managing jobs with ListModelCustomizationJobs
When running multiple distillation experiments, ListModelCustomizationJobsCommand lets you query jobs by status and date range without tracking individual ARNs:
import {
ListModelCustomizationJobsCommand,
SortJobsBy,
SortOrder,
} from "@aws-sdk/client-bedrock";
async function listDistillationJobs(statusFilter?: string) {
const allJobs: Array<{ jobName?: string; status?: string; creationTime?: Date; jobArn?: string }> = [];
let nextToken: string | undefined;
do {
const response = await bedrockClient.send(
new ListModelCustomizationJobsCommand({
// Filter by status: "InProgress" | "Completed" | "Failed" | "Stopped"
statusEquals: statusFilter as never,
// Sort by most recently created first
sortBy: SortJobsBy.CREATION_TIME,
sortOrder: SortOrder.DESCENDING,
maxResults: 20,
nextToken,
})
);
for (const job of response.modelCustomizationJobSummaries ?? []) {
allJobs.push({
jobName: job.jobName,
status: job.status,
creationTime: job.creationTime,
jobArn: job.jobArn,
});
}
nextToken = response.nextToken;
} while (nextToken);
return allJobs;
}
// Find all in-progress jobs
const running = await listDistillationJobs("InProgress");
console.log("Running jobs:", running.length);
// Find all completed jobs
const completed = await listDistillationJobs("Completed");
console.log("Completed jobs:", completed.map(j => j.jobName));
Stopping a running job
If you detect a configuration mistake (wrong training data URI, incorrect teacher model) after a job starts, stop it immediately to avoid wasting compute cost and unnecessary teacher model invocations:
import { StopModelCustomizationJobCommand } from "@aws-sdk/client-bedrock";
async function stopDistillationJob(jobArn: string): Promise<void> {
await bedrockClient.send(
new StopModelCustomizationJobCommand({ jobIdentifier: jobArn })
);
// Stopping is asynchronous — the job moves to "Stopping" then "Stopped"
// Poll until it reaches a terminal state
let status = "Stopping";
while (status === "Stopping") {
await new Promise((r) => setTimeout(r, 30_000));
const job = await bedrockClient.send(
new GetModelCustomizationJobCommand({ jobIdentifier: jobArn })
);
status = job.status ?? "Stopped";
console.log("Status:", status);
}
console.log("Job stopped. Final status:", status);
}
// A stopped job leaves no usable custom model — you must restart with corrected config
// Cost: you are billed for teacher invocations already completed before the stop
await stopDistillationJob(jobArn);
Stopping a job is irreversible — a stopped job cannot be resumed. You must create a new job with corrected parameters. You are billed for teacher model invocations that completed before the stop, as well as any compute time used for training steps. Early stopping is cheaper than letting a misconfigured job run to completion.
Job status lifecycle and common failure reasons
// Status transitions:
// Starting → InProgress → Completed
// Starting → InProgress → Stopping → Stopped (manual stop)
// Starting → Failed (validation failure before training begins)
// InProgress → Failed (training error mid-job)
// Common failureMessage values and their causes:
const FAILURE_REASONS = {
// Training data issues
"Failed to read training data": "S3 URI is wrong or IAM role lacks s3:GetObject",
"Invalid JSONL format at line N": "Malformed JSON, blank line, or BOM in training file",
"Insufficient training examples": "Fewer than 1,000 valid prompts in training file",
// Teacher model issues
"AccessDeniedException calling teacher model":
"IAM role lacks bedrock:InvokeModel on teacher model ARN",
"ResourceNotFoundException calling teacher model":
"Teacher model ID is wrong or not available in your region",
// Configuration issues
"Invalid hyperParameter value":
"A hyperParameter value is not in its valid range, or is a number not a string",
"teacherModelConfig is required for DISTILLATION":
"customizationType is DISTILLATION but teacherModelConfig was omitted",
"baseModelIdentifier is not supported for DISTILLATION":
"Chosen student base model does not support distillation customization",
// Quota issues
"ServiceQuotaExceededException":
"Account limit on concurrent customization jobs reached; wait for another to finish",
};
Cost estimation before starting
Distillation cost has two components: teacher model invocations (Bedrock calls the teacher for each prompt-only line during the job) and compute for the training job itself. Estimate before submitting:
// Rough cost estimation for a distillation job
function estimateDistillationCost(params: {
promptCount: number;
avgPromptTokens: number;
avgTeacherOutputTokens: number;
teacherInputPricePerKToken: number; // e.g. Claude 3 Sonnet: $0.003
teacherOutputPricePerKToken: number; // e.g. Claude 3 Sonnet: $0.015
trainingComputeHours: number; // estimate 1-4 hours for 5000 prompts
computePricePerHour: number; // Bedrock training rate; check Bedrock pricing page
}) {
const teacherInputCost =
(params.promptCount * params.avgPromptTokens / 1000) * params.teacherInputPricePerKToken;
const teacherOutputCost =
(params.promptCount * params.avgTeacherOutputTokens / 1000) * params.teacherOutputPricePerKToken;
const computeCost = params.trainingComputeHours * params.computePricePerHour;
return {
teacherInputCost: teacherInputCost.toFixed(2),
teacherOutputCost: teacherOutputCost.toFixed(2),
computeCost: computeCost.toFixed(2),
totalCost: (teacherInputCost + teacherOutputCost + computeCost).toFixed(2),
};
}
// Example: 10,000 prompts, 100 tokens avg each, 200 tokens teacher output
const estimate = estimateDistillationCost({
promptCount: 10_000,
avgPromptTokens: 100,
avgTeacherOutputTokens: 200,
teacherInputPricePerKToken: 0.003, // Claude 3 Sonnet input
teacherOutputPricePerKToken: 0.015, // Claude 3 Sonnet output
trainingComputeHours: 2,
computePricePerHour: 2.00, // approximate; check current Bedrock pricing
});
console.log(estimate);
// { teacherInputCost: "3.00", teacherOutputCost: "30.00", computeCost: "4.00", totalCost: "37.00" }
Teacher output cost dominates for open-ended tasks where the teacher writes long completions. For classification tasks where the teacher output is a single word or short phrase, teacher cost is negligible and compute cost dominates. If you pre-generate teacher completions yourself and include them in the JSONL (prompt+completion format), the teacher invocation cost is eliminated from the job — Bedrock uses your provided completions directly.
Know when your distilled MCP server goes down
After deploying a distilled model behind Provisioned Throughput, your MCP server's uptime depends on a custom endpoint that has different failure modes from standard foundation models. AliveMCP monitors your MCP server from the outside and alerts you when tool calls fail or latency spikes — before your users notice the difference between the teacher and student model.