Generated banner for Finetuning
Generated logo for Finetuning

Finetuning

AWS LabsOfficialPublished by AWS Labs

  • Skill
  • Workflow
  • Data and AI
  • Apache-2.0
  • Low risk
  • Has scripts

From the author

Generates code that fine-tunes a base model using SageMaker serverless training jobs. Use when the user says "start training", "fine-tune my model", "I'm ready to train", or when the plan reaches the finetuning step. Supports SFT, DPO, RLVR, and RLAIF trainers, including RLVR Lambda reward function and RLAIF custom prompt creation.
— the description by AWS Labs

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

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/awslabs/finetuning/download
  2. Unzip 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:

  1. A use_case_spec.md file exists

    • If missing: Activate the use-case-specification skill first, then resume

    • DON'T EVER offer to create a use case spec without activating the use-case-specification skill.

  2. 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-selection and/or finetuning-technique skills to collect what's missing, then resume

    • Don't make recommendations on the spot. You MUST activate the appropriate skill.

  3. A base model name available on SageMakerHub has been identified

    • If missing: Activate the model-selection skill to get it

    • Important: Only use the model name that model-selection retrieves, as it may differ from other commonly used names for the same model

  4. The SDK environment has been verified (SDK version, region, execution role)

    • If not done: Activate the sdk-getting-started skill first, then resume

  5. 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_cell is 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
  1. 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.py

  • DPO → code_templates/dpo.py

  • RLVR → code_templates/rlvr.py

  • RLAIF with built-in rewards → code_templates/rlaif_builtin.py

  • RLAIF 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
  1. Write the code from the template following the rules in code_output_guide.md

  2. Use same order, dependencies, and imports as the template

  3. DO NOT improvise or add extra code

  4. If the model is NOT a Meta/Llama model (model ID does NOT start with meta-):

    • Omit the ACCEPT_EULA = False line from the config cell

    • Omit the accept_eula=ACCEPT_EULA, line from the trainer call

  5. If the model is from the Nova family, omit any code containing max_epochs or lr_warmup_steps_ratio from the Configure Trainer section and the Hyperparameter Overrides section

1.4 Auto-Generate Configuration Values

