Skip to main content
Transfer knowledge from large teacher models to smaller, low-cost, more efficient student models while preserving performance. Knowledge distillation enables you to create compact models that maintain the reasoning capabilities of larger models. This tutorial demonstrates the complete workflow using GSM8K mathematical reasoning as our example task.
Qwen2.5-7B (52% accuracy) + DeepSeek-V3 knowledge → Optimized 7B model (70% accuracy, structured format)

Course Overview

This tutorial demonstrates a systematic two-stage knowledge distillation pipeline: Stage 1 - SFT (Format Learning):
  1. Generate training data with consistent output formatting
  2. Train student model to internalize structured response patterns
  3. Demonstrate format learning without explicit instructions
Stage 2 - RFT (Accuracy Improvement):
  1. Build reward system based on answer correctness
  2. Apply reinforcement learning to improve reasoning within learned format
  3. Show accuracy gains while maintaining consistent structure
Why This Two-Stage Approach Works:
  • SFT: Excels at learning structural patterns and making them default behavior
  • RFT: Excels at optimizing content quality through reward-based learning
  • Together: Create models that are both well-formatted AND more accurate
Run this tutorial interactively in Google Colab: Open Notebook

Chapter 1: Environment Setup

Requirements:
  • Fireworks AI account with API access
  • Basic familiarity with fine-tuning concepts
  • Understanding of train/test splits for valid evaluation

API Configuration

What’s Happening Here:
  • Fireworks SDK: Simplified interface for model deployment and fine-tuning
  • Serverless Models: Pre-deployed models you can use immediately
  • API Key: Authenticates your requests and tracks usage

Chapter 2: Dataset Preparation and Analysis

Why GSM8K?
  • Standard Benchmark: Widely used for evaluating mathematical reasoning
  • Clear Evaluation: Numerical answers are easy to check for correctness
  • Appropriate Difficulty: Challenging enough to demonstrate knowledge transfer
Why We Need Proper Train/Test Splits Critical for Valid Evaluation: Using the same data for training and testing leads to inflated results that don’t reflect real-world performance. GSM8K provides standard splits that enable fair comparison with other research.

Load GSM8K Dataset

Example GSM8K Problem:
Why This Format Matters: The #### 18 format provides the ground truth answer we need for automated evaluation. We’ll extract this pattern to check model correctness. Process Dataset for Training and Evaluation

Chapter 3: Model Setup

Deploy Your Student Model

Model Selection: We’re using Qwen2.5-7B as our student model because:
  • Right Size: Large enough to learn complex patterns, small enough to be efficient
  • Strong Base: Pre-trained on diverse data including mathematical content
  • Cost-Effective: Significantly cheaper to run than larger models

Testing Baseline Model Behavior

Expected Baseline Behavior: Unstructured, verbose responses without consistent formatting patterns. Actual Baseline Model Outputs: Output 1:
Output 2:

Chapter 4: Stage 1 - Supervised Fine-Tuning (SFT)

Generate Formatted Training Data with Teacher Model

Why Use a Teacher Model

The Knowledge Transfer Principle Rather than learning math reasoning from scratch, we’ll have a powerful model (DeepSeek-V3) solve problems step-by-step, then train our small model to mimic those high-quality solutions. Why DeepSeek-V3:
  • Strong mathematical reasoning (>90% accuracy on GSM8K)
  • Clear step-by-step explanations that provide good learning examples
  • Consistent output format when given proper instructions
  • Cost-effective for generating training data (no deployment required)
  • Available as serverless model on Fireworks AI platform
Two-Stage Data Strategy: We’ll generate one high-quality dataset from our teacher model and adapt it for both training stages:
  • Stage 1 (SFT): Use teacher responses as training targets to learn format patterns
  • Stage 2 (RFT): Use the same problems with ground truth labels for reward-based learning

Defining Our Target Format

Why Structured Output?
  • Consistency: Every response follows the same pattern
  • Parseability: Easy to extract answers programmatically
  • Debugging: Clear separation of reasoning and results
  • Production Ready: Reliable format for downstream applications
  • Unique: Different from typical model outputs

Teaching the Teacher Model Our Format

Strategy: We’ll use a system prompt to teach our teacher model (DeepSeek-V3) to use our desired format, then capture those formatted responses as training data.
Actual teacher model response:

Generating High-Quality Training Data

The Process:
  1. Take problems from GSM8K training set
  2. Have teacher model solve them using our format
  3. Verify teacher got the right answer
  4. Create training examples from successful solutions
Actual result:
Why Use a Teacher Model When We Already Have Answers? You might be wondering: “Wait, the GSM8K dataset already has the correct answers. Why do we need a teacher model to generate new ones?” Great question! This tutorial uses GSM8K because it provides a controlled environment where we can verify our teacher model’s accuracy. But in real-world applications, you typically don’t have the correct answers for your specific domain. The Knowledge Distillation Advantage The Pattern: In production, you have:
  • Questions/Inputs: Your domain-specific problems
  • No Perfect Answers: No ground truth responses
  • Solution: Use a powerful teacher model to create accurate high-quality training data

