File size: 15,661 Bytes
ef8d640
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#!/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 ───────────────────────────────────────────────────────────────

@dataclass
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 ──────────────────────────────────────────────────────────

@dataclass
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()