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://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

templates/nova_rlvr_reward_function_source_template.py

"""
Provide your custom reward function code below. Learn about the available libraries and templates that you can use
at: https://docs.aws.amazon.com/sagemaker/latest/dg/customize-model.html.

- You must add your evaluation logic in the reward_function() function
- Do not remove the lambda_handler() function or modify its schema as it is required to create the reward function
"""

import json  # For JSON parsing - adjust imports based on your use case
import re    # For pattern matching and validation
from typing import Dict, Any, List, Optional, Union # For type hints
# Add any other imports your use case requires

# ========================================================================================
#  NOTE: INITIAL SUGGESTION ONLY - MUST BE CUSTOMIZED
#
#     YOU MUST:
#     1. Review and update each section per YOUR use case
#     2. Customize the logic for YOUR SPECIFIC requirements
#     3. Replace example values (field names, thresholds, etc.) with your actual values
#     4. Test thoroughly before using
#
#     DO NOT use this code as-is. It will not work until you uncomment and customize it.
# =========================================================================================


# =========================================================================================
# SECTION 1: Helper function — content normalization
# =========================================================================================
# Nova messages use content as a string, a list of {"type":"text","text":"..."} chunks,
# or a dict with a "text" key. This helper normalizes all forms to a plain string.
def content_to_text(content: Any) -> str:
    """
    Normalize Nova message content to a plain string.

    Args:
        content: String, list of text chunks, or dict with "text" key

    Returns:
        Plain text string
    """
    if content is None:
        return ""
    if isinstance(content, str):
        return content
    if isinstance(content, list):
        parts: List[str] = []
        for item in content:
            if isinstance(item, str):
                parts.append(item)
            elif isinstance(item, dict) and "text" in item:
                parts.append(item["text"])
            else:
                parts.append(str(item))
        return "".join(parts)
    if isinstance(content, dict) and "text" in content:
        return content["text"]
    return str(content)


# =========================================================================================
# SECTION 2: Helper function — ground truth extraction
# =========================================================================================
# Nova reference_answer can be a dict with flexible keys (answer, label, sentiment, etc.),
# a JSON string, or a plain string.
def coerce_ground_truth(ground_truth: Union[str, Dict[str, Any], Any]) -> Optional[str]:
    """
    Extract the ground-truth answer as a string from reference_answer.

    Args:
        ground_truth: Dict, JSON string, or plain string

    Returns:
        Ground truth string, or None if not found
    """
    if ground_truth is None:
        return None

    if isinstance(ground_truth, str):
        s = ground_truth.strip()
        if not s:
            return None
        if s.startswith("{") or s.startswith("["):
            try:
                ground_truth = json.loads(s)
            except Exception:
                return s
        else:
            return s

    if isinstance(ground_truth, dict):
        for key in ("ground_truth", "answer", "label", "sentiment", "polarity", "target"):
            if key in ground_truth and ground_truth[key] is not None:
                return str(ground_truth[key])
        if len(ground_truth) == 1:
            only_val = next(iter(ground_truth.values()))
            if only_val is not None:
                return str(only_val)
        return None

    return str(ground_truth)


# =========================================================================================
# SECTION 3: Helper function — number extraction
# =========================================================================================
# TODO: UPDATE or REMOVE the helper function as per YOUR use case
# Note the below lines of code are examples and will not work for your use case
# You MUST update them to match YOUR use case
def extract_number(text: str) -> Optional[float]:
    """
    Extract numerical answer from text.
    Looks for numbers after answer keywords, or returns the last number found.

    Args:
        text: Text containing a numerical answer

    Returns:
        Extracted number as float, or None if no number found
    """
    if not text:
        return None

    # Try to find numbers after common answer keywords
    answer_patterns = [
        r'(?:equals|is|answer is|result is|=)\s*(-?\d+\.?\d*)',
        r'(?:answer|result|solution):\s*(-?\d+\.?\d*)',
    ]

    for pattern in answer_patterns:
        match = re.search(pattern, text, re.IGNORECASE)
        if match:
            try:
                return float(match.group(1))
            except ValueError:
                pass

    # Fallback: find all numbers and return the last one (likely the answer)
    pattern = r'-?\d+\.?\d*'
    matches = re.findall(pattern, text)

    if matches:
        try:
            return float(matches[-1])
        except ValueError:
            return None

    return None


# =========================================================================================
# SECTION 4: Helper function — reasoning quality
# =========================================================================================
# TODO: UPDATE or REMOVE the helper function as per YOUR use case
# Note the below lines of code are examples and will not work for your use case
# You MUST update them to match YOUR use case
def compute_reasoning_quality(response: str) -> float:
    """
    Compute reasoning quality score based on response characteristics.
    This is a simple heuristic - customize based on your needs.

    Args:
        response: The model's response text

    Returns:
        Quality score between 0.0 and 1.0
    """
    if not response:
        return 0.0

    score = 0.0

    # Check for reasoning indicators (customize these for your use case)
    reasoning_indicators = [
        'because', 'therefore', 'thus', 'since', 'so',
        'first', 'second', 'then', 'finally',
        'step', 'calculate', 'compute', 'equals'
    ]

    response_lower = response.lower()

    # Award points for reasoning indicators (max 0.55)
    indicator_count = sum(1 for indicator in reasoning_indicators if indicator in response_lower)
    score += min(indicator_count * 0.11, 0.55)

    # Award points for response length (indicates detailed reasoning, max 0.25)
    if len(response) > 30:
        score += 0.05
    if len(response) > 60:
        score += 0.1
    if len(response) > 120:
        score += 0.1

    # Award points for structured response (max 0.2)
    if '\n' in response or '.' in response:
        score += 0.2

    return min(score, 1.0)