Real-World Knowledge Distillation Use Cases

Common Scenarios Where You Need Teacher Models

1. Legal Document Analysis
  • Challenge: No ground truth for contract clause interpretation
  • Teacher Solution: Use teacher models to generate expert-level legal analyses
2. Code Review Automation
  • Challenge: No perfect code review comments for your codebase
  • Teacher Solution: Use teacher models to generate code review insights
4. Customer Support Chatbot
  • Challenge: No ideal responses for company-specific questions
  • Teacher Solution: Use teacher models for customer service responses
6. Content Moderation
  • Challenge: No labeled decisions for edge-case content
  • Teacher Solution: Use teacher models to generate moderation reasoning and decisions
  • Kimi K2: Great general purpose model, especially for agentic use cases.
  • Qwen3 Coder 480B: Strong coding model, especially for one-off coding tasks.
  • Qwen3 235B (instruct): Good general purpose model. Has strong world knowledge for tasks like classification.
  • Qwen3 235B (thinking): Good reasoning model for agentic tasks and tasks that require multi-step planning.
  • Open AI GPT OSS 120B: OpenAI’s open-weight model, with strong reasoning and tool use capabilities. Runs efficiently on single 80GB GPU and achieves near-parity with o4-mini on core reasoning benchmarks.
  • DeepSeek V3: Powerful MoE model with 671B parameters (37B active) that rivals GPT-4o and Claude 3.5 Sonnet. Strong performance in math, coding, and reasoning tasks.
  • DeepSeek R1: Open-source reasoning model that rivals OpenAI o1. Trained using pure reinforcement learning. Shows explicit chain-of-thought reasoning process and excels at complex mathematical and logical problems.

Uploading Training Data to Fireworks

SFT Training Configuration

Supervised Fine-Tuning Job:
  • Model: Qwen2.5 7B
  • Dataset: dataset (Your uploaded dataset)
  • Epochs: 5-8 (format learning needs repetition)
  • Learning Rate: 1e-5
Critical Parameters for Format Learning:
  • Higher Learning Rate: Needed to override existing response patterns
  • More Epochs: Format internalization requires repetition
  • Larger Model: 3B+ has capacity to learn complex structural patterns
  • No System Prompts in Training: Teaches default behavior, not instruction-following

Running the SFT Training Job

Deploying the Fine-Tuned Model

Chapter 5: Evaluating SFT Results

Testing Format Learning Success

The Critical Test: Can our fine-tuned model use the target format WITHOUT being explicitly told to do so?
Actual output:
SUCCESS! SFT taught the model to automatically use the target format! This demonstrates how SFT can make structural patterns the model’s default behavior. If your format learning is incomplete, consider:
  • More training examples (aim for 1000+)
  • Higher learning rate (try 1e-4)
  • More epochs (try 5-8)
  • Verify training data format consistency
Now that we have consistent, structured responses, we can focus purely on improving the quality of the content within that structure. This is where Stage 2 (RFT) shines - optimizing for correctness while maintaining our learned formatting.

Understanding SFT’s Strengths and Limitations

Strengths demonstrated
  • Consistent output formatting
  • No system prompts needed
  • Internalized behavior patterns
Limitations to address
  • Accuracy may not improve dramatically
  • Only mimics teacher, doesn’t generalize
  • No feedback loop for corrections

Chapter 6: Stage 2 - Reinforcement Fine-Tuning (RFT)

Now that our model consistently uses the [WORK] and [RESULT] format automatically (without being told), we can apply RFT to improve the accuracy of answers within that structure.

Why Add Reinforcement Learning

Beyond Imitation: While SFT teaches the model to mimic the teacher’s style, RFT optimizes for correctness. The model learns to:
  • Prefer reasoning paths that lead to correct answers
  • Self-correct when making mistakes
  • Develop confidence in its mathematical reasoning
How RFT Works: Instead of just copying teacher responses, RFT gives the model a reward (+1) for correct answers and penalty (0) for wrong answers, encouraging the model to find its own path to the right solution. RFT Advantages with SFT Foundation:
  • Easy reward calculation from [RESULT] tags
  • Maintains learned formatting while optimizing correctness

Creating the RFT Dataset

Strategy: Reuse the same problems our teacher model solved correctly during SFT generation, but format them for reinforcement learning.
This is what an RFT training data point looks like:

Understanding Reward Kit and Evaluators

What is Reward Kit?
Reward Kit is currently being deprecated. Please check out our latest Reinforcement Fine-Tuning guide.

Setting Up RFT Training (Manual Dashboard Configuration)

Due to the complexity of reinforcement learning setup, we’ll use the Fireworks dashboard for the final configuration steps.

