← Back to Pull requests

feat: classifier_sft — a convention-based decision/classification-head harness #160

Closed
unknown closed this pull request without merging on Nov 12, 2026 19:03 UTC
View on GitHub
unknown unknown commented on Oct 23, 2026 21:04 UTC
Author

Summary

A classifier_sft algorithm: a thin, convention-based trainer that fine-tunes a decision/classification head on any recognized backbone — covering the growing OSS "decision model" space (Laya-class models) without vendoring packages or per-model code branches. Distinct from embedding_sft (contrastive embedding space); this trains a head and produces per-class logits (calibration is an eval-time step). Best choice for a fixed, known label set.

Design: extend by convention + config, not integrations

Layer 1 — task selector over native HF Auto classes (the decision primitives):
| task | Auto class | use |
|---|---|---|
| sequence_classification (default) | AutoModelForSequenceClassification | fixed-label classification, yes/no |
| multiple_choice | AutoModelForMultipleChoice | pick-one-of-K (dynamic options per example) |
| token_classification | AutoModelForTokenClassification | span / entity extraction (GLiNER-style) |

Layer 2 — custom models out-of-the-box, vendoring nothing:

  • trust_remote_code + revision pinning → a custom architecture whose hub repo ships its own classification-head code via auto_map (works when that code supports the installed transformers version; see the out-of-the-box sweep below).

  • model_class (dotted path) → a backbone distributed as a pip package (e.g. Laya) loads if the user installs it; this package takes on no dependency.

  • loss_fn (dotted path) → a custom loss_fn(logits, labels) callable or a Trainer subclass.
  • Every extension point is a stable HF convention or a user-supplied import — coverage grows with the ecosystem at flat maintenance; nothing hard-coded expires.

    Backbones: encoders full fine-tune; decoders via LoRA (use_peft). String labels auto-encoded to ints; checkpoint saves id2label/label2id + task (label_mapping.json) → inference-ready.

    Validation (GA stack: transformers 5.17.0, torch 2.13.0, peft 0.20.0)

  • Unit suite: 37 classifier_sft tests pass in the GA image — incl. real-PEFT LoRA on a tiny config-built ModernBERT for sequence + token classification (no mocks), padded-choice attention + token_type_ids collation, custom-loss masking, nested pad_token_id, column / negative / out-of-range label validation, loss-normalization opt-out, metrics entry, CLI wiring.

  • Review harness (one case per reported issue, run before → after): variable-K multiple-choice NaN tensors 138 → 0; grad-accumulation (gas=4 vs 1) grad/loss ratio 4.00× → 1.00×; use_peft on ModernBERT (seq + token classification) crash → trains; Qwen3.5-0.8B + use_peft pad-token crash → fits its training set (1.00); custom 2-arg loss_fn on mixed-K multiple choice saw padded choices → masked; BERT multiple choice token_type_ids dropped → kept; negative label opaque CUDA assert → clear error (token-cls -100 still allowed); training_metrics.jsonl missing → written (strict JSON); seed → bit-identical (CPU); column fallback/collision → named error / works; token-cls max_length warnings → 0.

  • Learning, not just finite: variable-K multiple-choice reaches 1.00 held-out accuracy (chance ≈0.33).

  • Banking77 (77 intents, ModernBERT, 10 epochs): acc 0.9373 / macro-F1 0.9372 at lr 5e-5 (ECE 0.034 → 0.013 after temperature scaling); independently reproduced by @xingliu-netizen at lr 2e-5 over 4 seeds: 0.9299 ± 0.0032.

  • Decoder + LoRA: Qwen2.5 and Qwen3.5 + use_peft both fit their training sets; PEFT's per-architecture targets are kept where they exist, else all-linear with the head excluded.

  • CLI: thub classifier-sft --use-peft true --lora-target-modules Wqkv Wo … applies LoRA to exactly those modules and writes metrics.
  • Out-of-the-box sweep (final pass, head 94204c7)

    Every family on the as-is support list trained end to end through classifier_sft (train → reload with the Auto class → finite weights → label_mapping.json + training_metrics.jsonl → accuracy on a learnable toy set; held-out for multiple choice):

    | Backbone family (checkpoint tested) | seq-cls | token-cls | multiple choice |
    |---|---|---|---|
    | ModernBERT (answerdotai/ModernBERT-base) | ✅ 1.00 | ✅ 1.00 | ✅ 1.00 |
    | BERT (bert-base-uncased) | ✅ 1.00 | ✅ 1.00 | ✅ 1.00 |
    | RoBERTa (roberta-base) | ✅ 1.00 | ✅ 1.00 | ✅ 1.00 |
    | DeBERTa-v3 (deberta-v3-small) | ✅ 1.00 | ✅ 1.00 | ✅ 1.00 |
    | DistilBERT | ✅ 1.00 | ✅ 1.00 | ✅ 1.00 |
    | ELECTRA (electra-small-discriminator) | ✅ 1.00 | ✅ 1.00 | — |
    | XLM-R (xlm-roberta-base) | ✅ 1.00 | ✅ 1.00 | — |
    | ALBERT / MPNet | ✅ 1.00 / ✅ 1.00 | — | — |
    | Qwen2.5 / Qwen3.5 (LoRA) | ✅ 1.00 / ✅ 1.00 | ✅ 1.00 / ✅ 1.00 | n/a (encoder-only) |
    | Qwen3, Phi-1.5, OLMo-2, Gemma-3 (LoRA) | ✅ 1.00 each | — | n/a |
    | SmolLM2 / Llama arch (LoRA and full FT) | ✅ 1.00 / ✅ 1.00 | — | n/a |

    Expected not supported as-is — all fail with a clear error before training: decoder multiple choice (Unrecognized configuration class …), GLiClass (vendor package → model_class), Jina v3 (its remote code has no classification head). Remote-code repos that don't yet support transformers 5: GTE-v1.5 and Jina v2 (call removed APIs), nomic-embed-text-v1.5 (fails during training).

    The sweep caught one real bug, fixed in 255cb78: DeBERTa-v3 trained to chance because transformers 5 loads checkpoints in their stored dtype (fp16 for DeBERTa-v3) and AdamW on fp16 weights NaNs on the first step. Optimized weights are now always fp32 (full fine-tune loads fp32; LoRA keeps the frozen base bf16 and upcasts adapters + head).

    Review items addressed

    Round 4 (xingliu-netizen re-test, CodeRabbit outside-diff):

  • use_peft + token classification no longer LoRA-wraps the head (all-linear fallback excludes classifier / score).

  • Qwen3.5 (nested text_config) gets pad_token_id on the text sub-config.

  • Custom loss_fn on multiple choice: padded choices reach the loss with -inf logits; a loss accepting choice_mask also gets the mask.

  • Multiple choice keeps token_type_ids (BERT-family segment ids) through prep + collation.

  • Negative integer labels rejected with a clear error (token-cls -100 ignore marker preserved); multiple-choice labels must index an option.

  • training_metrics.jsonl only ever contains finite numbers (strict JSON).
  • Round 3 (xingliu-netizen, CodeRabbit):

  • Multiple choice with variable option counts no longer NaNs the model — padded choices carry one attended pad token (an all-zero mask made mean-pooling divide by zero); choice_mask still excludes them from the softmax.

  • Loss normalized across gradient accumulation — model_accepts_loss_kwargs=False on every trainer (all losses here are per-batch means); a Trainer subclass that consumes num_items_in_batch can opt out with a class attribute.

  • use_peft works on ModernBERT / Qwen3.5 — PEFT defaults where they exist, else target_modules="all-linear"; new --lora-target-modules CLI flag.

  • training_metrics.jsonl written (max_steps, global_step, train_loss, epoch, task) for Kubeflow progress.

  • Column handling — user columns validated and named in errors; columns read by name (no renames), so text_column="clean_text" alongside a text column, or swapped names, work.

  • Reproducible seed — set_seed before the head / LoRA are initialized.

  • Token classification — dropped the ignored collator max_length.

  • bf16 selected by GPU capability (is_bf16_supported), so pre-Ampere GPUs fall back to fp32.

  • Docs — raw logits are not described as calibrated; quick-start columns match label_column="category"; LoRA target defaults and the metrics file documented; absolute links.
  • Rounds 1–2: multiple-choice padded-choice masking; NaN/null labels rejected with a counted error; version-safe warmup (warmup_ratio on 4.x, warmup_steps on 5.x); lora_target_modules declared; lighter multiple-choice max_k; _align_word_labels extracted + tested; type hints / full docstring; dropped the never-shipped SequenceClassificationBackend alias.

    Docs

    Algorithm guide (docs/algorithms/classifier_sft.md), API reference (function/class/backend pages), and README support-matrix + section + sidebar nav.

    Follow-ups (non-blocking)

  • JIT-preemption checkpointing / merge_default_callbacks integration — not wired here, consistent with embedding_sft (the JIT/resume callbacks are currently only in the generative algorithms sft/osft/lora). Low priority for a head/embedding trainer.

  • In-training eval/metrics support.

  • Optional streaming max_k for very large multiple-choice datasets.
  • 🤖 Generated with Claude Code

    <!-- This is an auto-generated comment: release notes by coderabbit.ai -->
    <!-- coderabbit-ai-generated:v1 -->

    Summary by CodeRabbit

    New Features
    Added classifier fine-tuning for sequence classification, multiple choice, and token classification.
    Added the classifier-sft command with options for training settings, task-specific data columns, and model configuration.
    Added optional LoRA support, custom model classes and loss functions, and automatic encoding of categorical labels.
    Training outputs include the model, tokenizer, label mappings, and training metrics. Training is supported on CPU and single- or multi-GPU setups.
    Documentation
    * Added usage guides and API references for classifier fine-tuning.
    <!-- end of auto-generated comment: release notes by coderabbit.ai -->

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: xingliu-netizen Review duration: 28678m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    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.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #160"
    general weight: 0.35
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% 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: 52% (MEDIUM) · Higher = larger blast radius
    52%
    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: 60.5% · Lower = rushed or shallow review
    60.5%
    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: 20.5% · Safe to merge
    20.5%