[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-110754":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":13,"openIssues":14,"contributorsCount":15,"subscribersCount":15,"size":15,"stars1d":15,"stars7d":15,"stars30d":16,"stars90d":15,"forks30d":15,"starsTrendScore":15,"compositeScore":17,"rankGlobal":10,"rankLanguage":10,"license":18,"archived":19,"fork":19,"defaultBranch":20,"hasWiki":19,"hasPages":19,"topics":21,"createdAt":10,"pushedAt":40,"updatedAt":41,"readmeContent":42,"aiSummary":43,"trendingCount":15,"starSnapshotCount":15,"syncStatus":44,"lastSyncTime":45,"discoverSource":46},110754,"distillops","Zihao-Wu06\u002Fdistillops","Zihao-Wu06","Black-box LLM distillation for any verifiable task, with text or image inputs: teacher API -> rejection sampling -> SFT -> eval -> GRPO","",null,"Python",59,4,1,0,21,44.2,"MIT License",false,"main",[22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39],"ai-agents","distillation","document-understanding","fine-tuning","grpo","knowledge-distillation","llm","multimodal","posttraining","qwen","qwen3-vl","reinforcement-learning","rlvr","sft","small-language-models","trl","vision-language-model","vllm","2026-11-04 16:24:49","2026-11-23 17:08:29","\u003Cdiv align=\"center\">\n\n# distillops\n\n### Distil any LLM, hosted or local, into a small model you own\n\nBlack-box distillation for any task whose result can be Verified.\n\n**Want a LLM’s results on your own task? Distil it into a small local model, from its answers, never its weights.**\n\n[![tests](https:\u002F\u002Fimg.shields.io\u002Fgithub\u002Factions\u002Fworkflow\u002Fstatus\u002FZihao-Wu06\u002Fdistillops\u002Ftests.yml?branch=main&style=flat-square&label=tests)](https:\u002F\u002Fgithub.com\u002FZihao-Wu06\u002Fdistillops\u002Factions\u002Fworkflows\u002Ftests.yml)\n[![Python 3.11 | 3.12](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fpython-3.11%20%7C%203.12-3776ab?style=flat-square&logo=python&logoColor=white)](pyproject.toml)\n[![inputs: text · images](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Finputs-text%20%C2%B7%20images-0f766e?style=flat-square)](#results)\n[![models on Hugging Face](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fmodels-Hugging%20Face-ffd21e?style=flat-square&logo=huggingface&logoColor=black)](https:\u002F\u002Fhuggingface.co\u002FLiquor-06)\n[![MIT license](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Flicense-MIT-blue?style=flat-square)](LICENSE)\n\n[Try it](#try-it) · [How it works](#how-it-works) · [Add your own task](#add-your-own-task) · [Results](#results) · [Install](#install) · [Reference](#reference)\n\n\u003Ccode>git clone https:\u002F\u002Fgithub.com\u002FZihao-Wu06\u002Fdistillops && cd distillops && pip install -e \".[train,dev]\"\u003C\u002Fcode>\n\n\u003C\u002Fdiv>\n\n\u003Cp align=\"center\">\u003Cimg src=\"assets\u002Fworkflow.svg\" width=\"900\"\n  alt=\"Workflow: a Task class drives an LLM teacher (a hosted API or a local server); answers that pass verify (retried up to 3 times) become verified training rows, which train a small open model with SFT and then GRPO, using the task's score as reward\">\u003C\u002Fp>\n\n---\n\nHave a task a large LLM does well, such as extracting fields, finding personal information, solving\nmath or reading documents? distillops turns it into a small open model that does the same job on\nyour own machine. The large model, the *teacher*, answers your inputs. Your code checks every answer,\nand only the answers that pass become training data. A small *student* learns from them with SFT,\nthen improves with reinforcement learning (GRPO) on the same metric you report. Only the teacher's\ntext answers are needed, never its weights or logits, so any model behind an OpenAI-compatible\nendpoint can teach: a hosted API, or an open model you serve yourself with vLLM or SGLang.\n\nThe student can match its teacher, and sometimes beat it. A 0.6B personal-information detector\ntrained without a single human label **beats the API model that taught it** (0.955 vs 0.934 F1;\n[details](#personal-information-detection-a-student-that-beats-its-teacher)). A 1.7B base model\n**reaches the math accuracy of Qwen's own post-trained Qwen3-1.7B**\n([details](#math-gsm8k-qwen3-17b-base-student-all-1319-test-problems)). A 2B vision model **ties its\n32B teacher** at reading receipt photos ([vision extension](extensions\u002Fvision\u002FREADME.md)). A\n0.5M-parameter recommender **matches LLM recommenders** about 1,500 times its size\n([details](#recommendation-an-llm-teacher-for-a-deployable-recommender)).\n\nEvery gain is measured against a control, not assumed. Each example also trains the same student\non the dataset's own labels with no teacher, so you can see what the teacher itself added. The math,\nPII and receipt comparisons are paired over the same test set, with 95% confidence intervals.\n\nYou describe a task once, in a `Task` class: its data, prompts, a verifier and a score. The same\ncommands then collect verified teacher answers, fine-tune, evaluate and run GRPO, for any causal LM\non the Hugging Face hub as the student.\n\n**Released models:** [GSM8K, Qwen3-1.7B-Base](https:\u002F\u002Fhuggingface.co\u002FLiquor-06\u002FQwen3-1.7B-Base-GSM8K-distillops)\n([teacher data: 7,274 verified answers](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002FLiquor-06\u002Fgsm8k-deepseek-verified))\n· [PII, Qwen3-0.6B](https:\u002F\u002Fhuggingface.co\u002FLiquor-06\u002FQwen3-0.6B-PII-distillops)\n· [recommendation, SASRec](https:\u002F\u002Fhuggingface.co\u002FLiquor-06\u002FSASRec-TwoStage-Industrial-distillops)\n\n## Try it\nDistil DeepSeek's math reasoning into Qwen3-0.6B-Base on one 24 GB GPU (e.g. an RTX 4090), for under\n$1 of API calls. The teacher can be any OpenAI-compatible endpoint, a hosted API or a model you serve\nlocally (vLLM, SGLang): copy the template, set `base_url`, `model` and `api_key_env`, and export the key.\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002FZihao-Wu06\u002Fdistillops && cd distillops\npip install -e \".[train,dev]\"\ncp configs\u002Fteacher_template.yaml configs\u002Fmy_teacher.yaml       # then edit it for your provider\nexport TEACHER_API_KEY=...                                      # the variable named by api_key_env\nT=tasks.math.gsm8k:GSM8KTask\n\npython -m distillops eval    --task $T --model Qwen\u002FQwen3-0.6B-Base --chat-template plain   # 56.8%\npython -m distillops teacher --task $T --teacher configs\u002Fmy_teacher.yaml --n 100            # smoke test\npython -m distillops teacher --task $T --teacher configs\u002Fmy_teacher.yaml                   # all 7,473 problems\npython -m distillops sft     configs\u002Fsft_qwen3_0.6b_base.yaml\npython -m distillops eval    --task $T --model checkpoints\u002Fgsm8k_0.6b_base_teacher          # 65.9%\n```\n**+9.1 points** on all 1,319 test problems (95% CI +6.3 to +11.9). With DeepSeek as the teacher the\ncalls cost 3.79 CNY (~$0.53); `python -m distillops usage --teacher configs\u002Fmy_teacher.yaml` reports the\ntokens. Measured on an RTX PRO 6000 with GPU memory capped at 24 GB: SFT took 7 minutes and peaked at\n14 GB allocated (23 GB reserved); slower cards take longer. The same commands work for your own task\nonce it has a `Task` class ([Add your own task](#add-your-own-task)); [Results](#results) has the\n1.7B route, with GRPO on top.\n\n## What it can be used for\nThe one requirement: given an input and an output, your code can say whether the output is right\n(`verify`, for teacher data) and how right it is on a 0-1 scale (`score`, for evaluation and RL).\n\n| Task type | What `verify` \u002F `score` checks |\n|---|---|\n| Classification, routing, intent detection | the predicted label equals the gold label |\n| Structured extraction (JSON, forms, entities) | the output parses and its fields match |\n| Tool \u002F function calling | the function name and arguments match the expected call |\n| Code generation | the code passes the task's unit tests |\n| Math and quantitative reasoning | the final number equals the answer |\n| Short-answer QA | the normalised answer matches |\n| Ranking, retrieval, recommendation | the right item appears in the output (e.g. in the top-k) |\n\nThree of these ship as worked examples: **math (GSM8K)**, **personal-information (PII)\ndetection** (structured extraction) and **recommendation (Amazon)**. They show what the framework does and how well; nothing in the framework\nis specific to them. Any other task needs only its own `Task` class\n([Add your own task](#add-your-own-task) has a complete one in ~45 lines).\n\n## How it works\n```\n         ┌───────────────────────────────────────────────────────────────┐\n task ──►│ Task class: data, teacher prompt, verify, training row,       │  the only task-specific code\n         │ student prompt, score (+ optional: label-only rows, decoding) │\n         └───────────────────────────────────────────────────────────────┘\n                                    │\n 0 check     python -m distillops doctor     GPU, chosen precision, free memory and disk, versions\n                                    │\n 1 baseline  python -m distillops eval       the untrained student: the starting point\n                                    │\n 2 teacher   python -m distillops teacher    any OpenAI-compatible endpoint answers -> verify -> retry the failed\n                                             ones (up to --max-attempts, default 3): rejection sampling\n   control   python -m distillops labels     rows from the dataset's own labels (answers or human\n                                             solutions), no teacher\n                                    │\n 3 SFT       python -m distillops sft        one run on teacher rows, one on control rows (LoRA by default)\n                                    │\n 4 eval      python -m distillops eval       teacher SFT vs control SFT vs baseline\n                                    │\n 5 GRPO      python -m distillops grpo       reward = Task.score; optional --filter-samples keeps prompts that\n                                             are sometimes right; validation picks the best checkpoint;\n                                             stops on entropy collapse\n                                    │\n 6 eval      python -m distillops eval       before vs after GRPO\n```\n\n`verify` decides which teacher outputs become training data; `score` is both the evaluation metric\nand the GRPO reward, so reinforcement learning optimises exactly what you report.\n\n### Features\n- **Any verifiable task, one class.** Teacher calls, rejection sampling, SFT, evaluation and GRPO are\n  shared; a task only supplies data, prompts, a verifier and a score.\n- **Any student model.** Any causal LM from the Hugging Face hub or a local path can be the student\n  (Qwen, Llama, Mistral, Gemma, Phi, GPT-2, ...), including base models, with or without a chat\n  template of their own.\n- **Verified data, measured value.** Teacher outputs are kept only if they pass your verifier (failed\n  examples are retried), and a no-teacher control (`labels`) shows what the teacher actually adds.\n- **RL that tells you when it will not work.** Before GRPO, the share of prompts that carry a learning\n  signal is measured and explained; during and after it, validation on prompts the model never trained\n  on picks the best checkpoint, an entropy guard stops collapse, and a weight-change check catches\n  updates that never landed.\n- **Runs on the GPU you have.** Precision is chosen from the hardware, batch sizes from free memory and\n  the model's size, and disk space is checked before training; `doctor` reports all of it.\n\n## Add your own task\nA complete task: support tickets classified into a fixed label set, with the teacher explaining its\nchoice. Save it as e.g. `my_tasks\u002Ftriage.py`.\n\n```python\nimport json\nimport re\n\nfrom distillops.task import Task, Verdict\n\nclass TicketTriage(Task):\n    name = \"triage\"\n    LABELS = [\"billing\", \"bug\", \"feature\", \"other\"]\n\n    def load_examples(self, split):  # any source; here JSONL rows {\"id\", \"text\", \"label\"}\n        with open(f\"data\u002Ftriage_{split}.jsonl\", encoding=\"utf-8\") as f:\n            return [json.loads(line) for line in f]\n\n    def example_id(self, ex):\n        return ex[\"id\"]\n\n    def teacher_messages(self, ex, attempt):\n        return [{\"role\": \"user\", \"content\": f\"{ex['text']}\\n\\nExplain in one or two sentences which \"\n                 f\"team should handle this, then end with: LABEL: \u003Cone of {', '.join(self.LABELS)}>\"}]\n\n    def parse_teacher(self, ex, text):\n        found = re.findall(r\"LABEL:\\s*(\\w+)\", text)\n        return found[-1].lower() if found else None\n\n    def verify(self, ex, parsed, text, attempt):\n        if parsed not in self.LABELS:\n            return Verdict(False, \"parse_error\")\n        return Verdict(parsed == ex[\"label\"], \"ok\" if parsed == ex[\"label\"] else \"wrong_label\")\n\n    def sft_example(self, ex, parsed, text):\n        return {\"prompt\": self.student_messages(ex), \"completion\": [{\"role\": \"assistant\", \"content\": text}]}\n\n    def student_messages(self, ex):\n        return [{\"role\": \"user\", \"content\": f\"{ex['text']}\\n\\nEnd with: LABEL: \u003Cone of {', '.join(self.LABELS)}>\"}]\n\n    def score(self, ex, completion):\n        return float(self.parse_teacher(ex, completion) == ex[\"label\"])\n\n    def gold_sft_example(self, ex):  # optional: the no-teacher control for `labels`\n        return {\"prompt\": self.student_messages(ex),\n                \"completion\": [{\"role\": \"assistant\", \"content\": f\"LABEL: {ex['label']}\"}]}\n```\n\n```bash\npython scripts\u002Fcheck_task.py --task my_tasks.triage:TicketTriage --model Qwen\u002FQwen3-0.6B  # data, prompts, masked row\npython -m distillops teacher --task my_tasks.triage:TicketTriage --teacher configs\u002Fmy_teacher.yaml --n 50\n# then labels \u002F sft \u002F eval \u002F grpo as in Try it\n```\n\nThe methods, with the included GSM8K example for comparison:\n\n| Method | Purpose | GSM8K |\n|---|---|---|\n| `load_examples(split)` | your dataset (a `valid` split, if any, is used for GRPO validation) | `datasets.load_dataset(\"openai\u002Fgsm8k\")` |\n| `example_id(ex)` | stable id (logging, resume, `--exclude`, `--keep-ids`) | `\"gsm8k:train:17\"` |\n| `teacher_messages(ex, attempt)` | prompt for the teacher | question + \"end with `ANSWER: \u003Cnumber>`\" |\n| `parse_teacher(ex, text)` | raw text -> structured answer | steps + final number |\n| `verify(ex, parsed, text, attempt)` | **the distillation filter** | number equals gold, length limit |\n| `sft_example(ex, parsed, text)` | accepted output -> training row | `\u003Cthink>steps\u003C\u002Fthink>ANSWER: n` |\n| `student_messages(ex)` | the student's prompt | question + answer-format instruction |\n| `score(ex, completion)` | metric **and** GRPO reward, in [0, 1] | 1 if the final number is right |\n| `gold_sft_example(ex)` *(optional)* | label-only control row | `ANSWER: n`, or the human solution |\n| `extra_metrics(examples, completions, scores)` *(optional)* | metrics over the whole set, next to the mean `score` (e.g. macro-F1, BLEU) | - |\n| `evaluate(...)` *(optional)* | custom decoding | - (recommendation overrides it with constrained beam search) |\n\nConstructor arguments can be passed on the command line, e.g. `--task-arg max_words=200`.\n\n**Writing a good verifier is most of the work.** Teachers break instructions in ways that would\nteach the student the wrong thing (e.g. referring to information only the teacher saw); `verify` is\nwhere those outputs are dropped. Read accepted samples before scaling up. If GRPO's pass-rate filter\nreports a sparse reward, a `score` that gives partial credit is the first thing to try.\n\n## Results\nThe three included examples, chosen to be very different, show what the framework does and\nhow well; their code lives in `tasks\u002F` and is not needed for your own task.\n\n### Math: GSM8K (Qwen3-1.7B-Base student, all 1,319 test problems)\n| Model | Accuracy |\n|---|---|\n| Qwen3-1.7B-Base, untrained (zero-shot, plain prompt) | 73.8% |\n| + SFT on GSM8K's human solutions (same problems and settings, no teacher) | 68.5% |\n| **+ SFT on DeepSeek reasoning (rejection-sampled, full fine-tuning)** | **80.1%** |\n| **+ GRPO (1 epoch, reward = `Task.score`)** | **81.6%** |\n| *Qwen3-1.7B: Qwen's own post-trained model, for reference* | *80.2%* |\n\n\u003Cp align=\"center\">\u003Cimg src=\"assets\u002Fgsm8k_results.svg\" width=\"820\"\n  alt=\"GSM8K accuracy: untrained 73.8%, SFT on human solutions 68.5%, SFT on teacher reasoning 80.1%, plus GRPO 81.6%, Qwen3-1.7B 80.2%\">\u003C\u002Fp>\n\nTeacher: DeepSeek Flash, 7,274 of 7,473 problems accepted (97.3%), **3.79 CNY**. The student is a base\nmodel, which has seen no post-training on math, so the gain is the distillation's own. Paired over\nthe 1,319 problems: SFT adds **+6.3 points** (95% CI +3.9 to +8.6, p \u003C 1e-6) and GRPO with the same\nverifier as reward **+1.6** more (+0.2 to +3.1, p = 0.046); the result is on par with Qwen's post-trained\nQwen3-1.7B (+1.4, CI -0.8 to +3.6, p = 0.24). Before GRPO, 40.7% of training prompts carried a learning\nsignal (57.3% were always solved); GRPO ran 96 steps and token entropy went 0.19 -> 0.15 (no collapse).\nThe no-teacher control (`labels --task-arg label_reasoning=human`, same 7,274 problems, same SFT\nsettings) scores 68.5%, below the untrained model; the teacher's reasoning beats it by **+11.6 points**\n(+9.1 to +14.3, p \u003C 1e-17), so the gain comes from the teacher, not from training on GSM8K problems.\nTraining is not bit-for-bit repeatable on GPUs: an earlier run of the same route gave 78.5% \u002F 80.4%\n(no significant difference from these numbers). The smaller [Try it](#try-it) route, Qwen3-0.6B-Base\nwith the same teacher answers and no GRPO, goes from 56.8% to 65.9%.\n\n#### Reproduce it\nThe full route behind the chart, with the teacher set up as in [Try it](#try-it). The teacher\nanswers are the same as there: after Try it, the two `teacher` commands send no requests.\n```bash\nT=tasks.math.gsm8k:GSM8KTask\nTEACHER=configs\u002Fmy_teacher.yaml\nB=Qwen\u002FQwen3-1.7B-Base\n\npython -m distillops eval    --task $T --model $B --chat-template plain             # baseline: 73.8%\npython -m distillops teacher --task $T --teacher $TEACHER --n 100                   # smoke test on 100 problems\npython -m distillops teacher --task $T --teacher $TEACHER                           # full train split\npython -m distillops sft     configs\u002Fsft_qwen3_full.yaml                             # writes checkpoints\u002Fgsm8k_1.7b_base_teacher\npython -m distillops eval    --task $T --model checkpoints\u002Fgsm8k_1.7b_base_teacher   # 80.1%\n\n# GRPO (Linux + vLLM): measure the learning signal first, then train on the useful prompts\npython -m distillops grpo configs\u002Fgrpo_gsm8k_qwen3_1.7b_base.yaml --task $T --filter-samples 8 --filter-only\npython -m distillops grpo configs\u002Fgrpo_gsm8k_qwen3_1.7b_base.yaml --task $T \\\n         --keep-ids checkpoints\u002Fgsm8k_1.7b_base_grpo\u002Fpass_rate_kept.txt --epochs 1\npython -m distillops eval    --task $T --model checkpoints\u002Fgsm8k_1.7b_base_grpo      # 81.6%\npython -m distillops usage   --teacher $TEACHER                                     # teacher calls and tokens\n```\n- **Full fine-tuning, not LoRA:** the base model's chat-template tokens (`\u003C|im_start|>`, `\u003C|im_end|>`,\n  `\u003Cthink>`) were never trained, and LoRA cannot learn embeddings; with LoRA, `sft` stops and says so.\n  Full fine-tuning of 1.7B parameters needs ~33 GB plus activations (and vLLM's share during GRPO);\n  the results were produced on a 96 GB GPU.\n- **Baseline:** a base model is scored with the `plain` template (it has not learned the chat format);\n  4-shot prompting scored lower (68.1%), so 73.8% is the baseline.\n- **GRPO validation:** SFT saw nearly every training problem, and the few it did not are ones the\n  teacher failed, so there is no representative validation set: the config sets `eval_every: 0` and\n  GRPO keeps its final model. To select checkpoints instead, set problems apart with\n  `--task-arg valid_size=500` on both `teacher` and `grpo`, and turn `eval_every` back on.\n- **Teacher:** the included results used DeepSeek (`configs\u002Fteacher_deepseek.yaml`); the GSM8K teacher\n  calls cost 3.79 CNY (3.74 for the full run, 0.05 for the 100-problem smoke test).\n\n### Personal-information detection: a student that beats its teacher\nFind names, contact details, addresses, ID and card numbers, dates and demographics in English text\n([OpenPII-1M](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002Fai4privacy\u002Fpii-masking-openpii-1m)) so they can be masked\nlocally. The teacher (DeepSeek, 3 worked examples) labels 10,000 texts; its answers are accepted by\nrules alone (values copied verbatim, plausible formats, no long number left unmasked), with no gold\nlabels. A Qwen3-0.6B student then learns from them, and GRPO uses per-text F1 as the reward.\n\n| Model (2,000 test texts, 7 categories) | Labelled texts used | Mean F1 | Personal info left visible |\n|---|---|---|---|\n| Qwen3-0.6B, untrained | - | 0.158 | 73.1% |\n| Teacher (DeepSeek, 3-shot) | 103 (100 to write its instructions, 3 as examples) | 0.934 | 3.0% |\n| **0.6B, SFT on rule-checked teacher labels** | **103** (the teacher's; it trains on none) | **0.945** | 2.0% |\n| **+ GRPO on a small labelled pool** | **2,100** | **0.955** | **1.9%** |\n| 0.6B, SFT on gold labels of all 10,000 texts (control) | 10,000 | 0.982 | 1.1% |\n\nThe student beats its teacher (+1.15 points, 95% CI +0.65 to +1.67, p = 4e-5), and GRPO adds +0.95\n(p = 1e-9); teacher labels reach 96-97% of what full human annotation gives. Teacher calls: 17.7 CNY.\nPer-category scores, the pilot batch that shaped the teacher's instructions, leakage checks and\nthe commands: [tasks\u002Fpii\u002FREADME.md](tasks\u002Fpii\u002FREADME.md).\nModel (the GRPO student, bf16): [Liquor-06\u002FQwen3-0.6B-PII-distillops](https:\u002F\u002Fhuggingface.co\u002FLiquor-06\u002FQwen3-0.6B-PII-distillops).\n\n### Recommendation: an LLM teacher for a deployable recommender\nA task far from math: next-item recommendation on Amazon Industrial & Scientific. A fine-tuned\nQwen3-1.7B recommends well but is too large to serve, so it is used offline as a teacher (item\nembeddings + top-3 soft labels) for SASRec. Two ~0.5M-parameter SASRecs then reach **HR@10 .164 \u002F\nNDCG@10 .119**, on par with recent LLM recommenders (1.5B-7B parameters, HR@10 .159-.163) at ~1\u002F1,500\nof their serving size. Tables, cold-start results and the commands to reproduce:\n[tasks\u002Frec\u002FREADME.md](tasks\u002Frec\u002FREADME.md).\nModel (both SASRecs, ~0.8M parameters, plain PyTorch): [Liquor-06\u002FSASRec-TwoStage-Industrial-distillops](https:\u002F\u002Fhuggingface.co\u002FLiquor-06\u002FSASRec-TwoStage-Industrial-distillops).\n\n### Images: reading receipts (vision extension)\nA Qwen3-VL-2B student reads receipt photos (CORD-v2) into JSON: items, totals, cash and change. Mean\nF1 on 200 test receipts:\n\n| Model | Human labels used | Mean F1 | Receipts read perfectly |\n|---|---|---|---|\n| Qwen3-VL-2B, untrained | 0 | 0.756 | 10.5% |\n| Qwen3-VL-32B teacher | 0 | 0.896 | 41.0% |\n| **2B, SFT on the teacher's arithmetic-checked labels** | **0** | **0.897** | **42.0%** |\n| **+ GRPO on 200 labelled receipts** | **300** | **0.905** | **49.5%** |\n| 2B, SFT on all 800 gold labels (control) | 800 | 0.928 | 58.0% |\n\nThe teacher's labels give 82% of the gain that gold labels for every training receipt give (87% after\nGRPO). GRPO's mean gain is not significant (p = 0.16), but it reads 15 more receipts perfectly\n(McNemar p = 0.004). The extension adds images to every stage (teacher requests, SFT, evaluation, GRPO\nwith vLLM) without changing distillops. Tables, process notes and commands:\n[extensions\u002Fvision\u002Fvision_tasks\u002Fcord\u002FREADME.md](extensions\u002Fvision\u002Fvision_tasks\u002Fcord\u002FREADME.md).\n\n### Takeaways\n1. A few CNY of verified teacher reasoning replace a model's math post-training: on GSM8K, SFT takes a\n   base model +6.3 points and GRPO with the same verifier as reward +1.6 more, matching Qwen's own\n   post-trained model of the same size.\n2. Always compare against a same-data, no-teacher control (`python -m distillops labels`), not just the\n   untrained model, to see what the teacher itself contributes: on GSM8K, SFT on the human solutions of\n   the same problems lowered the score (73.8% -> 68.5%) while the teacher's reasoning raised it (80.1%).\n3. Labelling every training text is not needed: rules that check the teacher's answers, plus 100\n   labelled texts to write its instructions, train a 0.6B PII detector that beats its teacher, and\n   2,000 labelled texts for GRPO bring it to 97% of what labelling all 10,000 training texts gives.\n4. For latency-bound products, use the LLM as an offline teacher: item embeddings plus soft labels lifted\n   SASRec by 22-24% HR@10, and a two-stage recall + re-rank matched recent LLM recommenders, at\n   unchanged serving cost.\n\n## Install\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002FZihao-Wu06\u002Fdistillops && cd distillops\npip install -e \".[train,dev]\"          # framework, training stack and tests\npip install \"vllm==0.11.0\"             # only for GRPO and the pass-rate filter (Linux)\npython -m distillops doctor            # GPU, chosen precision, free memory and disk, library versions\npython -m pytest -q                    # unit tests; no GPU or network needed\n```\nPython 3.11-3.12. Tested on these setups:\n\n| Machine | Used for | torch | transformers | TRL | PEFT | vLLM |\n|---|---|---|---|---|---|---|\n| Windows 11, RTX 4090 24GB | teacher calls, SFT, evaluation, SASRec | 2.11 (cu128) | 5.21 | 1.16 | 0.21 | - |\n| Ubuntu 22.04, RTX PRO 6000 96GB (and RTX 6000D 84GB) | GRPO, pass-rate filter, SFT, evaluation | 2.8 (cu128) | 4.57.1 | 0.24 | 0.21 | 0.11.0 |\n| macOS (Apple Silicon), CPU only | SFT, evaluation and GRPO without vLLM on non-Qwen students (gpt2, SmolLM2-135M-Instruct) | 2.15 | 4.57.1 | 0.24 | 0.21 | - |\n\nvLLM 0.11 needs transformers 4.x; pin `transformers==4.57.1 trl==0.24.0` next to it. The framework\nhandles the version differences it knows about (warmup arguments, chat-template options).\n\n**Teacher terms of use:** check that your teacher's terms allow training other models on its outputs;\nsome providers' terms forbid training competing models.\n\n## Hardware\nNothing is tuned to a particular GPU: memory settings are fractions of the card or are sized from\nthe memory that is free when the run starts.\n\n| Step | Needs |\n|---|---|\n| `teacher`, `labels`, `usage` | no GPU (teacher requests and files); a teacher you serve locally needs its own GPU |\n| `sft`, `eval` | a CUDA GPU; without one they run on the CPU, which is practical only for small models |\n| `grpo` with vLLM (default), pass-rate filter | Linux and a CUDA GPU; `use_vllm: false` runs anywhere, more slowly |\n\nRough GPU memory per billion student parameters, before activations:\n- **LoRA SFT:** ~2 GB (base weights in bf16\u002Ffp16; the adapter and its optimizer state are small).\n- **Full fine-tuning** (`lora: false`; GRPO's default): ~16 GB (fp32 weights, gradients and AdamW\n  state). GRPO with vLLM also reserves `vllm_gpu_memory_utilization` of the card for rollouts.\n- **Evaluation:** ~2 GB for the weights; the rest goes to the KV cache.\n\nWhat adapts and what does not:\n- Evaluation and GRPO size their batches from free memory and the model's config, and shrink them\n  if a batch would not fit. SFT uses `batch_size` as given: if it runs out of memory, lower\n  `batch_size` and raise `grad_accum` (same effective batch).\n- `doctor` reports the GPU, precision and free memory; training refuses to start if the disk cannot\n  hold the run, and GRPO stops at once if vLLM's share of the GPU is not free, naming the setting to lower.\n- One GPU per run; multi-GPU launches (`accelerate`, `torchrun`) are not tested.\n\n## Reference\n\u003Cdetails>\n\u003Csummary>\u003Cb>Commands\u003C\u002Fb>\u003C\u002Fsummary>\n\n`python -m distillops \u003Ccommand> --help` lists every flag. Commands that read a dataset share\n`--task module:Class` (or a YAML file with `task:` and `args:`), `--task-arg KEY=VALUE` (constructor\narguments, repeatable), `--split`, `--n` (random subset, 0 = all) and `--seed`.\n\n| Command | What it does | Main flags |\n|---|---|---|\n| `doctor` | environment report and platform warnings | - |\n| `teacher` | teacher outputs -> `verify` -> accepted SFT rows, with retries; a rerun resumes, and refuses a folder made with another teacher, task settings, teacher prompt or task code | `--teacher` (config, required), `--max-attempts` (3), `--out` |\n| `labels` | label-only SFT rows from `gold_sft_example` (the no-teacher control) | `--out` |\n| `sft` | supervised fine-tuning from a YAML config | `--train_file`, `--output_dir`, `--model`, `--epochs`, `--chat-template` (override the config) |\n| `eval` | generate with a student and score with `Task.score` | `--model`, `--max-new-tokens` (512), `--batch` (0 = auto), `--template-arg KEY=VALUE`, `--no-think` (= `enable_thinking=false`), `--chat-template`, `--tag`, `--out` |\n| `grpo` | GRPO with `Task.score` as the reward | `--model`, `--filter-samples N`, `--filter-only`, `--filter-gpu-memory` (0.4), `--keep-ids`, `--exclude`, `--epochs`, `--max-steps`, `--eval-every`, `--eval-examples`, `--chat-template`, `--template-arg`, `--output_dir` |\n| `merge` | merge a LoRA adapter into its base model | `--base`, `--adapter`, `--out` |\n| `usage` | teacher calls and tokens (prompt, provider prompt-cache hits, completion) from the local response cache | `--teacher` (required) |\n\n`grpo` details: `--filter-samples 8 --filter-only` samples 8 completions per prompt with vLLM (same\ntemperature, length limits and prompt truncation as GRPO), keeps the prompts whose samples differ in\nscore (the only ones GRPO learns from, with binary or partial-credit scores), prints why the others\nwere dropped, and writes `pass_rate_kept.txt`; `--keep-ids` then trains on\nthose prompts in a fresh process. `--exclude \u003Cjsonl>` skips prompts whose `meta.id` appears in a file\n(e.g. the SFT data). `--epochs E` sets the number of steps so each prompt is seen E times.\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cb>Configuration (teacher, student model, SFT, GRPO)\u003C\u002Fb>\u003C\u002Fsummary>\n\nEvery option has a default and can be changed in the YAML file. Whenever the framework chooses\nsomething itself (micro-batch, precision, validation source), it prints what it chose and why.\n\n### Teacher (`configs\u002Fteacher_template.yaml`; `configs\u002Fteacher_deepseek.yaml` is a filled-in example)\n| Field | Default | Meaning |\n|---|---|---|\n| `base_url`, `model` | required | any OpenAI-compatible endpoint (hosted API, vLLM, SGLang, ...) and model name |\n| `api_key_env` | `TEACHER_API_KEY` | environment variable holding the key (keys never go in config files); a local server started without a key accepts any value |\n| `temperature` | 1.0 | > 0 so retries in rejection sampling give different answers; `null` = not sent (models that only accept their default) |\n| `max_tokens` | 1024 | per call; `null` = not sent |\n| `max_tokens_param` | `max_tokens` | request field for `max_tokens`; OpenAI's reasoning models need `max_completion_tokens` |\n| `max_concurrency` | 32 | parallel requests; raise it if your provider allows |\n| `timeout_s`, `max_retries` | 300, 6 | per request; retries (exponential backoff) only for network errors, timeouts, replies without a completion, 408\u002F409\u002F429 and 5xx |\n| `extra_body` | `{}` | provider-specific request options, passed through unchanged |\n| `cache_path` | `cache\u002Fteacher.sqlite` | response cache: an identical request to the same endpoint is never sent twice; teachers can share the file (`usage` counts each separately) |\n\n### Student model\nAny causal language model can be the student: set `model` in the SFT or GRPO config, or pass\n`--model`, to a hub id or a local path. The included configs name Qwen3 only because the example\nresults used it.\n- **Chat template.** Prompts and training rows go through the student's chat template, the same one\n  in SFT, evaluation and GRPO. Instruct models bring their own. A model without one (a base model\n  such as `gpt2`) gets a plain `User:` \u002F `Assistant:` template whose replies end with the EOS token,\n  so the model learns to stop; a notice says so. To choose another, set `chat_template` in the config\n  or pass `--chat-template`: `plain`, a Jinja file, or a Jinja string. The template is saved with the\n  trained model, so later commands use it without the option.\n- **Base models with a chat template.** A base model may ship a chat template whose special tokens it\n  never trained (Qwen3-Base: `\u003C|im_start|>`, `\u003C|im_end|>`, `\u003Cthink>`). LoRA cannot learn those\n  embeddings, so `sft` stops with the options instead of training a model that never ends its reply;\n  use `lora: false` (`configs\u002Fsft_qwen3_full.yaml`). Generation stops at the template's end-of-turn\n  token as well as EOS, and both are written to the saved model's `generation_config.json`, so\n  transformers and vLLM stop there too.\n- **Template options** (`--template-arg KEY=VALUE`, `chat_template_kwargs` in the GRPO config;\n  `--no-think` is `enable_thinking=false`) are passed to the template; templates that do not use\n  them ignore them.\n- **Architectures.** Memory and disk estimates read layer, head and vocabulary sizes under each\n  family's own config names (Llama\u002FQwen, GPT-2, Falcon, ChatGLM, multimodal configs, ...). For a\n  model with no attention heads (e.g. a state-space model), generation starts at batch 8 and adapts.\n- **No CUDA GPU.** SFT, evaluation and GRPO with `use_vllm: false` run on the CPU (slow, but\n  fine for small models); GRPO with vLLM and the pass-rate filter need a Linux GPU.\n\n### SFT (`configs\u002Fsft_qwen3.yaml` with LoRA; `configs\u002Fsft_qwen3_full.yaml` and `configs\u002Fsft_qwen3_0.6b_base.yaml` with full fine-tuning)\n| Field | Default | Meaning |\n|---|---|---|\n| `model`, `train_file`, `output_dir` | required | base model, JSONL of prompt\u002Fcompletion rows, where to write |\n| `eval_file` | none | optional JSONL evaluated each epoch |\n| `max_length` | 1024 | longer rows are **dropped**, never truncated (the length distribution is printed) |\n| `epochs`, `lr` | 2, 1e-4 | 1e-4 suits LoRA; use ~1e-5 for full fine-tuning |\n| `batch_size`, `grad_accum` | 8, 4 | per-device batch and accumulation (effective batch 32) |\n| `warmup_ratio` | 0.03 | cosine schedule |\n| `lora`, `lora_r`, `lora_alpha`, `lora_dropout` | true, 32, 64, 0.05 | LoRA on all linear layers; `lora: false` = full fine-tuning (fp32 master weights) |\n| `seed`, `logging_steps`, `save_strategy` | 42, 10, `epoch` | |\n| `chat_template` | none | none = the model's own (plain if it has none); `plain`, a Jinja file or string ([Student model](#student-model)) |\n| `extra` | `{}` | any TRL `SFTConfig` argument, including ones the framework sets (`report_to`, `lr_scheduler_type`, `gradient_checkpointing`, ...; overrides are printed); arguments with a field above are set through that field |\n\nWith LoRA, a merged copy is saved to `output_dir\u002Fmerged` for evaluation and serving. Each saved model\ngets `trained_ids.txt`, the ids of the rows it was trained on (rows from `teacher` and `labels` carry\nthem), so GRPO never validates on them. Checkpoints hold\nweights only and one is kept (`extra: {save_only_model: false, save_total_limit: null}` keeps\noptimizer state and every checkpoint); disk space for what will be written is checked before training.\n\n### GRPO (`configs\u002Fgrpo_gsm8k_qwen3_1.7b_base.yaml`)\n| Field | Default | Meaning |\n|---|---|---|\n| `model`, `output_dir` | required | start checkpoint (the SFT model; `--model` overrides) and where to write |\n| `num_generations` | 8 | completions per prompt; the group is the baseline for the advantage |\n| `max_prompt_length`, `max_completion_length` | 768, 256 | token limits; TRL \u003C 0.28 keeps the last `max_prompt_length` tokens of a longer prompt, later TRL (which removed the argument) leaves such prompts out, with a count |\n| `temperature` | 1.0 | sampling temperature for rollouts |\n| `lr` | 1e-6 | learning rate (full fine-tuning keeps fp32 master weights) |\n| `beta` | 0.0 | KL coefficient to the start model (0 = no reference model) |\n| `epsilon`, `loss_type` | 0.2, `dapo` | clipping and loss; `extra: {epsilon_high: 0.28}` for DAPO clip-higher |\n| `batch_size`, `grad_accum` | 8, 4 | completions per device step and accumulation; the micro-batch shrinks automatically if long completions would not fit, keeping the product |\n| `max_steps` | 500 | or set by `--epochs` |\n| `use_vllm`, `vllm_mode`, `vllm_gpu_memory_utilization` | true, `colocate`, 0.3 | rollouts with vLLM on the training GPU |\n| `lora`, `lora_r`, `lora_alpha`, `lora_dropout` | false, 32, 64, 0.0 | true = LoRA on all linear layers (low-precision base); LoRA usually needs a higher `lr` (~1e-5 to 1e-4) |\n| `chat_template` | none | as for SFT; a model trained with distillops already carries its template |\n| `chat_template_kwargs` | `{}` | e.g. `{enable_thinking: false}`; prompts are rendered by the framework, so this works with any TRL version |\n| `eval_every` | 25 | validation check every N steps (0 = off) |\n| `eval_examples` | 200 | validation prompts: the task's `valid` split if it has one, else held out of training (at most 20%); never prompts the start model was trained on (its `trained_ids.txt`): with none left, selection is off and `output_dir` holds the final model; scores are printed with their standard error |\n| `eval_patience` | 0 | stop after N checks without improvement (0 = never stop early) |\n| `entropy_floor_ratio`, `entropy_patience` | 0.1, 2 | stop when entropy stays below 10% of its starting value for 2 logs (0 = off) |\n| `seed`, `logging_steps`, `save_steps` | 42, 5, 100 | |\n| `extra` | `{}` | any TRL `GRPOConfig` argument, as for SFT (e.g. `epsilon_high`, `report_to`); checkpoints default to weights only, one kept (`save_only_model`, `save_total_limit`) |\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cb>Outputs\u003C\u002Fb>\u003C\u002Fsummary>\n\n| Command | Writes |\n|---|---|\n| `teacher` | `results\u002F\u003Ctask>\u002Fteacher_\u003Csplit>_n\u003Cn>[_\u003Ctask args>]\u002F`: `run.json` (teacher, task settings, and hashes of the teacher prompt and task code), `accepted.jsonl` (SFT rows), `log.jsonl` (every attempt and verdict; reruns resume from it), `stats.json` (yield, rejection reasons, token usage) |\n| `labels` | `data\u002Fsft\u002F\u003Ctask>\u002Flabels_\u003Csplit>_n\u003Cn>[_\u003Ctask args>].jsonl` |\n| `sft` | `output_dir\u002F` (LoRA adapter, or the model with full fine-tuning), `output_dir\u002Fmerged\u002F` (LoRA merged into the model), `trained_ids.txt` in each, `sft_summary.json` |\n| `eval` | `results\u002F\u003Ctask>\u002Feval\u002F\u003Ctag>\u002Fmetrics.json` and `predictions.jsonl` (every completion and its score); `\u003Ctag>` defaults to the model folder's name (`\u003Crun>-merged` for an SFT model) |\n| `grpo --filter-only` | `output_dir\u002Fpass_rate_filter.json` (statistics and advice), `output_dir\u002Fpass_rate_kept.txt` |\n| `grpo` | `output_dir\u002F` = **best model on validation** (a copy of the start model if nothing beat it; the final model when there is no validation), `output_dir\u002Flast\u002F` = final model, `trained_ids.txt`, `output_dir\u002Fvalidation.json` (scores per check, best step, weight change, entropy stop) |\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cb>What the framework handles\u003C\u002Fb>\u003C\u002Fsummary>\n\n- **Teacher client** (`distillops\u002Fteacher.py`): any OpenAI-compatible endpoint (hosted API, vLLM, SGLang, ...); configurable concurrency,\n  retries with backoff for network errors, rate limits and server errors only, an on-disk response cache\n  (a re-run sends no repeated request) and a token counter.\n- **Adaptive rejection sampling** (`distillops\u002Frejection.py`): retry only failed examples, up to\n  `--max-attempts`; append-only logs so a killed run resumes where it stopped.\n- **SFT** (`distillops\u002Fsft.py`): TRL, completion-only loss, over-long rows dropped (never truncated),\n  LoRA, and a printout of exactly which tokens carry loss.\n- **Evaluation** (`distillops\u002Fevaluate.py`): batched generation + `Task.score`; tasks can override decoding.\n- **GRPO** (`distillops\u002Fgrpo.py`): `Task.score` becomes the reward, so RL optimises the reported metric;\n  pass-rate filter, validation-based checkpoint selection, entropy guard.\n- **Hardware-agnostic** (`distillops\u002Fprecision.py`, `memory.py`, `preflight.py`): precision chosen from\n  the GPU, batch sizes from free memory and the model's KV-cache size, disk checked before training.\n- **Model-agnostic** (`distillops\u002Fchat.py`, `memory.py`): any causal LM; a chat template for models\n  without one, and config sizes read under each architecture's field names.\n\n\u003C\u002Fdetails>\n\n## Related work\n- **Distillation toolkits.** [EasyDistill](https:\u002F\u002Fgithub.com\u002Fmodelscope\u002Feasydistill) (Alibaba, EMNLP 2025\n  demos) covers black-box data synthesis across text, vision-language, text-to-image and text-to-video,\n  with outputs for LLaMA-Factory \u002F ms-swift; [DistillKit](https:\u002F\u002Fgithub.com\u002Farcee-ai\u002FDistillKit) focuses\n  on logit-level distillation. distillops is narrower (text tasks, plus image prompts through its\n  [vision extension](extensions\u002Fvision\u002FREADME.md)) and goes deeper on the training loop:\n  verification-based rejection sampling, no-teacher controls, built-in GRPO and its diagnostics.\n  Training itself runs on [TRL](https:\u002F\u002Fgithub.com\u002Fhuggingface\u002Ftrl).\n- **LLM recommenders into sequential recommenders:** see [tasks\u002Frec\u002FREADME.md](tasks\u002Frec\u002FREADME.md#related-work).\n\n## Layout\n```\ndistillops\u002F       the framework: teacher, task interface, rejection sampling, sft, evaluate, grpo,\n                  chat (templates), precision \u002F memory \u002F preflight, cli\ntasks\u002F            the three included example tasks (not needed for your own):\n  math\u002F           GSM8K, also the reference implementation of a Task\n  pii\u002F            personal-information detection (its own README.md): labels, entity parsing and\n                  rule checks, F1 and leak rate\n  rec\u002F            recommendation (its own README.md): data, SASRec baseline and distillation, prompts, title trie,\n                  constrained beams, item embeddings; resources\u002F holds the SFT user list\nscripts\u002F          check_task.py (any task); pii_*.py: the PII example (prepare, rule check, teacher eval);\n                  rec_*.py: the recommendation example (prepare, SASRec sweep, build SFT data,\n                  LLM \u002F SASRec eval, paired comparison, SASRec distillation, two-stage)\nconfigs\u002F          teacher, SFT and GRPO configs (example settings)\nassets\u002F           README figures\ntests\u002F            unit tests; no network or GPU needed\nextensions\u002Fvision\u002F  image prompts (its own README.md, package, configs and tests), with the receipts\n                  example in vision_tasks\u002Fcord\u002F\n```\n`data\u002F`, `results\u002F`, `checkpoints\u002F` and `cache\u002F` are created at run time and not tracked.\n\nData: GSM8K (MIT); OpenPII-1M by Ai4Privacy (CC-BY-4.0); CORD-v2 by NAVER Clova (CC-BY-4.0); MiniOneRec's preprocessed Amazon splits (Apache-2.0) of the Amazon Reviews dataset\n(McAuley Lab). Code: MIT.\n","distillops 是一个黑箱大语言模型（LLM）蒸馏框架，支持文本与图像输入，可将任意可验证任务的教师模型（如托管API或本地部署的Qwen、Qwen3-VL等）知识蒸馏为轻量级学生模型。其核心流程包括：调用教师API生成响应、基于自定义验证逻辑进行拒绝采样、监督微调（SFT）及基于任务得分奖励的GRPO强化学习优化。全程仅依赖教师输出文本\u002F图像结果，无需访问其权重或内部 logits，兼容 OpenAI 兼容接口及 vLLM\u002FSGLang 等推理服务。适用于私有化部署场景下的字段抽取、文档理解、数学求解、视觉文档解析等需高可控性与低延迟的垂直任务。",2,"2026-11-24 04:39:31","CREATED_QUERY"]