Step 1: Upload the RFT Evaluator

  1. Navigate to Evaluators
  2. Create New Evaluator
    • Click “Create Evaluator”
    • Evaluator Name: kd-rft-evaluator
  3. Configure Dataset
    • Select “Select an existing dataset”
    • Choose the kd-rft-dataset you uploaded earlier
  4. Add Evaluator Code
    • Choose “Start from scratch”
    • Click “Next”
    • In the code editor, delete any existing code
    • Copy and paste the complete code from kd-rft-evaluator.py
  5. Save Evaluator
    • Click “Save Evaluator”
    • Your evaluator is now ready for RFT training

Step 2: Create RFT Training Job

  1. Navigate to Fine-Tuning
    • Go to the Fine-Tuning tab in the dashboard
    • Click “Fine-Tune a Model”
    • Select “Reinforcement” tab
  2. Configure Training Job Model Selection:
    • Select your SFT-trained model
    • Use job.output_model from your SFT job to obtain SFT model name (e.g., accounts/your-account/models/kd-sft-model)
    Dataset:
    • Select kd-rft-dataset from the dropdown
    Evaluator:
    • Select kd-rft-evaluator (the one you just created)
    Training Settings:
    • Rollout Settings: Leave as default values
    • Model Output Name:
      • Option 1: Leave blank for auto-generated name
      • Option 2: Enter custom name (e.g., kd-rft-model)
    • Other Hyperparameters: Leave as defaults
  3. Launch Training
    • Review your configuration
    • Click “Create Job”
    • Important: Note the output model name for evaluation later
  4. Monitoring
  • Track progress in the dashboard’s Fine Tuning section.
  • Once the job status is Completed, you can deploy your model.

Deploying the Fine-Tuned Model

Chapter 7: Evaluate Complete Knowledge Distillation Pipeline

Now that we’ve completed our knowledge distillation pipeline, it’s time to evaluate our results. But first, we need robust evaluation tools that can handle the complexity of comparing different models fairly. Why We Need Sophisticated Evaluation Tools The Challenge: We now have models that may respond in different formats:
  • Baseline model: Natural language, inconsistent formatting
  • RFT model: Structured [WORK]/[RESULT] format
The Problem: Simple string matching won’t work because:
We need evaluation tools that can:
  • Extract answers from any response format
  • Normalize numbers (handle commas, decimals, currency)
  • Track multiple metrics (accuracy, extraction success)
Building Our Evaluation System Let’s build two essential functions that will power our model comparisons: Answer Extraction Engine
Evaluation System

Test Model Performance

Actual Results Analysis

Course Summary and Key Takeaways

What We Demonstrated

1. SFT for Internalized Format Learning:
  • Training Strategy: Include format examples without system prompts in training data
  • Testing Strategy: No system prompts needed - format is internalized
  • Result: Model automatically uses [WORK]/[RESULT] structure as default behavior
  • Key Insight: SFT teaches “how to respond” by making patterns the model’s natural behavior
2. RFT for Accuracy Improvement:
  • Foundation: Builds on SFT model
  • Optimization: Reward-based learning improves content quality
  • Result: Significantly improves reasoning accuracy
  • Key Insight: RFT optimizes “what to respond with”
3. Two-Stage Pipeline Synergy:
  • Stage 1 (SFT): Establishes reliable, consistent response structure
  • Stage 2 (RFT): Optimizes content quality within that structure
  • Combined Result: Models that are both well-formatted AND accurate

Practical Applications

This knowledge distillation approach is valuable for:
  • API Integrations: Reliable output parsing + improved accuracy
  • Structured Reasoning Tasks: Clear thinking process + better results
  • Production Pipelines: Consistent format + higher quality content
  • Evaluation Systems: Easy answer extraction + improved performance
  • Cost Optimization: Small models with large model capabilities

Expected Resources

  • Cost: ~Costs apply for API calls, deployments and training jobs

Conclusion

This tutorial demonstrated how to systematically apply knowledge distillation using Fireworks AI to create models that combine the structural reliability of supervised learning with the performance optimization of reinforcement learning. Key Success Factors:
  1. Clear separation of concerns: SFT for structure, RFT for accuracy
  2. Consistent evaluation methodology: Test without system prompts to measure true learning
  3. Building on foundations: RFT builds on SFT rather than starting from scratch
  4. Quality training data: High teacher model accuracy and format consistency
The result is a compact, efficient model that maintains the reasoning capabilities and output structure of much larger models, making it suitable for production deployment at significantly lower cost and latency. Next Steps: Apply this methodology to your own domain-specific tasks by:
  1. Defining appropriate outputs for your use case
  2. Generating high-quality teacher demonstrations
  3. Fine tuning
  4. Evaluating performance improvements
This systematic approach to knowledge distillation enables you to create specialized, efficient models that retain the capabilities of their larger teachers while being practical for real-world deployment. Questions or feedback? Reach out to us on Discord.