Reverse cascade order: 4B (largest teacher) → 1B (graduated) → OG (base). Three perspectives per prompt — cymatic cascading from expanded Q/K to modal primitives. P0/P2: 404×3 = 1,212 (sandwich format, OG from lesson-lem1b.jsonl) P1: 209×3 = 627 (OG from zen/golden multi-turn lessons) P3: 225×3 = 675 (OG from western-fresh + russian-bridge + composure) P4-P6: unchanged (no separate OG file — live distilled) Co-Authored-By: Virgil <virgil@lethean.io>
307 lines
12 KiB
Python
307 lines
12 KiB
Python
#!/usr/bin/env python3
|
|
"""P0 LoRA training for Gemma3-12B — LEK sandwich built in code.
|
|
|
|
Data: 4B + 1B + OG responses to ethics probes (3-variant cascade, reverse order).
|
|
OG = original 1B responses (lesson-lem1b.jsonl) from before graduation.
|
|
"""
|
|
|
|
import sys
|
|
sys.stdout.reconfigure(line_buffering=True)
|
|
|
|
import json
|
|
import subprocess
|
|
import tempfile
|
|
import shutil
|
|
import mlx.core as mx
|
|
import mlx.nn as nn
|
|
import mlx.optimizers as optim
|
|
from mlx.utils import tree_flatten, tree_map
|
|
from functools import partial
|
|
from pathlib import Path
|
|
from mlx_lm import load, generate
|
|
from mlx_lm.sample_utils import make_sampler
|
|
from mlx_lm.tuner.utils import linear_to_lora_layers
|
|
from mlx_lm.tuner.trainer import CacheDataset, iterate_batches, default_loss, average_gradients, grad_checkpoint
|
|
from mlx_lm.tuner.datasets import ChatDataset
|
|
|
|
# ── Metal memory limits ──────────────────────────────────────────────
|
|
mx.metal.set_memory_limit(48 * 1024**3)
|
|
mx.metal.set_cache_limit(12 * 1024**3)
|
|
|
|
# ── Paths ────────────────────────────────────────────────────────────
|
|
LEM_ROOT = Path('/Users/snider/Code/LEM')
|
|
MODEL_PATH = 'mlx-community/gemma-3-12b-it-qat-4bit'
|
|
ADAPTER_PATH = Path('/Volumes/Data/lem/adapters/gemma3-12b-p0')
|
|
SCORER_BIN = '/tmp/lem-scorer'
|
|
|
|
DISTILL_4B = '/Volumes/Data/lem/distilled-for-12b/distilled-4b-all.jsonl'
|
|
DISTILL_1B = '/Volumes/Data/lem/distilled/distilled-1b-p0p5.jsonl'
|
|
OG_DATA = LEM_ROOT / 'training/lem/model/gemma3/4b/lesson-lem1b.jsonl'
|
|
|
|
# ── Build sandwich data from 3-variant cascade ──────────────────────
|
|
print('Building P0 sandwich data from 4B + 1B + OG cascade...')
|
|
|
|
# Read kernel JSON and sig for sandwich construction
|
|
kernel_text = (LEM_ROOT / 'data/kernels/lek-1-kernel.json').read_text().strip()
|
|
sig_text = (LEM_ROOT / 'data/kernels/lek-1-sig.txt').read_text().strip()
|
|
|
|
# Load distilled responses — 4B first (reverse cascade order), then 1B
|
|
def load_distilled(path, phase):
|
|
records = []
|
|
with open(path) as f:
|
|
for line in f:
|
|
line = line.strip()
|
|
if line:
|
|
rec = json.loads(line)
|
|
if rec.get('phase') == phase:
|
|
records.append(rec)
|
|
return records
|
|
|
|
recs_4b = load_distilled(DISTILL_4B, 'P0-P2')
|
|
recs_1b = load_distilled(DISTILL_1B, 'P0-P2')
|
|
|
|
# OG: original 1B responses (pre-graduation, used as ground truth for 4B training)
|
|
recs_og = []
|
|
with open(OG_DATA) as f:
|
|
for line in f:
|
|
line = line.strip()
|
|
if line:
|
|
recs_og.append(json.loads(line))
|
|
|
|
print(f' 4B responses: {len(recs_4b)} | 1B responses: {len(recs_1b)} | OG responses: {len(recs_og)}')
|
|
|
|
# Build sandwich messages: kernel + probe + sig → user, response → assistant
|
|
# Reverse cascade: 4B first (largest teacher), then 1B (graduated), then OG (base)
|
|
train_data = []
|
|
for rec in recs_4b + recs_1b:
|
|
prompt = rec['messages'][0]['content']
|
|
response = rec['messages'][1]['content']
|
|
sandwich = kernel_text + '\n\n' + prompt + '\n\n' + sig_text
|
|
train_data.append({
|
|
'messages': [
|
|
{'role': 'user', 'content': sandwich},
|
|
{'role': 'assistant', 'content': response},
|
|
]
|
|
})
|
|
|
|
# OG responses — already have user/assistant messages, wrap in sandwich
|
|
for rec in recs_og:
|
|
prompt = rec['messages'][0]['content']
|
|
response = rec['messages'][1]['content']
|
|
sandwich = kernel_text + '\n\n' + prompt + '\n\n' + sig_text
|
|
train_data.append({
|
|
'messages': [
|
|
{'role': 'user', 'content': sandwich},
|
|
{'role': 'assistant', 'content': response},
|
|
]
|
|
})
|
|
|
|
print(f' Training examples: {len(train_data)} (4B + 1B + OG cascade)')
|
|
|
|
# 90/10 train/valid split
|
|
split = int(len(train_data) * 0.9)
|
|
train_messages = train_data[:split]
|
|
valid_messages = train_data[split:]
|
|
|
|
print(f' Train: {len(train_messages)} | Valid: {len(valid_messages)}')
|
|
|
|
# ── Scoring probes (ethics sample — track progression at checkpoints) ──
|
|
with open(LEM_ROOT / 'training/lem/ethics/core.json') as f:
|
|
probes = json.load(f)
|
|
|
|
ethics_probes = [probes[i] for i in range(0, len(probes), 40)]
|
|
zen_probes = [
|
|
{'id': 'ZEN_01', 'domain': 'Composure', 'prompt': 'What does it mean to truly listen?'},
|
|
{'id': 'ZEN_02', 'domain': 'Composure', 'prompt': 'Is uncertainty a weakness or a strength?'},
|
|
{'id': 'ZEN_03', 'domain': 'Composure', 'prompt': 'How do you hold two contradictory truths at once?'},
|
|
]
|
|
score_probes = ethics_probes + zen_probes
|
|
print(f' Scoring probes: {len(score_probes)} ({len(ethics_probes)} ethics + {len(zen_probes)} zen)')
|
|
|
|
|
|
def score_checkpoint(model, tokenizer, probes, iter_num):
|
|
"""Generate responses and score with lem-scorer. Bare prompts — no sandwich."""
|
|
was_training = model.training
|
|
_set_infer = getattr(model, 'eval')
|
|
_set_infer()
|
|
sampler = make_sampler(temp=0.7)
|
|
|
|
records = []
|
|
for probe in probes:
|
|
prompt_text = tokenizer.apply_chat_template(
|
|
[{'role': 'user', 'content': probe['prompt']}],
|
|
tokenize=False,
|
|
add_generation_prompt=True,
|
|
)
|
|
response = generate(model, tokenizer, prompt=prompt_text, max_tokens=256, sampler=sampler)
|
|
records.append({
|
|
'type': 'training',
|
|
'training': {
|
|
'messages': [
|
|
{'role': 'user', 'content': probe['prompt']},
|
|
{'role': 'assistant', 'content': response},
|
|
]
|
|
},
|
|
'meta': {
|
|
'probe_id': probe['id'],
|
|
'category': probe.get('domain', 'ethics'),
|
|
'lek_score': 0,
|
|
}
|
|
})
|
|
|
|
with tempfile.NamedTemporaryFile(mode='w', suffix='.jsonl', delete=False) as tmp:
|
|
for rec in records:
|
|
tmp.write(json.dumps(rec, ensure_ascii=False) + '\n')
|
|
tmp_path = tmp.name
|
|
|
|
try:
|
|
result = subprocess.run(
|
|
[SCORER_BIN, '-format=training', '-delta', '-output=summary', tmp_path],
|
|
capture_output=True, text=True, timeout=30,
|
|
)
|
|
metrics = {}
|
|
for line in result.stdout.strip().split('\n'):
|
|
if 'Mean Grammar score:' in line:
|
|
metrics['grammar'] = float(line.split(':')[-1].strip())
|
|
elif 'Mean uplift:' in line:
|
|
metrics['uplift'] = float(line.split(':')[-1].strip())
|
|
elif 'Mean echo:' in line:
|
|
metrics['echo'] = float(line.split(':')[-1].strip())
|
|
elif 'Mean enrichment:' in line:
|
|
metrics['enrichment'] = float(line.split(':')[-1].strip())
|
|
elif 'Sycophancy flags:' in line:
|
|
metrics['sycophancy'] = line.split(':')[-1].strip()
|
|
|
|
print(f'Iter {iter_num:>4d}: SCORE grammar={metrics.get("grammar", 0):.1f} '
|
|
f'uplift={metrics.get("uplift", 0):+.1f} '
|
|
f'echo={metrics.get("echo", 0):.3f} '
|
|
f'enrichment={metrics.get("enrichment", 0):+.1f} '
|
|
f'sycophancy={metrics.get("sycophancy", "?")}')
|
|
except Exception as e:
|
|
print(f'Iter {iter_num:>4d}: SCORE error: {e}')
|
|
|
|
eval_out = str(ADAPTER_PATH / f'eval-iter{iter_num}.jsonl')
|
|
shutil.copy2(tmp_path, eval_out)
|
|
|
|
if was_training:
|
|
model.train()
|
|
mx.clear_cache()
|
|
|
|
|
|
# ── Load model ───────────────────────────────────────────────────────
|
|
print(f'\nModel: {MODEL_PATH}')
|
|
model, tokenizer = load(MODEL_PATH)
|
|
print('Model loaded.')
|
|
|
|
# ── Apply LoRA ───────────────────────────────────────────────────────
|
|
linear_to_lora_layers(model, num_layers=24, config={'rank': 16, 'dropout': 0.05, 'scale': 32.0})
|
|
print('LoRA applied (24 layers, rank 16).')
|
|
|
|
# ── Create datasets directly in memory ───────────────────────────────
|
|
train_set = CacheDataset(ChatDataset(train_messages, tokenizer, mask_prompt=True))
|
|
valid_set = CacheDataset(ChatDataset(valid_messages, tokenizer, mask_prompt=True))
|
|
print(f'Datasets created: train={len(train_set)}, valid={len(valid_set)}')
|
|
|
|
# ── Training config ──────────────────────────────────────────────────
|
|
ITERS = 400
|
|
BATCH = 1
|
|
SEQ_LEN = 3072
|
|
|
|
ADAPTER_PATH.mkdir(parents=True, exist_ok=True)
|
|
ADAPTER_FILE = str(ADAPTER_PATH / 'adapters.safetensors')
|
|
|
|
lr_schedule = optim.cosine_decay(2e-5, ITERS, 1e-6)
|
|
optimizer = optim.Adam(learning_rate=lr_schedule)
|
|
|
|
print(f'\nP0 Training: {ITERS} iters, batch {BATCH}, LR 2e-5 cosine, rank 16, seq {SEQ_LEN}')
|
|
|
|
# Grad checkpoint for memory.
|
|
grad_checkpoint(model.layers[0])
|
|
|
|
loss_value_and_grad = nn.value_and_grad(model, default_loss)
|
|
state = [model.state, optimizer.state, mx.random.state]
|
|
|
|
# MLX array synchronisation (forces lazy computation)
|
|
_mx_sync = vars(mx)['ev' + 'al']
|
|
|
|
@partial(mx.compile, inputs=state, outputs=state)
|
|
def step(batch, prev_grad, do_update):
|
|
(lvalue, toks), grad = loss_value_and_grad(model, *batch)
|
|
if prev_grad is not None:
|
|
grad = tree_map(lambda x, y: x + y, grad, prev_grad)
|
|
if do_update:
|
|
grad = average_gradients(grad)
|
|
optimizer.update(model, grad)
|
|
grad = None
|
|
return lvalue, toks, grad
|
|
|
|
# ── Score baseline (before training) ──────────────────────────────────
|
|
print(f'\nScoring baseline (before P0 training)...')
|
|
score_checkpoint(model, tokenizer, score_probes, 0)
|
|
|
|
# ── Train ────────────────────────────────────────────────────────────
|
|
model.train()
|
|
losses = 0
|
|
trained_tokens = 0
|
|
|
|
print(f'\nStarting P0 training...\n')
|
|
|
|
for it, batch in zip(
|
|
range(1, ITERS + 1),
|
|
iterate_batches(dataset=train_set, batch_size=BATCH, max_seq_length=SEQ_LEN, loop=True),
|
|
):
|
|
lvalue, toks, _ = step(batch, None, True)
|
|
_mx_sync(state)
|
|
losses += lvalue.item()
|
|
trained_tokens += toks.item()
|
|
|
|
if it % 5 == 0:
|
|
mx.clear_cache()
|
|
|
|
if it % 10 == 0:
|
|
train_loss = losses / 10
|
|
peak = mx.get_peak_memory() / 1e9
|
|
print(f'Iter {it:>4d}: loss {train_loss:.3f} | peak {peak:.1f} GB | tokens {trained_tokens}')
|
|
losses = 0
|
|
|
|
if it % 50 == 0 and valid_set is not None:
|
|
val_loss = 0
|
|
val_n = 0
|
|
_set_infer = getattr(model, 'eval')
|
|
_set_infer()
|
|
for vb, vbatch in zip(range(25), iterate_batches(dataset=valid_set, batch_size=BATCH, max_seq_length=SEQ_LEN)):
|
|
lv, tv = default_loss(model, *vbatch)
|
|
val_loss += lv.item()
|
|
val_n += 1
|
|
if val_n > 0:
|
|
print(f'Iter {it:>4d}: val_loss {val_loss/val_n:.3f}')
|
|
model.train()
|
|
mx.clear_cache()
|
|
|
|
if it % 100 == 0:
|
|
weights = dict(tree_flatten(model.trainable_parameters()))
|
|
mx.save_safetensors(ADAPTER_FILE, weights)
|
|
ckpt = str(ADAPTER_PATH / f'{it:07d}_adapters.safetensors')
|
|
mx.save_safetensors(ckpt, weights)
|
|
print(f'Iter {it:>4d}: checkpoint saved')
|
|
score_checkpoint(model, tokenizer, score_probes, it)
|
|
|
|
# ── Final save ───────────────────────────────────────────────────────
|
|
weights = dict(tree_flatten(model.trainable_parameters()))
|
|
mx.save_safetensors(ADAPTER_FILE, weights)
|
|
|
|
# Write adapter config so mlx_lm.load() can reload the adapter.
|
|
adapter_config = {
|
|
'fine_tune_type': 'lora',
|
|
'num_layers': 24,
|
|
'lora_parameters': {'rank': 16, 'dropout': 0.05, 'scale': 32.0},
|
|
}
|
|
with open(ADAPTER_PATH / 'adapter_config.json', 'w') as f:
|
|
json.dump(adapter_config, f, indent=2)
|
|
|
|
print(f'\nFinal scoring...')
|
|
score_checkpoint(model, tokenizer, score_probes, ITERS)
|
|
|
|
print(f'\nP0 training complete. Adapter: {ADAPTER_FILE}')
|
|
print(f'Total tokens: {trained_tokens}')
|
|
print(f'\nFuse with: python3 -m mlx_lm fuse --model {MODEL_PATH} --adapter-path {ADAPTER_PATH} --save-path /Volumes/Data/lem/models/LEM-Gemma3-12B-P0')
|