Exact reproduction of all 7 CL-BPL phases for Gemma3-12B: - P0: LEK sandwich ethics (400 iters, LR 2e-5) - P1: Zen composure (300 iters, LR 1e-5) - P2: LEK sandwich reinforcement (300 iters, LR 1e-5) - P3: Freeflow multi-source (300 iters, LR 1e-5) - P4: 1B teacher tension distillation (300 iters, LR 1e-5) - P5: 1B teacher creative distillation (300 iters, LR 1e-5) - P6: Golden set graduation (13479 iters, LR 1e-5) Only model-size differences from 4B: 48GB/12GB Metal limits, 24 LoRA layers (vs 16), 12B base model path. All phases score at checkpoint cadence via lem-scorer. Previous wrong 12B models preserved as -no-axioms control group. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
271 lines
11 KiB
Python
271 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""P2 (Final LEK Sandwich) LoRA training for LEM-Gemma3-4B-P1 — ethics on composure."""
|
|
|
|
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(24 * 1024**3)
|
|
mx.metal.set_cache_limit(8 * 1024**3)
|
|
|
|
# ── Paths ────────────────────────────────────────────────────────────
|
|
LEM_ROOT = Path('/Users/snider/Code/LEM')
|
|
MODEL_PATH = '/Volumes/Data/lem/models/LEM-Gemma3-4B-P1'
|
|
ADAPTER_PATH = Path('/Volumes/Data/lem/adapters/gemma3-4b-p2')
|
|
SCORER_BIN = '/tmp/lem-scorer'
|
|
|
|
# ── Build sandwich data in memory ────────────────────────────────────
|
|
print('Building P2 sandwich data...')
|
|
|
|
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()
|
|
|
|
with open(LEM_ROOT / 'training/lem/ethics/core.json') as f:
|
|
all_probes = json.load(f)
|
|
|
|
responses = []
|
|
with open(LEM_ROOT / 'training/lem/model/gemma3/4b/lesson-lem1b.jsonl') as f:
|
|
for line in f:
|
|
line = line.strip()
|
|
if line:
|
|
responses.append(json.loads(line))
|
|
|
|
print(f' Probes: {len(all_probes)} | Responses: {len(responses)}')
|
|
|
|
train_data = []
|
|
for i, probe in enumerate(all_probes):
|
|
if i >= len(responses):
|
|
break
|
|
sandwich = kernel_text + '\n\n' + probe['prompt'] + '\n\n' + sig_text
|
|
train_data.append({
|
|
'messages': [
|
|
{'role': 'user', 'content': sandwich},
|
|
{'role': 'assistant', 'content': responses[i]['messages'][1]['content']},
|
|
]
|
|
})
|
|
|
|
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 (sandwich format — model should handle LEK naturally) ──
|
|
score_probes = [all_probes[i] for i in range(0, len(all_probes), 20)]
|
|
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?'},
|
|
]
|
|
all_score_probes = score_probes + zen_probes
|
|
print(f' Scoring probes: {len(all_score_probes)} ({len(score_probes)} ethics + {len(zen_probes)} zen)')
|
|
|
|
# MLX array sync helper (mx .eval — not Python eval)
|
|
_mx_sync = getattr(mx, 'eval')
|
|
|
|
|
|
def score_checkpoint(model, tokenizer, kernel, sig, probes, iter_num):
|
|
"""Generate responses on scoring probes and run through lem-scorer."""
|
|
was_training = model.training
|
|
model.eval() # nn.Module mode switch
|
|
sampler = make_sampler(temp=0.7)
|
|
|
|
records = []
|
|
for probe in probes:
|
|
# Ethics probes get sandwich, zen probes get bare prompt
|
|
if probe.get('domain', '') == 'Composure':
|
|
prompt_content = probe['prompt']
|
|
else:
|
|
prompt_content = kernel + '\n\n' + probe['prompt'] + '\n\n' + sig
|
|
|
|
prompt_text = tokenizer.apply_chat_template(
|
|
[{'role': 'user', 'content': prompt_content}],
|
|
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 fused P1 model ──────────────────────────────────────────────
|
|
print(f'\nModel: {MODEL_PATH} (fused P1 = P0 ethics + zen composure)')
|
|
model, tokenizer = load(MODEL_PATH)
|
|
print('P1 model loaded.')
|
|
|
|
# ── Apply LoRA for P2 ────────────────────────────────────────────────
|
|
linear_to_lora_layers(model, num_layers=16, config={'rank': 16, 'dropout': 0.05, 'scale': 32.0})
|
|
print('LoRA applied (16 layers, rank 16).')
|
|
|
|
# ── Datasets ─────────────────────────────────────────────────────────
|
|
train_set = CacheDataset(ChatDataset(train_messages, tokenizer, mask_prompt=True))
|
|
valid_set = CacheDataset(ChatDataset(valid_messages, tokenizer, mask_prompt=True))
|
|
print(f'Datasets: train={len(train_set)}, valid={len(valid_set)}')
|
|
|
|
# ── Training config ──────────────────────────────────────────────────
|
|
ITERS = 300
|
|
BATCH = 1
|
|
SEQ_LEN = 3072
|
|
|
|
ADAPTER_PATH.mkdir(parents=True, exist_ok=True)
|
|
ADAPTER_FILE = str(ADAPTER_PATH / 'adapters.safetensors')
|
|
|
|
# Gentle LR — reinforcing LEK on a calm foundation, not reshaping
|
|
lr_schedule = optim.cosine_decay(1e-5, ITERS, 5e-7)
|
|
optimizer = optim.Adam(learning_rate=lr_schedule)
|
|
|
|
print(f'\nP2 Training: {ITERS} iters, batch {BATCH}, LR 1e-5 cosine, rank 16, seq {SEQ_LEN}')
|
|
|
|
grad_checkpoint(model.layers[0])
|
|
loss_value_and_grad = nn.value_and_grad(model, default_loss)
|
|
state = [model.state, optimizer.state, mx.random.state]
|
|
|
|
|
|
@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 P1 baseline (before P2 training) ────────────────────────────
|
|
print(f'\nScoring P1 baseline (before P2 training)...')
|
|
score_checkpoint(model, tokenizer, kernel_text, sig_text, all_score_probes, 0)
|
|
|
|
# ── Train ────────────────────────────────────────────────────────────
|
|
model.train()
|
|
losses = 0
|
|
trained_tokens = 0
|
|
|
|
print(f'\nStarting P2 LEK sandwich 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
|
|
model.eval() # nn.Module mode switch
|
|
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 % 50 == 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, kernel_text, sig_text, all_score_probes, it)
|
|
|
|
# ── Final save ───────────────────────────────────────────────────────
|
|
weights = dict(tree_flatten(model.trainable_parameters()))
|
|
mx.save_safetensors(ADAPTER_FILE, weights)
|
|
|
|
adapter_config = {
|
|
'fine_tune_type': 'lora',
|
|
'num_layers': 16,
|
|
'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, kernel_text, sig_text, all_score_probes, ITERS)
|
|
|
|
print(f'\nP2 LEK sandwich training complete. Adapter: {ADAPTER_FILE}')
|
|
print(f'Total tokens: {trained_tokens}')
|
|
print(f'\nBaselines for comparison:')
|
|
print(f' P0 best (iter 450): grammar=62.1 uplift=+1.7 sycophancy=1/21 (5%)')
|
|
print(f' P1 best (iter 150): grammar=61.8 uplift=+2.5 sycophancy=0/16 (0%)')
|
|
print(f' If P2 best >= P0 grammar with P1 composure, the curriculum worked.')
|