| """Distill accepted data into weights (LoRA SFT), then DISCARD the raw data. |
| |
| This realizes "weighted, not stored": curated + critique-revised pairs are folded into |
| the model's parameters via supervised fine-tuning, then the text items are deleted. Only |
| the weights and a small replay buffer survive -- the model carries the knowledge, not a |
| growing corpus on disk. |
| """ |
| import json |
| import os |
| from pathlib import Path |
|
|
|
|
| def distill(base_or_adapter, pairs, out_dir, lr, lora_r, lora_alpha, discard_raw=True): |
| from datasets import Dataset |
| from peft import LoraConfig |
| from transformers import AutoTokenizer |
| from trl import SFTConfig, SFTTrainer |
|
|
| tok = AutoTokenizer.from_pretrained(base_or_adapter) |
|
|
| def fmt(ex): |
| msg = [{"role": "user", "content": ex["instruction"]}, |
| {"role": "assistant", "content": ex["response"]}] |
| return {"text": tok.apply_chat_template(msg, tokenize=False)} |
|
|
| ds = Dataset.from_list(pairs).map(fmt) |
| args = SFTConfig(output_dir=out_dir, per_device_train_batch_size=2, |
| gradient_accumulation_steps=4, learning_rate=lr, |
| num_train_epochs=1, bf16=True, gradient_checkpointing=True, |
| logging_steps=10, save_strategy="no", report_to="none", |
| dataset_text_field="text", max_length=1024) |
| peft_cfg = LoraConfig(r=lora_r, lora_alpha=lora_alpha, task_type="CAUSAL_LM", |
| target_modules=["q_proj", "k_proj", "v_proj", "o_proj"]) |
| trainer = SFTTrainer(model=base_or_adapter, args=args, train_dataset=ds, peft_config=peft_cfg) |
| trainer.train() |
| |
| merged = trainer.model.merge_and_unload() |
| merged.save_pretrained(out_dir) |
| tok.save_pretrained(out_dir) |
|
|
| if discard_raw: |
| |
| pairs.clear() |
| return out_dir |
|
|
|
|
| def keep_replay(pairs, frac, path): |
| """Persist a tiny stratified replay slice (real, high-score) to fight forgetting.""" |
| import random |
| top = sorted(pairs, key=lambda x: -x.get("score", 0)) |
| keep = top[:max(1, int(len(top) * frac))] |
| Path(path).parent.mkdir(parents=True, exist_ok=True) |
| with open(path, "a", encoding="utf-8") as f: |
| for k in keep: |
| f.write(json.dumps(k) + "\n") |
| return len(keep) |
|
|