Skip to content

About

A configurable utility for Synthetic Data Knowledge Distillation: turning LLM prompts into efficient, serverless classification microservices.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Text Classifier Distillation

A configurable utility for Synthetic Data Knowledge Distillation: turning LLM prompts into efficient, serverless classification microservices.

Don't Pay Einstein to Sort Mail

LLMs are great teachers, but expensive (and crappy) workers.

We like to use LLMs for classification because it's easy. You write a prompt, you get an answer. No training data, no MLOps and model weight files, no headache. It is the path of least resistance.

But running that LLM in production is a different story. You pay for billions of parameters for every simple "Yes/No" decision. You struggle with variable latency (1-3s). You write complex regex to parse "Sure! Here is the JSON..." outputs. Sometimes you have to throw the completion out and re-run the whole LLM request.

This tool gives you the best of both worlds:

  1. The Dev Experience of an LLM: You still just write prompts (in YAML).
  2. The Runtime of a BERT model: You get a deterministic, sub-300ms, auto-scaling microservice.

This tool automates Offline Knowledge Distillation. It uses the LLM to create a dataset, then trains a specialized model that does exactly one thing extremely well.

In fact, it does four things well (or however many tasks you define). The student model uses a shared MobileBERT encoder with task-specific heads. This architecture scales efficiency dramatically: instead of running a massive LLM for every task, or making multiple API calls, you get predictions for all your tasks simultaneously in one sub-300ms forward pass.

The Pipeline:

  1. You write a prompt: "Is the input text a question about image processing?" (Stored in YAML, obviously.)

    Positive: "Generate questions about image processing, computer vision, blurring, edge detection..." Negative: "Generate questions about OTHER topics like databases, web development, or system administration..."

  2. The Teacher generates the curriculum: The pipeline invokes GPT-4o-mini to generate thousands of synthetic examples based on your positive and negative prompts.

    • ✅ Positive: "How do I apply a Gaussian blur to an image using OpenCV?"
    • ❌ Negative: "What is the difference between SQL and NoSQL databases?"

    This creates a labeled dataset without you lifting a finger.

  3. The Cloud does the heavy lifting: Your data flies to S3, triggering a SageMaker training job on a powerful GPU. You don't need a GPU on your laptop.

  4. Infrastructure appears automatically: The code spins up a serverless API endpoint using Infrastructure as Code (AWS CDK).

  5. You get a production API: Minutes later, you have a live, auto-scaling endpoint that responds in ~270ms and scales down to zero cost when nobody is using it.

The Payoff: You get an API that is 10x faster and 10x cheaper than the LLM that created it, with better privacy because data never leaves your AWS account.

Teacher (LLM) Student (Distilled)
Latency 1.5s - 3.0s ~270ms
Consistency Stochastic (Varies) Deterministic
Throughput Rate Limited Auto-scaling
Idle Cost $0.00/hr $0.00/hr
Active Cost ~$0.20 / 1M tokens ~$0.02 / 1000 reqs

The Bottom Line: By shifting from a general-purpose generative model to a specialized discriminative one, you gain real-time latency suitable for interactive UI applications, while replacing the variable, stochastic nature of LLM outputs with a stable, deterministic API contract.


The Concept: Teaching via Data

This project is a practical implementation of Synthetic Data Knowledge Distillation. It provides a framework to distill the specific capabilities of a large "teacher" model (like GPT-4o-mini) into a compact, efficient "student" model (MobileBERT) entirely through the medium of synthetic data.

Often referred to as teaching via data, this approach allows for offline knowledge transfer without direct model interaction. Unlike traditional online distillation where models run in parallel, this is an offline distillation process. The teacher (a decoder-only generative model) creates a high-quality curriculum of training data based on your specifications. The student (an encoder-only discriminative model) then consumes this data to master specific classification tasks. The two models have vastly different architectures and never interact directly; they are bridged solely by the synthetic data pipeline.