In the 'Setup & Credentials' cell, populate:

  1. BASE_MODEL

    • Use the exact SageMakerHub model name from context

  2. MODEL_PACKAGE_GROUP_NAME

    • Generate from use case (read use_case_spec.md if 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

  3. 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
  1. Follow workflow in references/rlvr_reward_function.md section "Helping Users Create Custom Reward Functions"

2.3 Set CUSTOM_REWARD_FUNCTION value
  1. Set the value for CUSTOM_REWARD_FUNCTION in the Notebook with the ARN of the reward function (either given directly by the user, or from the function generation code as evaluator.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

  1. Look up the official license link for the selected base model from references/eula_links.md

  2. 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}."

  3. 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 = True and uncomment accept_eula=ACCEPT_EULA in the generated notebook. If the user declines, leave ACCEPT_EULA = False and 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_EULA variable and accept_eula parameter 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:

  1. Leave it to you — run with python scripts/[script_name]

  2. Run it and wait until it's done

  3. 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=True to wait=False in the script, execute, report the training job name.

Checking status:

  • describe-training-job --training-job-name NAME → TrainingJobStatus, FailureReason, SecondaryStatusTransitions

  • For 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.py as the pattern to query MLflow metrics

  • Present 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 options

  • rlaif_builtin.py - Code template for RLAIF with built-in judge prompt

  • rlaif_custom_prompt.py - Code template for RLAIF with custom judge prompt

Files

references/rlvr_reward_function.md

RLVR Lambda Reward Function Guide

What Is a Lambda Reward Function?

For RLVR (Reinforcement Learning from Verifiable Rewards) training, a Lambda reward function is an AWS Lambda that evaluates model outputs during training and returns numerical reward scores. SageMaker invokes this Lambda within the training loop to provide learning signals that guide model optimization.


Helping Users Create Custom Reward Functions

Tell user: I will now review your use case and data, as well as my own resources, to propose a reward function that you can use to train your model. I will do my best to match it to your needs, but I strongly suggest that you review it carefully before starting the training.

Step 1: Analyze the Use Case

Reward functions are specific to the use case and dataset. Consider the task and data format to understand what constitutes a good output and how to measure it.

  1. Review these materials:

    • use_case_spec.md — problem description and success criteria

    • Conversation context — the user's goals

    • 20 rows of training data — structure and content of the expected responses

  2. Answer these questions internally (involve the user if you need clarification):

    • Given the analysis in (1), what makes a good response? A bad response? A partially correct response?

    • Which aspects of the response can be verified programmatically?

    • Are there specific constraints or formats the output must follow?

    • How would the base model's initial responses during early training likely look?


Step 2: Analyze the Structure of the Response
  • Which parts of the response contain the content you want to verify programmatically?

  • How are those parts delimited? How can they be parsed?

  • How rigid should the extraction patterns be, given the 20 rows of data reviewed?

  • Are there special formats to account for (fractions, LaTeX, Unicode, Markdown, etc.)? How do they affect the extraction logic?

  • Does the base model include a thinking block in its output?

  • Does the use case require changing the model's behavior within the thinking block, or only in the final response?

  • If warranted, how can the response format/schema be verified programmatically?

  • If there is a ground truth in the data:

    • Does the model's response need to match it exactly?

    • Does a partial match count? If so, how?

    • How can you deterministically decide whether the response is close enough to the ground truth?


Step 3: Plan the Verification Logic
  • Write a function that extracts the verifiable parts identified in Steps 1 and 2 from the response.

  • Identify the most suitable and performant tools for checking format or schema (e.g., which Python libraries?).

  • If you need to validate generated code, write a function that executes it and returns a pass/fail/test result with a corresponding reward score.

  • Are there keywords to check for? Which ones, and how many need to be present?

  • What is the appropriate similarity function for comparing the response to the ground truth?

  • If the response contains a block of text where the choice of words can vary slightly and still be correct, how can you verify that it is similar enough to the ground truth?

  • Share the plan with the user and get confirmation before proceeding.

Step 4: Add Anti-Gaming Checks

Add at least two mechanisms to detect and penalize gaming behavior. Common gaming patterns include:

  • Padding — inserting filler characters to inflate response length

  • Skipping steps — jumping to a final answer without showing required reasoning

  • Repetition — filling length requirements with repeated whitespace or words

  • Dummy content — using placeholder text instead of genuine answers

  • Echo attack — repeating the prompt or question back as the answer

  • Nonsense — producing incoherent or irrelevant text


Step 5: Design the Aggregation Method

If the use case allows, think of rewards as a pyramid where each layer depends on the one beneath it. No credit is given for higher layers until lower ones are fully satisfied.

  • Layer 1 (Foundation) — Structure

    • Is the output formatted correctly and machine-parsable?

    • Example: If JSON is expected, is it valid JSON? Are all required fields filled?

  • Layer 2 (Core) — Semantics

    • Is the output factually correct and does it deliver real value?

    • Example: Can generated code pass unit tests? Is the math answer correct?

  • Layer 3 (Polish) — Behavior

    • Does the output meet operational and safety requirements?

    • Example: Is the response concise? Free from toxic content? Complete?

  • Aggregation

    • What is the most suitable weighted distribution across these layers and their sub-components?

    • Ensure each component function returns a spread of scores even for low-quality responses. If a component returns 0 for 90%+ of plausible early-training outputs, it will flatten the reward signal and stall learning.

    • Briefly share the reasoning with the user and get confirmation.


Step 6: Write the Function as a Python Script
  1. Create a file called lambda_function.py in the project's scripts directory.

  2. Read the directory-management skill to determine the correct directory for storing scripts.

  3. Consult the reward function templates for structural reference:

    • Nova 2.0 Lite → templates/nova_rlvr_reward_function_source_template.py

    • All other models → templates/rlvr_reward_function_source_template.py

Critical rules:

  • The lambda_handler function must be copied to lambda_function.py exactly as given in the template. Do not change its signature or internal logic.

  • The chat template used in the example reward functions is correct. Use it to extract the assistant's response. Then apply the parsing logic from Step 2 to extract the parts of the response you want to score.

  • Do not copy anything beyond the lambda_handler and the assistant-response extraction. The rest of the template is an example that will not work out of the box. You must customize the reward logic based on the use case and data, as described in Steps 1–5. Copying the template's reward logic without customization will likely produce flat rewards, wasting the user's time and compute budget.

Code writing principles:

  1. Provide a learning gradient: Return diverse scores across [-1.0, 1.0], with partial credit for partial answers where appropriate — not just {-1, 0, 1}.

  2. Verify correctly: Use actual parsing tools (json.loads, ast.parse, etc.), not string matching.

  3. Include all necessary imports: Add every required import statement at the top of the file.

  4. Execute fast: Complete in <100 ms with no API calls or blocking operations.

  5. Be deterministic: Same input → same output, always.

  6. Be bounded: The final score must always fall within [-1.0, 1.0]. Add return min(1.0, max(-1.0, score)) at the end.

  7. Comment thoroughly: Include detailed comments explaining the reward logic.

Step 7: Test Locally

Test the reward function by executing it against crafted sample data:

  1. Build test input. Infer the expected Lambda event and response format from the lambda_handler function in the appropriate source template. Choose one prompt from the training data reviewed in Step 1. Construct four test events that mimic what SageMaker sends to the Lambda:

    • An excellent response — use the response from the data.

    • A partially correct response — generate one that gets some things right but misses others.

    • A bad response — generate one that is clearly wrong or off-topic, but without gaming.

    • A gaming response — generate one that tries to get rewards by gaming.

  2. Explain what you are doing and show the user the four responses that you want to test.

  3. Write the batch to a temp file (e.g., /tmp/test_reward_input.json).

  4. Run the function Invoke lambda_function.py via the shell:

    python3 -c "
    import sys, json
    sys.path.insert(0, '<project-dir>/scripts')
    from lambda_function import lambda_handler
    with open('/tmp/test_reward_input.json') as f:
        event = json.load(f)
    result = lambda_handler(event, None)
    print(json.dumps(result, indent=2))
    "
  5. Verify the output. Check that:

    • All scores fall within [-1.0, 1.0].

    • The excellent response scores highest, the bad response scores lowest.

    • No errors or exceptions occurred.

  6. Show the user the test inputs, expected score ordering, and actual scores.

  7. If the test fails or scores don't match expectations, fix the function and re-run until it passes. Inform the user about what you are doing.

Step 8: Check In with the User
  • Share the path to the reward function with the user.

  • Remind user that this is only a suggestion, and emphasize the need to review the reward function before launching the training. It is up to them to decide if they want to use it, edit it, or choose not to use it.

  • Let the user know that the source templates are also available for them under finetuning/templates, if they want to compare your function to them or customize them on their own.

Step 9: Register the Reward Function in the Finetuning Output

After the reward function is written and tested, generate the registration code that corresponds to Cell 3 in code_templates/rlvr.py. Add the registration code to the finetuning output as Cell 3, following the format already chosen for this session (notebook or script).

Set reward_function_path to the path where lambda_function.py was saved in Step 6.

from sagemaker.ai_registry.evaluator import Evaluator

# Insert path to lambda_function.py from Step 6 here:
reward_function_path = ""

evaluator = Evaluator.create(
    name="[GENERATE A NAME FOR THE EVALUATOR HERE]",
    type="RewardFunction",
    source=reward_function_path,
)
CUSTOM_REWARD_FUNCTION = evaluator.arn
print(f"Reward Function ARN: {CUSTOM_REWARD_FUNCTION}")

Generate an appropriate name for the Evaluator based on the use case and current context.

  • Format: lowercase, alphanumeric with hyphens only, 1–20 characters

  • Pattern: [a-zA-Z0-9](-*[a-zA-Z0-9]){0,20}

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