Finetuning
AWS LabsOfficialPublished by AWS Labs
- Skill
- Workflow
- Data and AI
- Apache-2.0
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured workflow to generate code for fine-tuning machine learning models on AWS SageMaker. It supports multiple training techniques including SFT, DPO, RLVR, and RLAIF. The skill ensures that all prerequisites—such as use case specifications, model selection, and environment configuration—are met before generating the necessary Python scripts or Jupyter notebooks. It also handles EULA acceptance for specific models and provides options for executing training jobs and monitoring their status.
What it does
- Generates standardized training code for SFT, DPO, RLVR, and RLAIF techniques.
- Configures SageMaker serverless training jobs with appropriate model and dataset parameters.
- Manages EULA review and acceptance for restricted base models.
- Supports creation of custom reward functions for RLVR workflows.
- Provides options to run training jobs as scripts or within notebooks.
- Monitors training job status and reports performance metrics upon completion.
When to use it
- When the user requests to start training or fine-tune a model.
- When the project plan reaches the fine-tuning phase.
- When you need to perform a subsequent round of fine-tuning on an already customized model.
Advantages
- Ensures consistent code structure and dependency management across projects.
- Automates the configuration of complex SageMaker training parameters.
- Provides a safe, step-by-step process that validates prerequisites before execution.
- Offers flexible execution modes (notebook vs. script) to suit user preferences.
Usage examples
- “I'm ready to train my model using SFT.”
- The agent verifies prerequisites, selects the SFT template, configures the SageMaker environment, and generates the training notebook or script.
- “Can you help me fine-tune this model with RLVR?”
- The agent guides the user through creating a reward function or providing an existing ARN, then generates the RLVR training code.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/awslabs/finetuning/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip finetuning.zip -d .agents/skills
Documentation by AWS Labs
Prerequisites
Before starting this workflow, verify:
A
use_case_spec.mdfile existsIf missing: Activate the
use-case-specificationskill first, then resumeDON'T EVER offer to create a use case spec without activating the use-case-specification skill.
A fine-tuning technique (SFT, DPO, RLVR, RLAIF, or CPT/RFT (for Nova)) and base model have already been selected
If missing: Activate the
model-selectionand/orfinetuning-techniqueskills to collect what's missing, then resumeDon't make recommendations on the spot. You MUST activate the appropriate skill.
A base model name available on SageMakerHub has been identified
If missing: Activate the
model-selectionskill to get itImportant: Only use the model name that
model-selectionretrieves, as it may differ from other commonly used names for the same model
The SDK environment has been verified (SDK version, region, execution role)
If not done: Activate the
sdk-getting-startedskill first, then resume
A training dataset uploaded to a bucket in the environment's default region.
If not met: Help the user upload the dataset to the correct S3
Critical Rules
Code Generation Rules
✅ Use EXACTLY the imports shown in each code template
❌ Do NOT add additional imports even if they seem helpful
❌ Do NOT create variables before they're needed in that section
📋 Copy the code structure precisely - no improvisation
🎯 Follow the minimal code principle strictly
✅ When writing code, make sure the indentation and f strings are correct
User Communication Rules
❌ NEVER offer to move on to a downstream skill while training is in progress (logically impossible)
❌ NEVER set ACCEPT_EULA to True without explicit user confirmation in the conversation
✅ Always mention both the number AND title of sections you reference
✅ If user asks how to run (notebook): If
run_cellis available, offer to run it. Otherwise, tell them to run cells one by one (mention ipykernel requirement).✅ If user asks how to run (script): Tell them to run with
python3 <script>.py
Workflow
1. Code Generation Setup
1.1 Directory Setup
Identify project directory from conversation context
If unclear (multiple relevant directories exist) → Ask user which folder to use
If no project directory exists → activate the directory-management skill to set one up
⏸ Wait for user.
1.2 Select Code Template
Read references/code_output_guide.md for output format rules, then read the code template matching the finetuning strategy:
SFT →
code_templates/sft.pyDPO →
code_templates/dpo.pyRLVR →
code_templates/rlvr.pyRLAIF with built-in rewards →
code_templates/rlaif_builtin.pyRLAIF with custom prompt →
code_templates/rlaif_custom_prompt.py
The template is a Python file where each # Cell N: Label comment marks the start of a new section. Split on these markers — everything between one marker and the next becomes one unit of output.
1.3 Generate Code
Write the code from the template following the rules in
code_output_guide.mdUse same order, dependencies, and imports as the template
DO NOT improvise or add extra code
If the model is NOT a Meta/Llama model (model ID does NOT start with
meta-):Omit the
ACCEPT_EULA = Falseline from the config cellOmit the
accept_eula=ACCEPT_EULA,line from the trainer call
If the model is from the Nova family, omit any code containing
max_epochsorlr_warmup_steps_ratiofrom the Configure Trainer section and the Hyperparameter Overrides section
1.4 Auto-Generate Configuration Values
In the 'Setup & Credentials' cell, populate:
BASE_MODEL
Use the exact SageMakerHub model name from context
MODEL_PACKAGE_GROUP_NAME
Generate from use case (read
use_case_spec.mdif needed)Format rules:
Lowercase, alphanumeric with hyphens only
1-63 characters
Pattern:
[a-zA-Z0-9](-*[a-zA-Z0-9]){0,62}Example: "Customer Support Chatbot" →
customer-support-chatbot-v1
Save notebook
2. RLVR Reward Function (for RLVR only, skip this section if technique is SFT or DPO)
2.1 Check Reward Function Status
Ask if user has a reward function already, or would like help creating one.
If user says they have one → Ask for the SageMaker Hub Evaluator ARN. Only proceed to Section 2.3 once the user provides a valid Evaluator ARN. If they don't have it registered as a SageMaker Hub Evaluator, continue to 2.2.
If user says they do not have one → Continue to 2.2
2.2 Generate Reward Function From Template
Follow workflow in
references/rlvr_reward_function.mdsection "Helping Users Create Custom Reward Functions"
2.3 Set CUSTOM_REWARD_FUNCTION value
Set the value for
CUSTOM_REWARD_FUNCTIONin the Notebook with the ARN of the reward function (either given directly by the user, or from the function generation code asevaluator.arn).
3. RLAIF (for RLAIF only, skip this section if technique is not RLAIF)
Read references/rlaif_guide.md and follow its instructions.
4. EULA review and acceptance
Look up the official license link for the selected base model from references/eula_links.md
Display the license to the user following the phrasing in references/eula_links.md. For OSS models: "This model is licensed under {License}. Please review the license terms here: {URL}." For Nova models: "This model is subject to the AWS Service Terms: {URL}."
Check if the selected base model is a Meta/Llama model (model ID starts with
meta-)If Meta/Llama: Tell the user they must read and agree to the EULA before using this model. Ask: "Do you accept the license terms? (yes/no)". If the user confirms, set
ACCEPT_EULA = Trueand uncommentaccept_eula=ACCEPT_EULAin the generated notebook. If the user declines, leaveACCEPT_EULA = Falseand warn that training will fail without acceptance.If non-Meta: Inform the user of the license for their awareness. No code-level action needed — the
ACCEPT_EULAvariable andaccept_eulaparameter should already be omitted from the notebook (see Step 1.3).
5. Post-Generation
After generating the code, offer to run it. Training can take hours depending on your dataset and model.
Notebook mode: If run_cell is available, offer to run the cells. Otherwise tell the user to run cells themselves.
Script mode: Present the user with options:
"Would you like me to:
Leave it to you — run with
python scripts/[script_name]Run it and wait until it's done
Start it but don't wait — we can check status later"
Option 1: Done. Wait for user to come back.
Option 2: Execute the script as-is.
trainer.train(wait=True)blocks until complete. Report final status.Option 3: Change
wait=Truetowait=Falsein the script, execute, report the training job name.
Checking status:
describe-training-job --training-job-name NAME→TrainingJobStatus,FailureReason,SecondaryStatusTransitionsFor model package ARN after completion:
list-model-packages --model-package-group-name GROUP_NAME --sort-by CreationTime --sort-order Descending --max-results 1
Showing results after completion:
Use
scripts/mlflow_reference.pyas the pattern to query MLflow metricsPresent loss by epoch as a text table (total_loss, val_eval_total_loss for SFT; rewards/margins for DPO; critic/rewards/mean for RLVR)
CRITICAL:
DON'T suggest moving to next steps before training completes
DON'T elaborate on the next steps unless the user specifically asks you about them.
6. Continuous Customization
If the user wants to finetune a model they had already customized, follow the instructions in references/continuous_customization.md
References
rlvr_reward_function.md- Lambda reward function creation guide (RLVR only)templates/rlvr_reward_function_source_template.py- Lambda reward function source template for open-weights models (RLVR only)templates/nova_rlvr_reward_function_source_template.py- Lambda reward function source template for Nova 2.0 Lite (RLVR only)code_templates/sft.py- Complete notebook template for Supervised Fine-Tuning (OSS path)code_templates/dpo.py- Complete notebook template for Direct Preference Optimization (OSS path)code_templates/rlvr.py- Complete notebook template for Reinforcement Learning from Verifiable Rewards (OSS path)references/continuous_customization.md- Instructions on fine-tuning an already fine-tuned model.rlaif_guide.md- instructions on RLAIF finetuning optionsrlaif_builtin.py- Code template for RLAIF with built-in judge promptrlaif_custom_prompt.py- Code template for RLAIF with custom judge prompt
Files
- ATTRIBUTION.mdAdded by AutoGineer904 B
- LICENSELicence file added by AutoGineer9.9 KiB
- NOTICELicence file added by AutoGineer89 B
- SKILL.md9.1 KiB
- code_templates/dpo.pyScript5.7 KiB
- code_templates/rlaif_builtin.pyScript5.5 KiB
- code_templates/rlaif_custom_prompt.pyScript6.0 KiB
- code_templates/rlvr.pyScript6.2 KiB
- code_templates/sft.pyScript5.5 KiB
- references/code_output_guide.md3.2 KiB
- references/continuous_customization.md8.5 KiB
- references/eula_links.md7.8 KiB
- references/rlaif_guide.md3.8 KiB
- references/rlvr_reward_function.md10.0 KiB
- scripts/mlflow_reference.pyScript840 B
- templates/nova_rlvr_reward_function_source_template.pyScript12.7 KiB
- templates/rlvr_reward_function_source_template.pyScript9.2 KiB
references/continuous_customization.md
Continuous Customization (Multi-Round Fine-Tuning)
Adds a subsequent fine-tuning round on top of an already-customized model. Uses the Model Package ARN from a previous training job as the base model instead of a SageMakerHub model name.
Prerequisites
| Requirement | How to obtain |
|---|---|
| Training data S3 path for current round | Collect from the conversation context, ask user if not available |
| Confirmation that data is in correct format for current finetuning strategy | From dataset-evaluation skill or user is sure it's correct |
| Fine-tuning technique | If not available from context, ask which technique for this round: SFT, DPO, RLVR, or RLAIF |
| Previous model package group name | From the prior output, or help the user find it (Section A instructions) |
| Previous training job name | Ask user or get from user's account (Section B instructions) |
| Reward function for RLVR as a Lambda Evaluator | Ask user if they have one, otherwise follow rlvr_reward_function.md to create one |
| Reward prompt as a RewardPrompt Evaluator and reward model id for RLAIF | Ask user if they have one, otherwise follow rlaif_guide.md |
Output Placement
The output format (notebook or script) should already be established from the conversation context — do not re-ask if it has already been decided. If necessary, the output format guide is in references/code_output_guide.md.
Notebook mode: If the user has an existing notebook from the previous round, append these cells under a new markdown header describing the round, e.g.,
## DPO Fine-Tuning (Round 2). If no prior notebook exists, create a new one with a name reflecting the use case and techniques, e.g.,news-app-sft-to-dpo.ipynb.Script mode: Write a new numbered
.pyfile in<project-dir>/scripts/, e.g.,02_dpo_finetuning_round2.py. Use# %%cell markers to separate logical sections.
Section A: Setup & Credentials
<!-- markdownlint-disable MD001 -->
Re-establishes session variables. Required to ensure all variables are defined.
Agent Instructions
Set
NEW_TRAINING_DATA_S3to the user's dataset S3 path for the current round.Set
PREVIOUS_MODEL_PACKAGE_GROUP_NAME:If the prior output is available: Copy the model package group name from it.
If not: Use the AWS CLI MCP tool
list-model-package-groupswith these flags:--query 'ModelPackageGroupSummaryList[].{Name:ModelPackageGroupName,Status:ModelPackageGroupStatus,Created:CreationTime}' --output tableOptionally add
--name-contains <keyword>to filter by name.If you can't identify the name from the list: Ask the user.
Code
import boto3
from sagemaker.ai_registry.dataset import DataSet
from sagemaker.core.resources import ModelPackageGroup
from sagemaker.core.helper.session_helper import Session, get_execution_role
# Setup
sm_client = boto3.Session().client("sagemaker")
sagemaker_session = Session(sagemaker_client=sm_client)
bucket = sagemaker_session.default_bucket()
S3_OUTPUT_PATH = f"s3://{bucket}/finetuning-output/"
ROLE_ARN = get_execution_role()
# Configuration
NEW_TRAINING_DATA_S3 = "" # S3 path to the dataset for this round
PREVIOUS_MODEL_PACKAGE_GROUP_NAME = "" # Model package group name from the previous roundSection B: Retrieve Previous Model Package ARN
Looks up the model package ARN from the previous training job.
Agent Instructions
Ask the user if they have the training job name from the previous fine-tuning round or need help finding it.
If the user provides the name → Set it as
previous_training_job_namein the code.If the user needs help → Use the AWS CLI MCP tool
list-training-jobswith these flags:--status-equals Completed --query 'TrainingJobSummaries[].{Name:TrainingJobName,Status:TrainingJobStatus,Created:CreationTime}' --output tablePresent the results and let the user pick the correct job.
If the user is unsure and wants to fill it later → Leave the placeholder
<previous_training_job_name>and tell them to replace it before running.
Code
from sagemaker.core.resources import TrainingJob
previous_training_job_name = "<previous_training_job_name>" # USER: paste your previous training job name here
job = TrainingJob.get(training_job_name=previous_training_job_name)
previous_model_package_arn = job.output_model_package_arn
print(f"Previous Model Package ARN: {previous_model_package_arn}")Troubleshooting: If this cell throws
ValidationException: Requested resource not found, the job name is wrong or the output is connected to a different AWS region than where the job ran. Verify the region withboto3.Session().region_name.
Section C: Register New Dataset
Registers the current round's training data as a versioned DataSet.
Agent Instructions
Set
nameto something descriptive of the use case and round, e.g.,"customer-support-chatbot-dpo-round2".
Code
from sagemaker.ai_registry.dataset import DataSet
dataset = DataSet.create(
name="<dataset_name>",
source=NEW_TRAINING_DATA_S3,
wait=True
)
new_dataset_arn = dataset.arn
print(f"New Training Dataset ARN: {new_dataset_arn}")Section D: Add Evaluators
If necessary, use this section to register the custom RLVR reward function or custom RLAIF reward prompt as an evaluator on SageMaker AI Hub Registry.
from sagemaker.ai_registry.evaluator import Evaluator
from sagemaker.ai_registry.air_constants import REWARD_FUNCTION, REWARD_PROMPT
evaluator = Evaluator.create(
name="",
type=REWARD_FUNCTION, # Use REWARD_FUNCTION for RLVR, REWARD_PROMPT for RLAIF
source="", # Path to reward function or prompt file
sagemaker_session=sagemaker_session,
wait=True
)
print(f"Evaluator ARN: {evaluator.arn}")Section E: Configure and Start Training
Runs the next fine-tuning round. The key difference from the first round: model receives previous_model_package_arn instead of a base model name.
Agent Instructions
Choose the trainer class matching the user's technique for this round and pass additional inputs if needed:
| Technique | Import | Additional Trainer inputs |
|---|---|---|
| SFT | from sagemaker.train.sft_trainer import SFTTrainer | |
| DPO | from sagemaker.train.dpo_trainer import DPOTrainer | |
| RLVR | from sagemaker.train.rlvr_trainer import RLVRTrainer | custom_reward_function |
| RLAIF | from sagemaker.train.rlaif_trainer import RLAIFTrainer | reward_prompt, reward_model_id, built_in_metrics |
Code (SFT example — swap trainer class for DPO/RLVR/RLAIF)
from sagemaker.train.sft_trainer import SFTTrainer
from sagemaker.train.common import TrainingType
step2_trainer = SFTTrainer(
model=previous_model_package_arn,
training_type=TrainingType.LORA,
model_package_group=PREVIOUS_MODEL_PACKAGE_GROUP_NAME,
training_dataset=new_dataset_arn,
s3_output_path=S3_OUTPUT_PATH,
sagemaker_session=sagemaker_session,
role=ROLE_ARN,
)
step2_job = step2_trainer.train(wait=True)
print(f"Training Job Name for current round: {step2_job.training_job_name}")
print(f"Training Status: {step2_job.training_job_status}")Rules
✅ Reuse the same
PREVIOUS_MODEL_PACKAGE_GROUP_NAMEfrom the first round so all model versions stay grouped together❌ Do NOT pass
accept_eula— it only applies to the initial base model download❌ Do NOT re-create the
ModelPackageGroup— it already exists from the first round
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs Python
Security
What our scanner noticed· Low risk
- Instructions that use the network
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- AWS Labs
- Publisher
- AWS Labs (Official)
- Source
- awslabs/agent-plugins · plugins/sagemaker-ai/skills/finetuning · commit fbefb37
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- NOTICE (added by AutoGineer from NOTICE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by AWS Labs.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download finetuning.zip