How It Works: The Pipeline

This system acts as a Domain-Specific Language (DSL) for creating high-performance text classifiers. You define what you want to classify using natural language prompts, and this utility handles the how.

High-Level Overview

graph TB
    subgraph "Teacher Phase (Data Generation)"
        A[DSL Config] --> B[Teacher LLM]
        B --> C[Synthetic Dataset]
    end

    subgraph "Student Phase (Distillation)"
        C --> D[SageMaker Training]
        D --> E[Student Model<br>MobileBERT]
    end

    subgraph "Deployment Phase (IaC)"
        E --> F[Model Artifact]
        F --> G[Serverless Endpoint]
    end

    style A fill:#e1f5ff
    style E fill:#d4edda
    style G fill:#fff3cd
Loading

The final artifact is a production-ready serverless microservice on AWS SageMaker.

Quick Start

Prerequisites

  • Python 3.9+
  • AWS account with CLI configured (aws configure)
  • Node.js 14+ (for AWS CDK)
  • OpenAI API key

Installation

git clone <repo>
cd text-classifier-distillation

# Install Python dependencies
pip install -r requirements.txt

# Install CDK dependencies
cd cdk && pip install -r requirements.txt && cd ..

# Setup environment
cp .env.example .env
# Edit .env and add your OPENAI_API_KEY

Run the Complete Pipeline

This single command orchestrates the entire distillation process: generating data, training the student model, and deploying the API.

# Run the full pipeline and log output
python scripts/run_pipeline.py 2>&1 | tee pipeline.log

# Monitor progress in another terminal:
tail -f pipeline.log

What happens next:

  1. Data Generation: GPT-4o-mini generates thousands of synthetic examples based on your task definitions (~12 min).
  2. Distillation: A multi-head MobileBERT model is trained on this data using AWS SageMaker (~35 min).
  3. Deployment: The trained model is deployed as a serverless endpoint with public HTTP API via CloudFormation (~4 min).

Total time: ~50 minutes

Final endpoint performance: ~270ms average response time

Total cost: < $1.00 (approx $0.45 for training + $0.30 for data generation)

Test the Deployed Endpoint

Once deployed, you have a live API endpoint that can be accessed in two ways:

Access Method 1: HTTP API via API Gateway (Public, No Auth Required)

Perfect for public demos, web applications, or anywhere you don't want to manage AWS credentials.

curl -X POST https://YOUR-API-ID.execute-api.us-west-2.amazonaws.com/prod/classify \
  -H 'Content-Type: application/json' \
  -d '{"text": "How do I resize an image in Python?"}'

Performance: ~460ms average response time Pros: No AWS credentials needed, works from any HTTP client (browsers, mobile apps, etc.) Cons: Additional ~200ms latency compared to direct SageMaker access

Access Method 2: Direct SageMaker Endpoint (Faster, Requires AWS Auth)

Best for real-time use cases where every millisecond counts, or when integrating with existing AWS infrastructure.

aws sagemaker-runtime invoke-endpoint \
  --endpoint-name multi-task-classifier \
  --region us-west-2 \
  --body '{"text": "How do I resize an image?"}' \
  --content-type 'application/json' \
  output.json && cat output.json

Performance: ~270ms average response time (skips API Gateway overhead) Pros: Maximum performance, native AWS integration Cons: Requires AWS credentials and SDK/CLI

Python SDK example:

import boto3
import json

runtime = boto3.client('sagemaker-runtime', region_name='us-west-2')
response = runtime.invoke_endpoint(
    EndpointName='multi-task-classifier',
    ContentType='application/json',
    Body=json.dumps({'text': 'Your text here'})
)
result = json.loads(response['Body'].read())
print(result)

Run Automated Tests (Compares Both Methods)

python scripts/test_endpoint.py --endpoint-name multi-task-classifier

This will test both access methods, warm up both endpoints, run 40 test cases through each, and provide a performance comparison.

