Datasets:
Download scripts/finetune_demo.py from crontixdev/fable-5-premium: direct link, hf CLI and curl.
- Browser
- Download file 15.7 kB
-
https://huggingface.co/datasets/crontixdev/fable-5-premium/resolve/main/scripts/finetune_demo.py
- Command line
-
hf download hf://datasets/crontixdev/fable-5-premium/scripts/finetune_demo.py
-
curl -L -o finetune_demo.py https://huggingface.co/datasets/crontixdev/fable-5-premium/resolve/main/scripts/finetune_demo.py
15.7 kB
| #!/usr/bin/env python3 | |
| """ | |
| Fable-5 Premium: Fine-Tuning Demo | |
| ================================== | |
| A complete end-to-end demonstration of fine-tuning on the | |
| Fable-5 Premium Dataset β shows agentic tool-use behaviour | |
| transfer from Claude Fable-5 traces to a small open model. | |
| What this demo measures: | |
| - Tool-call formatting accuracy (before vs after fine-tune) | |
| - Multi-turn agent coherence | |
| - Code-writing quality improvement | |
| Requirements: | |
| pip install unsloth datasets transformers trl accelerate | |
| Usage: | |
| # Full run (fine-tune + eval β ~10 min on a MacBook) | |
| python scripts/finetune_demo.py --mode full | |
| # Eval only (load existing adapter) | |
| python scripts/finetune_demo.py --mode eval --adapter path/to/lora | |
| # Quick sanity check (1 batch, no training) | |
| python scripts/finetune_demo.py --mode quick | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import random | |
| import re | |
| import sys | |
| from dataclasses import dataclass, field | |
| from typing import Dict, List, Optional | |
| # βββ Config βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class Config: | |
| """Demo configuration β tweak for your hardware.""" | |
| # Dataset | |
| hf_dataset: str = "saidutta69/fable-5-premium" | |
| hf_config: str = "openai_chat" | |
| max_train_samples: int = 500 # Use 500 for demo speed; set to -1 for full | |
| max_seq_length: int = 4096 | |
| # Model | |
| base_model: str = "unsloth/Qwen2.5-1.5B-bnb-4bit" # 4-bit, runs on 8GB | |
| lora_r: int = 16 | |
| lora_alpha: int = 32 | |
| lora_dropout: float = 0.05 | |
| # Training | |
| batch_size: int = 2 | |
| grad_accum: int = 4 | |
| learning_rate: float = 2e-4 | |
| num_epochs: int = 1 | |
| output_dir: str = "./fable5-finetune-demo" | |
| # Eval | |
| eval_samples: int = 50 | |
| seed: int = 42 | |
| # βββ Data Formatting βββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def format_messages_for_training(example: Dict) -> str: | |
| """ | |
| Convert a messages array into a training string. | |
| Handles tool calls by keeping them in natural JSON-in-text format | |
| so the model learns to emit tool calls inline during generation. | |
| """ | |
| messages = example.get("messages", []) | |
| parts = [] | |
| for msg in messages: | |
| role = msg.get("role", "") | |
| content = msg.get("content", "") or "" | |
| tool_calls = msg.get("tool_calls", []) | |
| if role == "system": | |
| parts.append(f"<|system|>\n{content}\n") | |
| elif role == "user": | |
| parts.append(f"<|user|>\n{content}\n") | |
| elif role == "assistant": | |
| # Assistant may have content + tool calls | |
| text = f"<|assistant|>\n{content}" | |
| if tool_calls: | |
| # Serialise tool calls as JSON so the model learns the format | |
| calls_json = json.dumps( | |
| [{ | |
| "id": tc.get("id", ""), | |
| "type": "function", | |
| "function": { | |
| "name": tc.get("function", {}).get("name", ""), | |
| "arguments": tc.get("function", {}).get("arguments", "{}"), | |
| }, | |
| } for tc in tool_calls], | |
| indent=2, | |
| ) | |
| text += f"\n<tool_calls>\n{calls_json}\n</tool_calls>" | |
| text += "\n" | |
| parts.append(text) | |
| elif role == "tool": | |
| parts.append(f"<|tool|>\n{content}\n") | |
| return "".join(parts) + "<|assistant|>\n" | |
| # βββ Evaluation ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class EvalResult: | |
| tool_call_accuracy: float | |
| code_completion_rate: float | |
| avg_response_length: float | |
| samples: int | |
| def extract_tool_calls(text: str) -> List[Dict]: | |
| """Parse tool calls from model output.""" | |
| calls = [] | |
| # Pattern 1: JSON inside <tool_calls> tags | |
| for match in re.finditer(r'<tool_calls>\s*(.*?)\s*</tool_calls>', text, re.DOTALL): | |
| try: | |
| parsed = json.loads(match.group(1)) | |
| if isinstance(parsed, list): | |
| calls.extend(parsed) | |
| else: | |
| calls.append(parsed) | |
| except json.JSONDecodeError: | |
| pass | |
| # Pattern 2: Direct function call JSON blocks | |
| for match in re.finditer(r'\{\s*"id":\s*"[^"]+",\s*"type":\s*"function"\s*\}', text): | |
| try: | |
| calls.append(json.loads(match.group())) | |
| except json.JSONDecodeError: | |
| pass | |
| return calls | |
| def evaluate_model(model, tokenizer, eval_dataset, num_samples: int = 50) -> EvalResult: | |
| """Run a quick evaluation loop β compares model tool-call formatting against ground truth.""" | |
| random.seed(42) | |
| indices = list(range(len(eval_dataset))) | |
| random.shuffle(indices) | |
| indices = indices[:num_samples] | |
| correct_format = 0 | |
| total_tool_expected = 0 | |
| has_code = 0 | |
| response_lengths = [] | |
| for idx in indices: | |
| example = eval_dataset[idx] | |
| messages = example.get("messages", []) | |
| prompt = format_messages_for_training({"messages": messages[:-1]}) | |
| # Ground truth: does the last assistant message have tool calls? | |
| last_assistant = None | |
| for msg in reversed(messages): | |
| if msg.get("role") == "assistant": | |
| last_assistant = msg | |
| break | |
| expected_tool_calls = bool(last_assistant and last_assistant.get("tool_calls")) | |
| expected_code = bool( | |
| last_assistant | |
| and isinstance(last_assistant.get("content"), str) | |
| and len(last_assistant["content"]) > 100 | |
| ) | |
| if expected_tool_calls: | |
| total_tool_expected += 1 | |
| # Generate | |
| device = next(model.parameters()).device | |
| inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048).to(device) | |
| outputs = model.generate( | |
| **inputs, | |
| max_new_tokens=512, | |
| temperature=0.7, | |
| do_sample=True, | |
| pad_token_id=tokenizer.eos_token_id, | |
| ) | |
| response = tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True) | |
| response_lengths.append(len(response)) | |
| # Check for tool calls in output | |
| generated_calls = extract_tool_calls(response) | |
| if expected_tool_calls and generated_calls: | |
| correct_format += 1 | |
| if len(response) > 80: | |
| has_code += 1 | |
| accuracy = correct_format / total_tool_expected if total_tool_expected > 0 else 0.0 | |
| code_rate = has_code / num_samples | |
| avg_len = sum(response_lengths) / len(response_lengths) if response_lengths else 0 | |
| return EvalResult( | |
| tool_call_accuracy=accuracy, | |
| code_completion_rate=code_rate, | |
| avg_response_length=avg_len, | |
| samples=num_samples, | |
| ) | |
| # βββ Training ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def train(config: Config): | |
| """Fine-tune a model on Fable-5 Premium using Unsloth LoRA.""" | |
| print("=" * 60) | |
| print("FABLE-5 PREMIUM β FINE-TUNING DEMO") | |
| print("=" * 60) | |
| # ββ 1. Load dataset βββββββββββββββββββββββββββββββββββββββββββββββ | |
| print(f"\nπ₯ Loading dataset: {config.hf_dataset}/{config.hf_config}") | |
| from datasets import load_dataset | |
| ds = load_dataset(config.hf_dataset, config.hf_config, split="train") | |
| if config.max_train_samples > 0: | |
| ds = ds.select(range(min(config.max_train_samples, len(ds)))) | |
| print(f" Training samples: {len(ds)}") | |
| # Split into train/eval | |
| split = ds.train_test_split(test_size=config.eval_samples / len(ds), seed=config.seed) | |
| train_dataset_raw = split["train"] | |
| eval_dataset_raw = split["test"] # Keep raw messages for evaluate_model() | |
| # Format training split into text β keep eval raw for evaluation | |
| def prepare_text(examples): | |
| texts = [format_messages_for_training({"messages": msgs}) for msgs in examples["messages"]] | |
| return {"text": texts} | |
| train_dataset = train_dataset_raw.map(prepare_text, batched=True, remove_columns=train_dataset_raw.column_names) | |
| # ββ 2. Load model βββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print(f"\nπ§ Loading base model: {config.base_model}") | |
| from unsloth import FastLanguageModel | |
| model, tokenizer = FastLanguageModel.from_pretrained( | |
| model_name=config.base_model, | |
| max_seq_length=config.max_seq_length, | |
| dtype=None, | |
| load_in_4bit=True, | |
| ) | |
| # Add padding token | |
| tokenizer.pad_token = tokenizer.eos_token | |
| tokenizer.padding_side = "right" | |
| # ββ 3. Add LoRA βββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| model = FastLanguageModel.get_peft_model( | |
| model, | |
| r=config.lora_r, | |
| target_modules=["q_proj", "k_proj", "v_proj", "o_proj", | |
| "gate_proj", "up_proj", "down_proj"], | |
| lora_alpha=config.lora_alpha, | |
| lora_dropout=config.lora_dropout, | |
| use_gradient_checkpointing="unsloth", | |
| random_state=config.seed, | |
| ) | |
| print(f" Trainable params: {sum(p.numel() for p in model.parameters() if p.requires_grad):,}") | |
| # ββ 4. Evaluate BEFORE ββββββββββββββββββββββββββββββββββββββββββββ | |
| print("\nπ Evaluating BEFORE fine-tuning...") | |
| FastLanguageModel.for_inference(model) | |
| before = evaluate_model(model, tokenizer, eval_dataset_raw, config.eval_samples) | |
| print(f" Tool-call accuracy: {before.tool_call_accuracy:.1%}") | |
| print(f" Code completion: {before.code_completion_rate:.1%}") | |
| # ββ 5. Train ββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print(f"\nποΈ Starting fine-tuning ({config.num_epochs} epoch(s))...") | |
| from trl import SFTTrainer | |
| from transformers import TrainingArguments | |
| trainer = SFTTrainer( | |
| model=model, | |
| tokenizer=tokenizer, | |
| train_dataset=train_dataset, | |
| dataset_text_field="text", | |
| max_seq_length=config.max_seq_length, | |
| args=TrainingArguments( | |
| per_device_train_batch_size=config.batch_size, | |
| gradient_accumulation_steps=config.grad_accum, | |
| learning_rate=config.learning_rate, | |
| num_train_epochs=config.num_epochs, | |
| logging_steps=10, | |
| save_strategy="no", | |
| output_dir=config.output_dir, | |
| report_to="none", | |
| remove_unused_columns=False, | |
| optim="adamw_8bit", | |
| seed=config.seed, | |
| ), | |
| ) | |
| trainer.train() | |
| # ββ 6. Save adapter βββββββββββββββββββββββββββββββββββββββββββββββ | |
| os.makedirs(config.output_dir, exist_ok=True) | |
| model.save_pretrained(config.output_dir) | |
| tokenizer.save_pretrained(config.output_dir) | |
| print(f"\nπΎ Adapter saved to: {config.output_dir}/") | |
| # ββ 7. Evaluate AFTER βββββββββββββββββββββββββββββββββββββββββββββ | |
| print("\nπ Evaluating AFTER fine-tuning...") | |
| FastLanguageModel.for_inference(model) | |
| after = evaluate_model(model, tokenizer, eval_dataset_raw, config.eval_samples) | |
| print("\n" + "=" * 60) | |
| print("RESULTS") | |
| print("=" * 60) | |
| print(f" BEFORE AFTER Ξ") | |
| print(f" Tool-call acc: {before.tool_call_accuracy:>6.1%} {after.tool_call_accuracy:>6.1%} {after.tool_call_accuracy - before.tool_call_accuracy:>+6.1%}") | |
| print(f" Code rate: {before.code_completion_rate:>6.1%} {after.code_completion_rate:>6.1%} {after.code_completion_rate - before.code_completion_rate:>+6.1%}") | |
| print(f" Avg response: {before.avg_response_length:>6.0f} {after.avg_response_length:>6.0f} {after.avg_response_length - before.avg_response_length:>+6.0f}") | |
| print("=" * 60) | |
| # Save results | |
| results = {"before": before.__dict__, "after": after.__dict__} | |
| with open(os.path.join(config.output_dir, "eval_results.json"), "w") as f: | |
| json.dump(results, f, indent=2) | |
| print(f"π Results saved to: {config.output_dir}/eval_results.json") | |
| return model, tokenizer, before, after | |
| # βββ Main ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Fable-5 Premium Fine-Tuning Demo") | |
| parser.add_argument("--mode", choices=["full", "eval", "quick"], default="full", | |
| help="full = train + eval, eval = load adapter + eval, quick = sanity check") | |
| parser.add_argument("--adapter", type=str, default=None, | |
| help="Path to saved LoRA adapter (for --mode eval)") | |
| args = parser.parse_args() | |
| config = Config() | |
| if args.mode == "full": | |
| train(config) | |
| elif args.mode == "eval": | |
| if not args.adapter: | |
| print("β --adapter path required for eval mode") | |
| sys.exit(1) | |
| print("π₯ Loading dataset for eval...") | |
| from datasets import load_dataset | |
| ds = load_dataset(config.hf_dataset, config.hf_config, split="train") | |
| _, eval_dataset_raw = ds.train_test_split( | |
| test_size=config.eval_samples / len(ds), seed=config.seed | |
| ).values() | |
| print(f"π§ Loading base model + adapter from {args.adapter}...") | |
| from unsloth import FastLanguageModel | |
| from peft import PeftModel | |
| base_model, tokenizer = FastLanguageModel.from_pretrained( | |
| model_name=config.base_model, | |
| max_seq_length=config.max_seq_length, | |
| dtype=None, | |
| load_in_4bit=True, | |
| ) | |
| model = PeftModel.from_pretrained(base_model, args.adapter) | |
| FastLanguageModel.for_inference(model) | |
| result = evaluate_model(model, tokenizer, eval_dataset_raw, config.eval_samples) | |
| print(f"\nπ Evaluation results:") | |
| print(f" Tool-call accuracy: {result.tool_call_accuracy:.1%}") | |
| print(f" Code completion: {result.code_completion_rate:.1%}") | |
| elif args.mode == "quick": | |
| print("π Quick sanity check: loading dataset + model (no training)") | |
| from datasets import load_dataset | |
| ds = load_dataset(config.hf_dataset, config.hf_config, split="train") | |
| sample = ds[0] | |
| print(f" Dataset loaded: {len(ds)} samples") | |
| print(f" Sample messages: {len(sample['messages'])} turns") | |
| print(f" Formatted preview:") | |
| print(format_messages_for_training(sample)[:500]) | |
| print("β Everything works!") | |
| if __name__ == "__main__": | |
| main() | |