← Back to Pull requests

Add speculative decoding training via speculators library #88

Open
Maxusmusti opened this pull request with 650 lines diff across 8 files
View on GitHub
Maxusmusti Maxusmusti commented on Jun 05, 2026 21:47 UTC
Author

Summary

Adds a new speculative_decoding algorithm that wraps the speculators library to train Eagle3 (and other) draft models for speculative decoding inference acceleration.

  • New algorithm: speculative_decoding with speculators backend

  • Supports Eagle3, DFlash, MTP, and PEagle speculator architectures

  • 4 pipeline modes: offline, online, train_only, data_only

  • Managed or user-provided vLLM for hidden state extraction

  • GPU allocation: vllm_gpu_ids (data-parallel vLLM) and training_gpu_ids (FSDP training)

  • Single-GPU training via training_gpu_id also supported

  • Convenience functions: train_speculator(), eagle3(), prepare_speculator_data()

  • Compatible with speculators 0.5.0+ and vLLM 0.20.0+
  • Closes #86

    How It Works

    Speculative decoding trains a small "draft" model that predicts tokens using hidden states from intermediate layers of a large "verifier" model. The pipeline has distinct stages:

    1. Data prep — tokenize dataset, build loss masks, compute token frequencies
    2. Hidden state extraction — run the verifier through vLLM to extract intermediate hidden states
    3. Training — train the draft model on the extracted hidden states

    Pipeline Modes

    Offline (default) — bulk generate hidden states, then train from disk


    from training_hub import train_speculator
    
    result = train_speculator(
        verifier_name_or_path="Qwen/Qwen3-8B",
        ckpt_output_dir="./eagle3_output/checkpoints",
        data_path="sharegpt",
        mode="offline",
        speculator_type="eagle3",
        vllm_gpu_ids=[0, 1],       # vLLM data-parallel on 2 GPUs
        training_gpu_ids=[2, 3],   # FSDP training on 2 GPUs
        epochs=3,
        draft_vocab_size=32000,
        max_samples=5000,
    )
    

    Online — generate hidden states on-demand during training


    result = train_speculator(
        verifier_name_or_path="Qwen/Qwen3-8B",
        ckpt_output_dir="./eagle3_output/checkpoints",
        data_path="sharegpt",
        mode="online",
        speculator_type="eagle3",
        vllm_gpu_ids=[0, 1],
        training_gpu_ids=[2, 3],
        epochs=3,
        draft_vocab_size=32000,
        max_samples=5000,
    )
    

    With user-managed vLLM endpoint (offline or online)


    # User launches vLLM separately:
    #   CUDA_VISIBLE_DEVICES=0,1 python speculators/scripts/launch_vllm.py \
    #       Qwen/Qwen3-8B -- --data-parallel-size 2 --port 8234
    
    result = train_speculator(
        verifier_name_or_path="Qwen/Qwen3-8B",
        ckpt_output_dir="./eagle3_output/checkpoints",
        data_path="sharegpt",
        mode="offline",  # or "online"
        speculator_type="eagle3",
        vllm_endpoint="http://localhost:8234/v1",
        training_gpu_ids=[2, 3],
        epochs=3,
        draft_vocab_size=32000,
        max_samples=5000,
    )
    

    Train-only — from pre-existing hidden states


    result = train_speculator(
        verifier_name_or_path="Qwen/Qwen3-8B",
        ckpt_output_dir="./eagle3_output/checkpoints",
        mode="train_only",
        speculator_type="eagle3",
        data_output_dir="./existing_data",
        hidden_states_path="./existing_data/hidden_states",
        training_gpu_ids=[2, 3],
        epochs=3,
        draft_vocab_size=32000,
    )
    

    Single-GPU training


    result = train_speculator(
        verifier_name_or_path="Qwen/Qwen3-8B",
        ckpt_output_dir="./eagle3_output/checkpoints",
        data_path="sharegpt",
        mode="offline",
        speculator_type="eagle3",
        vllm_gpu_ids=[0],
        training_gpu_id=1,         # single GPU (in-process, no torchrun)
        epochs=3,
        draft_vocab_size=32000,
        max_samples=5000,
    )
    

    vLLM Management

    Two options for the vLLM server used for hidden state extraction:

    | Option | How | When to use |
    |--------|-----|-------------|
    | Managed | Set vllm_gpu_ids=[0, 1] | Default — backend handles lifecycle |
    | User endpoint | Set vllm_endpoint="http://..." | Custom vLLM config, different node, or shared server |

    Multiple GPUs for vLLM use data parallelism — separate vLLM instances per GPU, each handling different extraction requests in parallel.

    Training Modes

    | GPUs | How | What happens |
    |------|-----|-------------|
    | Single GPU | training_gpu_id=0 | In-process training via speculators Trainer |
    | Multi-GPU | training_gpu_ids=[2, 3, 4, 5] | torchrun subprocess with PyTorch FSDP |

    Multi-GPU training uses FSDP (Fully Sharded Data Parallel) to shard the draft model across GPUs, with DistributedCheckpointer for saving.

    Key Parameters

    | Parameter | Default | Description |
    |-----------|---------|-------------|
    | verifier_name_or_path | required | HF model ID or path to the verifier model |
    | ckpt_output_dir | required | Directory for checkpoints |
    | data_path | — | Dataset path, HF ID, or "sharegpt" |
    | mode | "offline" | offline, online, train_only, data_only |
    | speculator_type | "eagle3" | eagle3, dflash, mtp, peagle |
    | draft_vocab_size | auto | Draft model vocabulary size |
    | epochs | 3 | Training epochs |
    | lr | 1e-4 | Learning rate |
    | total_seq_len | 2048 | Sequence length |
    | vllm_gpu_ids | — | GPUs for managed vLLM data-parallel (e.g. [0, 1]) |
    | training_gpu_id | 0 | GPU for single-GPU training |
    | training_gpu_ids | — | GPUs for multi-GPU FSDP training (e.g. [2, 3]) |
    | max_samples | — | Max samples from dataset |
    | datagen_concurrency | 4 * num_vllm_gpus | Concurrent extraction requests |

    Output

    Checkpoints are saved as full HF-compatible models via save_pretrained():

    checkpoints/
      0/
        config.json
        model.safetensors
        optimizer_state_dict.pt
        val_metrics.json
      checkpoint_best -> 0
    

    The trained model can be loaded with:

    from speculators import SpeculatorModel
    model = SpeculatorModel.from_pretrained("./checkpoints/0")
    

    Dependencies

  • speculators>=0.5.0 — core training library (lazy import, not required at install time)

  • vllm>=0.20.0 — only needed for hidden state extraction (not training)

  • torch, transformers, safetensors — standard ML stack
  • Note: For offline/data_only modes, speculators must be installed from source (editable) so the scripts/ directory is available, or set SPECULATORS_SCRIPTS_PATH env var to point to the scripts directory.

    Test plan

    Tested with speculators 0.5.0 + vLLM 0.20.0 on 8x H100 (driver 580, CUDA 13.0):

    Single-GPU (all passed):

  • Offline + managed vLLM

  • Offline + user endpoint

  • Online + managed vLLM

  • Online + user endpoint
  • Multi-GPU — 2x vLLM (data-parallel) + 2x training (FSDP) (all passed):

  • Offline + managed vLLM

  • Offline + user endpoint

  • Online + managed vLLM

  • Online + user endpoint
  • Other:

  • Train-only mode from pre-generated hidden states

  • Checkpoint loading with SpeculatorModel.from_pretrained()

  • Val metrics returned in result dict

  • API compatibility with speculators 0.5.0 and newer versions
  • 🤖 Generated with Claude Code

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: None requested Review duration: 257807m
    All Vouch review confidence checks passed
    Residual risk 0.44 = Change Risk (0.76) × (1 − Review Confidence (0.42)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.76 · 650 lines diff across 8 files
    0.76
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 10%
    42%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    No Reviewer Assigned no_reviewer_assigned
    0.120
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    1 comments
    "Review active on #88"
    general weight: 0.35
    Reviewers
    None requested
    Assignees
    Maxusmusti Maxusmusti
    Labels
    risk: medium confidence: 42.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 76% (HIGH) · Higher = larger blast radius
    76%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 42.2% · Lower = rushed or shallow review
    42.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 43.9% · Moderate risk
    43.9%