Configuration

You define your classification tasks in config/tasks.yaml. This is the "source code" for your classifier.

# Define the Teacher Model
llm:
  generation_model: gpt-4o-mini
  temperature: 0.7

# Define the Student Model Architecture
model:
  base_model: google/mobilebert-uncased
  max_length: 128

# Define Your Tasks (The Curriculum)
tasks:
  - id: image_processing_question
    description: "Is the input text a question about image processing?"
    positive_instruction: |
      Generate questions about image processing operations
      like blurring, filtering, edge detection, resizing, etc.
    negative_instruction: |
      Generate questions about other programming topics
      (databases, web dev, ML, etc.)
    examples_per_class: 1000

  - id: urgent_request
    description: "Is the input text expressing urgency?"
    positive_instruction: |
      Generate messages with words like ASAP, immediately, urgent, etc.

Advanced Usage

Pipeline Idempotency

The pipeline is fully idempotent - it can be stopped and resumed without losing progress:

  • Data generation: Checks existing files and generates only what's missing
  • Training: Saves completed job to output/.training_job and reuses it
  • Deployment: Updates existing endpoint with new model

Simply re-run the same command to resume after interruption:

python scripts/run_pipeline.py 2>&1 | tee pipeline.log

Force Retraining

To train a new model (ignoring the cached training job):

python scripts/run_pipeline.py --force-training 2>&1 | tee pipeline.log

To force from scratch completely, delete cached files:

rm -rf data/ output/
python scripts/run_pipeline.py 2>&1 | tee pipeline.log

Regenerate Data for One Task

If you update the prompt for a specific task, you can regenerate just that part:

python scripts/run_pipeline.py --regenerate-task image_processing_question

Skip Data Generation (Advanced)

The pipeline automatically skips data generation if data already exists. To explicitly skip the entire data generation stage (useful for testing or when working with manually prepared data):

python scripts/run_pipeline.py --skip-data-generation

A Warning on Synthetic Data

With great power comes great risk of stupidity.

Let's be clear: we are giving ourselves a tool that lets us generate training data out of thin air. If that sounds too good to be true, it's because it usually is. When we generate our own data, we become the Gods of that tiny universe—and if we screw up the creation myth, the whole world is broken.

It allows for incredibly rapid prototyping, but also incredibly rapid overfitting. Since we are generating thousands of examples from the same source (the LLM) based on the same few prompts, our data lacks the messy variance of the real world. We call it "Synthetic Data Knowledge Distillation", but we could also call it "Automating Our Own Mistakes at Scale". The problem isn't just the LLM's biases; it's that every subtle flaw in our prompt—length distributions, punctuation habits, vocabulary choices—becomes a hard rule for our classifier.

We aren't claiming to be experts at preventing this (hold my beer...), but we can tell you that there are infinite ways to screw this up that you haven't even thought of yet.

A classic failure mode—which we definitely didn't encounter while building this (okay, we totally did)—is the "Clever Hans" effect (or shortcut learning). For example, if your prompt accidentally causes the LLM to generate long, complex sentences for "positive" examples and short, simple sentences for "negative" examples, your student model may learn to classify based on length rather than meaning. You'll get 99% accuracy in testing and 0% utility in production.

Recommendation: Move to AI-Curated Data For production systems, the safest path is to graduate from generating data to curating data. Instead of asking the LLM to invent user queries, feed it real anonymized logs from your application and ask it to find and label the examples that match your criteria. This "AI-Curated" approach grounds your model in the messy reality of actual user behavior while still automating the expensive labeling process.

Contributing

Contributions are welcome! Please see AGENTS.md for architectural details intended for AI collaborators.

License

MIT License - see LICENSE file for details.

text-classifier-distillation

About

A configurable utility for Synthetic Data Knowledge Distillation: turning LLM prompts into efficient, serverless classification microservices.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages