Upload 3 files
Browse files- hpc_fable_inject.py +217 -0
- test_recovered.py +41 -0
- train_fable.py +228 -0
hpc_fable_inject.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
hpc_fable_inject.py β FABLE 5 β HPC gate weight injection for Ornith
|
| 4 |
+
|
| 5 |
+
Extracts gate patterns from FABLE 5 training traces using HPC Pauli decomposition,
|
| 6 |
+
then injects them as an additive correction into Ornith-1.0-9B.
|
| 7 |
+
|
| 8 |
+
Formula (derived from Pauli decomposition I + X + c_ZΒ·Z of edge matrix):
|
| 9 |
+
z_i = [E[i]/Ο | ΞΌ_i/Ο | Ξ΅_i/Ο] (3 blocks Γ 4096 = 12288 dims)
|
| 10 |
+
where:
|
| 11 |
+
ΞΌ_i = Ξ£_j P(j|i)Β·E[j] β X-component: expected next embedding
|
| 12 |
+
Ξ΅_i = Ξ£_j c_Z(i,j)Β·E[j] β Z-component: Pauli-coupling-weighted sum
|
| 13 |
+
c_Z(i,j) = (1 - w_ij) / 2 β Pauli Z coefficient
|
| 14 |
+
w_ij = f_ij / β(f_iΒ·f_j) β normalized edge weight
|
| 15 |
+
|
| 16 |
+
The gate weight W is solved via ridge regression: E_nΒ·W β z,
|
| 17 |
+
then scaled to match original gate_proj weight norm (~0.012),
|
| 18 |
+
then added to the original weights: W_inj = W_orig + Ξ±Β·W_hpc.
|
| 19 |
+
|
| 20 |
+
Usage:
|
| 21 |
+
python3 hpc_fable_inject.py --data /tmp/fable5_sft.jsonl \\
|
| 22 |
+
--model ./Ornith-1.0-9B \\
|
| 23 |
+
--output ./Ornith-1.0-9B-hpc \\
|
| 24 |
+
--alpha 0.3 \\
|
| 25 |
+
--tau 0.003 \\
|
| 26 |
+
--topk 30000
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
import argparse, json, math, os, shutil, sys, time
|
| 30 |
+
from collections import Counter, defaultdict
|
| 31 |
+
from pathlib import Path
|
| 32 |
+
|
| 33 |
+
import numpy as np
|
| 34 |
+
import torch
|
| 35 |
+
from safetensors.torch import safe_open, save_file
|
| 36 |
+
from transformers import AutoTokenizer
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def load_model_shards(model_dir):
|
| 40 |
+
"""Return list of shard filenames and the weight index."""
|
| 41 |
+
index_path = Path(model_dir) / "model.safetensors.index.json"
|
| 42 |
+
with open(index_path) as f:
|
| 43 |
+
index = json.load(f)
|
| 44 |
+
shards = sorted(set(index["weight_map"].values()))
|
| 45 |
+
return shards, index
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def save_model_shards(src_dir, dst_dir, shards, modify_fn):
|
| 49 |
+
"""Load each shard, apply modify_fn to selected tensors, save."""
|
| 50 |
+
dst_dir = Path(dst_dir)
|
| 51 |
+
dst_dir.mkdir(parents=True, exist_ok=True)
|
| 52 |
+
for shard_name in shards:
|
| 53 |
+
src_path = Path(src_dir) / shard_name
|
| 54 |
+
dst_path = dst_dir / shard_name
|
| 55 |
+
tensors = {}
|
| 56 |
+
with safe_open(str(src_path), framework="pt") as sf:
|
| 57 |
+
for k in sf.keys():
|
| 58 |
+
tensors[k] = sf.get_tensor(k).clone()
|
| 59 |
+
tensors = modify_fn(tensors)
|
| 60 |
+
save_file(tensors, str(dst_path))
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def copy_config(src_dir, dst_dir, filenames=None):
|
| 64 |
+
"""Copy model config/tokenizer files."""
|
| 65 |
+
if filenames is None:
|
| 66 |
+
filenames = [
|
| 67 |
+
"model.safetensors.index.json",
|
| 68 |
+
"config.json",
|
| 69 |
+
"tokenizer.json",
|
| 70 |
+
"tokenizer_config.json",
|
| 71 |
+
"generation_config.json",
|
| 72 |
+
]
|
| 73 |
+
src_dir, dst_dir = Path(src_dir), Path(dst_dir)
|
| 74 |
+
for fn in filenames:
|
| 75 |
+
src = src_dir / fn
|
| 76 |
+
if src.exists():
|
| 77 |
+
shutil.copy2(src, dst_dir / fn)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def tokenize_fable(data_path, tokenizer):
|
| 81 |
+
"""Tokenize FABLE assistant turns. Returns flat token id list."""
|
| 82 |
+
all_ids = []
|
| 83 |
+
with open(data_path) as f:
|
| 84 |
+
for line in f:
|
| 85 |
+
d = json.loads(line)
|
| 86 |
+
text = d.get("text", "")
|
| 87 |
+
for part in text.split("<|im_start|>"):
|
| 88 |
+
if part.startswith("assistant\n"):
|
| 89 |
+
content = part[len("assistant\n"):].replace("<|im_end|>", "").strip()
|
| 90 |
+
if content:
|
| 91 |
+
all_ids.extend(tokenizer.encode(content, add_special_tokens=False))
|
| 92 |
+
return all_ids
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def compute_bigram_stats(all_ids, vocab_size, topk):
|
| 96 |
+
"""Build token frequency and bigram counter for top-k tokens."""
|
| 97 |
+
cnt = Counter()
|
| 98 |
+
bigram = defaultdict(lambda: Counter())
|
| 99 |
+
for i, tid in enumerate(all_ids):
|
| 100 |
+
cnt[tid] += 1
|
| 101 |
+
if i > 0:
|
| 102 |
+
bigram[all_ids[i - 1]][tid] += 1
|
| 103 |
+
|
| 104 |
+
top_tokens = [t for t, _ in cnt.most_common(topk)]
|
| 105 |
+
token_to_idx = {t: i for i, t in enumerate(top_tokens)}
|
| 106 |
+
return cnt, bigram, top_tokens, token_to_idx
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def recover_gate_weight(embed, cnt, bigram, top_tokens, token_to_idx, tau):
|
| 110 |
+
"""
|
| 111 |
+
Recover gate weight via Pauli-decomposition regression.
|
| 112 |
+
|
| 113 |
+
Returns: W_hpc as float32 numpy array (12288, 4096), unscaled.
|
| 114 |
+
"""
|
| 115 |
+
D = embed.shape[1]
|
| 116 |
+
V = len(top_tokens)
|
| 117 |
+
|
| 118 |
+
E_raw = np.array([embed[t] for t in top_tokens]).astype(np.float64)
|
| 119 |
+
mu = np.zeros_like(E_raw) # X-component: probability-weighted
|
| 120 |
+
eps = np.zeros_like(E_raw) # Z-component: c_Z-weighted
|
| 121 |
+
|
| 122 |
+
for i, ti in enumerate(top_tokens):
|
| 123 |
+
total = sum(bigram[ti].values())
|
| 124 |
+
fi = cnt[ti] or 1
|
| 125 |
+
if total == 0:
|
| 126 |
+
continue
|
| 127 |
+
for tj, c in bigram[ti].items():
|
| 128 |
+
if tj not in token_to_idx:
|
| 129 |
+
continue
|
| 130 |
+
fj = cnt[tj] or 1
|
| 131 |
+
p = c / total
|
| 132 |
+
w = c / math.sqrt(fi * fj)
|
| 133 |
+
c_Z = (1.0 - w) / 2.0
|
| 134 |
+
mu[i] += p * embed[tj]
|
| 135 |
+
eps[i] += c_Z * embed[tj]
|
| 136 |
+
|
| 137 |
+
# Build target: [E/Ο | ΞΌ/Ο | Ξ΅/Ο]
|
| 138 |
+
z = np.hstack([E_raw / tau, mu / tau, eps / tau])
|
| 139 |
+
z = np.clip(z, -30.0, 30.0)
|
| 140 |
+
|
| 141 |
+
# Ridge regression: E_n Β· W = z
|
| 142 |
+
E_n = (E_raw - E_raw.mean(0, keepdims=True)) / (E_raw.std(0, keepdims=True) + 1e-10)
|
| 143 |
+
reg = 1e-3 * np.eye(D)
|
| 144 |
+
W = np.linalg.solve(E_n.T @ E_n + reg, E_n.T @ z)
|
| 145 |
+
return W.T.astype(np.float32) # (12288, 4096)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def main():
|
| 149 |
+
parser = argparse.ArgumentParser(description="FABLE β HPC gate weight injector")
|
| 150 |
+
parser.add_argument("--data", default="/tmp/fable5_sft.jsonl", help="FABLE 5 JSONL path")
|
| 151 |
+
parser.add_argument("--model", default="./Ornith-1.0-9B", help="Source model directory")
|
| 152 |
+
parser.add_argument("--output", default="./Ornith-1.0-9B-hpc", help="Output model directory")
|
| 153 |
+
parser.add_argument("--alpha", type=float, default=0.3, help="Additive correction strength")
|
| 154 |
+
parser.add_argument("--tau", type=float, default=0.003, help="Temperature for target scaling")
|
| 155 |
+
parser.add_argument("--topk", type=int, default=30000, help="Top-k tokens to use")
|
| 156 |
+
args = parser.parse_args()
|
| 157 |
+
|
| 158 |
+
t0 = time.time()
|
| 159 |
+
|
| 160 |
+
# ββ 1. Tokenizer & model info ββ
|
| 161 |
+
print("[1/5] Loading tokenizer & embeddings...")
|
| 162 |
+
tokenizer = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True)
|
| 163 |
+
shards, index = load_model_shards(args.model)
|
| 164 |
+
|
| 165 |
+
# Load embedding matrix from first shard
|
| 166 |
+
embed = None
|
| 167 |
+
with safe_open(str(Path(args.model) / shards[0]), framework="pt") as sf:
|
| 168 |
+
for k in sf.keys():
|
| 169 |
+
if "embed_tokens" in k:
|
| 170 |
+
embed = sf.get_tensor(k).float().numpy()
|
| 171 |
+
break
|
| 172 |
+
assert embed is not None, "Could not find embed_tokens in shards"
|
| 173 |
+
print(f" Embeddings: {embed.shape}, dtype={embed.dtype}")
|
| 174 |
+
|
| 175 |
+
# ββ 2. Tokenize FABLE data ββ
|
| 176 |
+
print(f"[2/5] Tokenizing {args.data}...")
|
| 177 |
+
all_ids = tokenize_fable(args.data, tokenizer)
|
| 178 |
+
print(f" {len(all_ids)} tokens")
|
| 179 |
+
|
| 180 |
+
# ββ 3. Bigram statistics ββ
|
| 181 |
+
print(f"[3/5] Computing bigrams (top-{args.topk})...")
|
| 182 |
+
cnt, bigram, top_tokens, token_to_idx = compute_bigram_stats(
|
| 183 |
+
all_ids, tokenizer.vocab_size, args.topk
|
| 184 |
+
)
|
| 185 |
+
print(f" {len(top_tokens)} tokens with {sum(len(bigram[t]) for t in top_tokens)} edges")
|
| 186 |
+
|
| 187 |
+
# ββ 4. Recover gate weight ββ
|
| 188 |
+
print(f"[4/5] Recovering gate weight (Ο={args.tau})...")
|
| 189 |
+
W_hpc = recover_gate_weight(embed, cnt, bigram, top_tokens, token_to_idx, args.tau)
|
| 190 |
+
|
| 191 |
+
# Scale to match original weight norm (~0.012)
|
| 192 |
+
target_std = 0.012
|
| 193 |
+
scale = target_std / W_hpc.std()
|
| 194 |
+
W_hpc *= scale
|
| 195 |
+
print(f" W_hpc: {W_hpc.shape}, std={W_hpc.std():.6f}, "
|
| 196 |
+
f"range=[{W_hpc.min():.4f},{W_hpc.max():.4f}]")
|
| 197 |
+
|
| 198 |
+
# ββ 5. Inject as additive correction ββ
|
| 199 |
+
print(f"[5/5] Injecting (Ξ±={args.alpha}) β {args.output}...")
|
| 200 |
+
W_torch = torch.from_numpy(W_hpc).to(torch.bfloat16).contiguous()
|
| 201 |
+
|
| 202 |
+
def modify_fn(tensors):
|
| 203 |
+
for k in list(tensors.keys()):
|
| 204 |
+
if "gate_proj" in k and "visual" not in k:
|
| 205 |
+
tensors[k] = tensors[k] + args.alpha * W_torch
|
| 206 |
+
return tensors
|
| 207 |
+
|
| 208 |
+
save_model_shards(args.model, args.output, shards, modify_fn)
|
| 209 |
+
copy_config(args.model, args.output)
|
| 210 |
+
|
| 211 |
+
elapsed = time.time() - t0
|
| 212 |
+
print(f"Done in {elapsed:.1f}s. Model saved to {args.output}/")
|
| 213 |
+
print(f"\nTo test: python3 test_recovered.py")
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
if __name__ == "__main__":
|
| 217 |
+
main()
|
test_recovered.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Quick test: load recovered model, generate a few tokens, check sanity."""
|
| 3 |
+
import torch
|
| 4 |
+
import gc
|
| 5 |
+
gc.collect(); torch.cuda.empty_cache()
|
| 6 |
+
|
| 7 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
|
| 8 |
+
|
| 9 |
+
MODEL_PATH = "/home/none/Documents/HPC-Quantize/Ornith-1.0-9B-hpc"
|
| 10 |
+
|
| 11 |
+
bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
|
| 12 |
+
bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16)
|
| 13 |
+
|
| 14 |
+
print("Loading model in 4-bit...")
|
| 15 |
+
tok = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)
|
| 16 |
+
tok.padding_side = "right"
|
| 17 |
+
if tok.pad_token is None: tok.pad_token = tok.eos_token
|
| 18 |
+
|
| 19 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 20 |
+
MODEL_PATH, trust_remote_code=True,
|
| 21 |
+
quantization_config=bnb, device_map="auto", low_cpu_mem_usage=True,
|
| 22 |
+
torch_dtype=torch.bfloat16
|
| 23 |
+
)
|
| 24 |
+
model.config.use_cache = True
|
| 25 |
+
|
| 26 |
+
prompts = [
|
| 27 |
+
"The capital of France is",
|
| 28 |
+
"Once upon a time, in a land far away,",
|
| 29 |
+
"Machine learning is a field of study that",
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
print("\n--- Generation test ---")
|
| 33 |
+
for p in prompts:
|
| 34 |
+
inp = tok(p, return_tensors="pt").to(model.device)
|
| 35 |
+
with torch.no_grad():
|
| 36 |
+
out = model.generate(**inp, max_new_tokens=32, do_sample=True, temperature=0.7, top_p=0.9)
|
| 37 |
+
text = tok.decode(out[0], skip_special_tokens=True)
|
| 38 |
+
print(f"\nPrompt: {p}")
|
| 39 |
+
print(f"Output: {text}")
|
| 40 |
+
|
| 41 |
+
print("\nDone.")
|
train_fable.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
train_fable.py β QLoRA fine-tune HPC-injected Ornith on FABLE 5 traces
|
| 4 |
+
|
| 5 |
+
Loads the HPC-injected model (Ornith-1.0-9B-hpc), adds LoRA adapters,
|
| 6 |
+
and fine-tunes on FABLE 5 assistant conversations.
|
| 7 |
+
|
| 8 |
+
Usage:
|
| 9 |
+
python3 train_fable.py --model ./Ornith-1.0-9B-hpc \\
|
| 10 |
+
--data /tmp/fable5_sft.jsonl \\
|
| 11 |
+
--output ./Ornith-1.0-9B-fable \\
|
| 12 |
+
--epochs 1 \\
|
| 13 |
+
--lr 2e-4
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import argparse, json, gc, math, os, sys, time
|
| 17 |
+
from functools import partial
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.nn as nn
|
| 21 |
+
from torch.utils.data import Dataset, DataLoader
|
| 22 |
+
from transformers import (
|
| 23 |
+
AutoTokenizer,
|
| 24 |
+
AutoModelForCausalLM,
|
| 25 |
+
BitsAndBytesConfig,
|
| 26 |
+
get_linear_schedule_with_warmup,
|
| 27 |
+
)
|
| 28 |
+
from peft import LoraConfig, get_peft_model
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# ββ Dataset ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 32 |
+
|
| 33 |
+
class FableDataset(Dataset):
|
| 34 |
+
"""Tokenized FABLE 5 assistant conversations."""
|
| 35 |
+
|
| 36 |
+
def __init__(self, data_path, tokenizer, max_length=2048):
|
| 37 |
+
self.tokenizer = tokenizer
|
| 38 |
+
self.max_length = max_length
|
| 39 |
+
self.samples = []
|
| 40 |
+
|
| 41 |
+
# System prompt used by Claude-style models
|
| 42 |
+
system_msg = "You are a helpful, harmless, and honest assistant."
|
| 43 |
+
|
| 44 |
+
with open(data_path) as f:
|
| 45 |
+
for line in f:
|
| 46 |
+
d = json.loads(line)
|
| 47 |
+
text = d.get("text", "")
|
| 48 |
+
if not text:
|
| 49 |
+
continue
|
| 50 |
+
|
| 51 |
+
# Reconstruct structured conversation
|
| 52 |
+
turns = text.split("<|im_start|>")
|
| 53 |
+
messages = [{"role": "system", "content": system_msg}]
|
| 54 |
+
for turn in turns:
|
| 55 |
+
turn = turn.strip()
|
| 56 |
+
if not turn:
|
| 57 |
+
continue
|
| 58 |
+
if turn.startswith("user\n"):
|
| 59 |
+
messages.append({"role": "user", "content": turn[len("user\n"):].replace("<|im_end|>", "").strip()})
|
| 60 |
+
elif turn.startswith("assistant\n"):
|
| 61 |
+
messages.append({"role": "assistant", "content": turn[len("assistant\n"):].replace("<|im_end|>", "").strip()})
|
| 62 |
+
|
| 63 |
+
if len(messages) <= 1:
|
| 64 |
+
continue
|
| 65 |
+
|
| 66 |
+
# Format with chat template
|
| 67 |
+
formatted = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)
|
| 68 |
+
tokens = tokenizer.encode(formatted, add_special_tokens=False, truncation=True, max_length=max_length)
|
| 69 |
+
self.samples.append(tokens)
|
| 70 |
+
|
| 71 |
+
def __len__(self):
|
| 72 |
+
return len(self.samples)
|
| 73 |
+
|
| 74 |
+
def __getitem__(self, idx):
|
| 75 |
+
tokens = self.samples[idx]
|
| 76 |
+
return torch.tensor(tokens, dtype=torch.long)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def collate_fn(batch, pad_token_id):
|
| 80 |
+
"""Pad batch to uniform length."""
|
| 81 |
+
max_len = max(len(x) for x in batch)
|
| 82 |
+
padded = torch.full((len(batch), max_len), pad_token_id, dtype=torch.long)
|
| 83 |
+
for i, seq in enumerate(batch):
|
| 84 |
+
padded[i, :len(seq)] = seq
|
| 85 |
+
return padded
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ββ Training βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 89 |
+
|
| 90 |
+
def train():
|
| 91 |
+
parser = argparse.ArgumentParser(description="Fine-tune HPC-injected Ornith on FABLE 5")
|
| 92 |
+
parser.add_argument("--model", default="./Ornith-1.0-9B-hpc", help="Injected model path")
|
| 93 |
+
parser.add_argument("--data", default="/tmp/fable5_sft.jsonl", help="FABLE 5 JSONL path")
|
| 94 |
+
parser.add_argument("--output", default="./Ornith-1.0-9B-fable", help="Output path")
|
| 95 |
+
parser.add_argument("--epochs", type=int, default=1, help="Training epochs")
|
| 96 |
+
parser.add_argument("--lr", type=float, default=2e-4, help="Peak learning rate")
|
| 97 |
+
parser.add_argument("--batch_size", type=int, default=1, help="Per-device batch size")
|
| 98 |
+
parser.add_argument("--grad_accum", type=int, default=8, help="Gradient accumulation steps")
|
| 99 |
+
parser.add_argument("--max_length", type=int, default=2048, help="Max sequence length")
|
| 100 |
+
parser.add_argument("--lora_r", type=int, default=16, help="LoRA rank")
|
| 101 |
+
parser.add_argument("--lora_alpha", type=int, default=32, help="LoRA alpha")
|
| 102 |
+
parser.add_argument("--lora_dropout", type=float, default=0.05, help="LoRA dropout")
|
| 103 |
+
parser.add_argument("--save_steps", type=int, default=200, help="Checkpoint interval (steps)")
|
| 104 |
+
args = parser.parse_args()
|
| 105 |
+
|
| 106 |
+
t0 = time.time()
|
| 107 |
+
|
| 108 |
+
# ββ 1. Tokenizer & 4-bit model ββ
|
| 109 |
+
print("[1/6] Loading tokenizer & 4-bit model...")
|
| 110 |
+
tokenizer = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True, use_fast=False)
|
| 111 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 112 |
+
tokenizer.padding_side = "right"
|
| 113 |
+
if tokenizer.chat_template is None:
|
| 114 |
+
tokenizer.chat_template = "{% for message in messages %}{% if message['role'] == 'system' %}<|im_start|>system\n{{ message['content'] }}<|im_end|>\n{% elif message['role'] == 'user' %}<|im_start|>user\n{{ message['content'] }}<|im_end|>\n{% elif message['role'] == 'assistant' %}<|im_start|>assistant\n{{ message['content'] }}<|im_end|>\n{% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant\n{% endif %}"
|
| 115 |
+
|
| 116 |
+
bnb = BitsAndBytesConfig(
|
| 117 |
+
load_in_4bit=True,
|
| 118 |
+
bnb_4bit_quant_type="nf4",
|
| 119 |
+
bnb_4bit_use_double_quant=True,
|
| 120 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 121 |
+
)
|
| 122 |
+
# Leave ~3 GiB headroom on GPU for activations/gradients
|
| 123 |
+
max_memory = {0: f"{torch.cuda.get_device_properties(0).total_memory // (1024**3) - 3}GiB", "cpu": "64GiB"}
|
| 124 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 125 |
+
args.model,
|
| 126 |
+
trust_remote_code=True,
|
| 127 |
+
quantization_config=bnb,
|
| 128 |
+
device_map="auto",
|
| 129 |
+
max_memory=max_memory,
|
| 130 |
+
torch_dtype=torch.bfloat16,
|
| 131 |
+
low_cpu_mem_usage=True,
|
| 132 |
+
)
|
| 133 |
+
model.config.use_cache = False # required for gradient checkpointing
|
| 134 |
+
model.gradient_checkpointing_enable()
|
| 135 |
+
|
| 136 |
+
# ββ 2. LoRA config β target gate_proj (the injected weights) ββ
|
| 137 |
+
print(f"[2/6] Adding LoRA (r={args.lora_r}, alpha={args.lora_alpha})...")
|
| 138 |
+
lora_config = LoraConfig(
|
| 139 |
+
r=args.lora_r,
|
| 140 |
+
lora_alpha=args.lora_alpha,
|
| 141 |
+
lora_dropout=args.lora_dropout,
|
| 142 |
+
bias="none",
|
| 143 |
+
task_type="CAUSAL_LM",
|
| 144 |
+
target_modules=["gate_proj", "up_proj", "down_proj"],
|
| 145 |
+
)
|
| 146 |
+
model = get_peft_model(model, lora_config)
|
| 147 |
+
model.print_trainable_parameters()
|
| 148 |
+
|
| 149 |
+
# ββ 4. Data ββ
|
| 150 |
+
print("[3/6] Loading FABLE 5 dataset...")
|
| 151 |
+
dataset = FableDataset(args.data, tokenizer, max_length=args.max_length)
|
| 152 |
+
loader = DataLoader(
|
| 153 |
+
dataset,
|
| 154 |
+
batch_size=args.batch_size,
|
| 155 |
+
shuffle=True,
|
| 156 |
+
collate_fn=partial(collate_fn, pad_token_id=tokenizer.pad_token_id),
|
| 157 |
+
num_workers=2,
|
| 158 |
+
pin_memory=True,
|
| 159 |
+
)
|
| 160 |
+
print(f" {len(dataset)} samples, {len(loader)} batches/epoch")
|
| 161 |
+
|
| 162 |
+
# ββ 4. Optimizer & scheduler (only trainable LoRA params) ββ
|
| 163 |
+
print("[4/6] Setting up optimizer...")
|
| 164 |
+
opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=args.lr)
|
| 165 |
+
total_steps = len(loader) * args.epochs // args.grad_accum
|
| 166 |
+
scheduler = get_linear_schedule_with_warmup(opt, num_warmup_steps=int(0.05 * total_steps), num_training_steps=total_steps)
|
| 167 |
+
|
| 168 |
+
# ββ 6. Training loop ββ
|
| 169 |
+
print(f"[5/6] Training ({args.epochs} epoch(s))...")
|
| 170 |
+
os.makedirs(args.output, exist_ok=True)
|
| 171 |
+
global_step = 0
|
| 172 |
+
best_loss = float("inf")
|
| 173 |
+
|
| 174 |
+
for epoch in range(args.epochs):
|
| 175 |
+
model.train()
|
| 176 |
+
total_loss = 0.0
|
| 177 |
+
n_batches = 0
|
| 178 |
+
epoch_t0 = time.time()
|
| 179 |
+
|
| 180 |
+
for batch_idx, batch in enumerate(loader):
|
| 181 |
+
batch = batch.to(model.device)
|
| 182 |
+
labels = batch.clone()
|
| 183 |
+
|
| 184 |
+
loss = model(input_ids=batch, labels=labels).loss
|
| 185 |
+
loss = loss / args.grad_accum
|
| 186 |
+
loss.backward()
|
| 187 |
+
|
| 188 |
+
total_loss += loss.item() * args.grad_accum
|
| 189 |
+
n_batches += 1
|
| 190 |
+
|
| 191 |
+
if (batch_idx + 1) % args.grad_accum == 0 or (batch_idx + 1) == len(loader):
|
| 192 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 193 |
+
opt.step()
|
| 194 |
+
scheduler.step()
|
| 195 |
+
opt.zero_grad()
|
| 196 |
+
global_step += 1
|
| 197 |
+
|
| 198 |
+
if global_step % args.save_steps == 0:
|
| 199 |
+
avg_loss = total_loss / n_batches
|
| 200 |
+
ppl = math.exp(avg_loss)
|
| 201 |
+
save_path = os.path.join(args.output, f"checkpoint-{global_step}")
|
| 202 |
+
model.save_pretrained(save_path)
|
| 203 |
+
tokenizer.save_pretrained(save_path)
|
| 204 |
+
print(f" Step {global_step}: loss={avg_loss:.4f}, ppl={ppl:.2f}, lr={scheduler.get_last_lr()[0]:.2e}")
|
| 205 |
+
|
| 206 |
+
if (batch_idx + 1) % 20 == 0:
|
| 207 |
+
current_loss = total_loss / n_batches
|
| 208 |
+
print(f" Epoch {epoch+1}, batch {batch_idx+1}/{len(loader)}: loss={current_loss:.4f}")
|
| 209 |
+
|
| 210 |
+
avg_loss = total_loss / n_batches
|
| 211 |
+
ppl = math.exp(avg_loss)
|
| 212 |
+
epoch_time = time.time() - epoch_t0
|
| 213 |
+
print(f" Epoch {epoch+1} done: loss={avg_loss:.4f}, ppl={ppl:.2f}, time={epoch_time:.0f}s")
|
| 214 |
+
|
| 215 |
+
if avg_loss < best_loss:
|
| 216 |
+
best_loss = avg_loss
|
| 217 |
+
model.save_pretrained(os.path.join(args.output, "best"))
|
| 218 |
+
tokenizer.save_pretrained(os.path.join(args.output, "best"))
|
| 219 |
+
|
| 220 |
+
# Save final
|
| 221 |
+
model.save_pretrained(os.path.join(args.output, "final"))
|
| 222 |
+
tokenizer.save_pretrained(os.path.join(args.output, "final"))
|
| 223 |
+
print(f"\nDone in {time.time()-t0:.0f}s. Final model: {args.output}/final")
|
| 224 |
+
print(f"Best loss: {best_loss:.4f} (PPL={math.exp(best_loss):.2f})")
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
if __name__ == "__main__":
|
| 228 |
+
train()
|