# =========================================================================================
# SECTION 5: Helper function — answer extraction
# =========================================================================================
# TODO: UPDATE or REMOVE the helper function as per YOUR use case
# Note the below lines of code are examples and will not work for your use case
# You MUST update them to match YOUR use case
def extract_answer(response: str) -> Optional[str]:
    """
    Extract the answer from a Nova model response.
    Looks for <|begin_of_solution|>...<|end_of_solution|> blocks and \\boxed{} patterns.

    Args:
        response: The model's response text

    Returns:
        Extracted answer string, or None if not found
    """
    if not response:
        return None

    # Try solution block first
    solution_match = re.search(
        r"<\|begin_of_solution\|>(.*?)<\|end_of_solution\|>",
        response,
        re.DOTALL,
    )
    if solution_match:
        boxed = re.findall(r"\\boxed\{([^}]+)\}", solution_match.group(1))
        if boxed:
            return boxed[-1].strip()

    # Fallback: boxed anywhere
    boxed = re.findall(r"\\boxed\{([^}]+)\}", response)
    if boxed:
        return boxed[-1].strip()

    return None


# =========================================================================================
# SECTION 6: Sample reward function
# =========================================================================================
# TODO: UPDATE or REMOVE the reward function as per YOUR use case
# Note the below lines of code are examples and will not work for your use case
# You MUST update them to match YOUR use case
def reward_function(sample: Dict[str, Any], index: int) -> Dict[str, Any]:
    """
    Args:
        sample: Dictionary containing messages and reference_answer
        index: Sample index in batch

    Returns:
        Dictionary with reward scores and metrics
    """
    # ========================================================================
    # SECTION 7: Parse input
    # ========================================================================
    # TODO: UPDATE logic to parse the input as per YOUR use case
    # Note the below lines of code are examples and will not work for your use case
    # You MUST update them to match YOUR use case
    messages = sample.get('messages', [])
    ground_truth = sample.get('reference_answer', {})

    # Get the assistant's response (last message with role assistant or nova_assistant)
    response = ""
    for msg in messages:
        role = msg.get('role', '')
        if role in ('assistant', 'nova_assistant'):
            response = content_to_text(msg.get('content', ''))

    # Extract numerical answers
    predicted = extract_number(response)
    expected_str = coerce_ground_truth(ground_truth)
    expected = extract_number(expected_str) if expected_str else None

    # Compute metrics
    exact_match = 0.0
    answer_present = 0.0
    reasoning_quality = compute_reasoning_quality(response)

    if predicted is not None and expected is not None:
        exact_match = 1.0 if abs(predicted - expected) < 1e-6 else 0.0
        answer_present = 1.0

    # ========================================================================
    # SECTION 8: Compute reward scores
    # ========================================================================
    # TODO: UPDATE logic to compute aggregate score
    # Note the below lines of code are examples and will not work for your use case
    # You MUST update them to match YOUR use case
    aggregate_reward = 0.7 * exact_match + 0.3 * reasoning_quality

    # ========================================================================
    # SECTION 9: Form the metrics list
    # ========================================================================
    # TODO: UPDATE logic to compute metrics list
    # Note the below lines of code are examples and will not work for your use case
    # You MUST update them to match YOUR use case
    metrics = [
        {
            'name': 'exact_match',
            'value': float(exact_match),
            'type': 'Reward'
        },
        {
            'name': 'answer_present',
            'value': float(answer_present),
            'type': 'Metric'
        },
        {
            'name': 'reasoning_quality',
            'value': float(reasoning_quality),
            'type': 'Metric'
        }
    ]

    # ========================================================================
    # SECTION 10: Return output
    # ========================================================================
    # TODO: UPDATE the return statement to return YOUR output
    # UPDATE the key before creating the evaluator
    # Note the below lines of code are examples and will not work for your use case
    # You MUST update them to match YOUR use case

    return {
        'id': str(sample.get('id', f'sample-{index:03d}')),
        'aggregate_reward_score': float(aggregate_reward),
        'metrics_list': metrics
    }

def lambda_handler(event: Dict[str, Any], context: Any) -> Dict[str, Any]:
    """
    AWS Lambda Handler for reward function.
    SageMaker Nova RLVR invokes this with a bare list of samples and expects
    a bare list of {id, aggregate_reward_score, ...} dicts in return.
    """
    # Event is a bare list of samples
    batch = event if isinstance(event, list) else []

    results = []
    for i, sample in enumerate(batch):
        try:
            result = reward_function(sample, i)
            results.append(result)
        except Exception as e:
            results.append({
                'id': str(sample.get('id', f'sample-{i:03d}') if isinstance(sample, dict) else f'sample-{i:03d}'),
                'aggregate_reward_score': 0.0,
                'metrics_list': []
            })

    return results

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 or AWS Labs.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download finetuning.zip