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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Distill Gemini Flash summaries into Qwen3-0.6B.
|
| 4 |
+
|
| 5 |
+
Fine-tunes Qwen3-0.6B with LoRA to generate one-sentence summaries from
|
| 6 |
+
raw markdown text β distilling from 6,720 high-quality Gemini-generated
|
| 7 |
+
summaries. At inference time, feed any markdown text and get a summary
|
| 8 |
+
back. Runs on CPU for inference (~1-2s per summary).
|
| 9 |
+
|
| 10 |
+
Input: raw embedded_text (markdown)
|
| 11 |
+
Output: one-sentence summary (Gemini-quality, Qwen-speed)
|
| 12 |
+
|
| 13 |
+
Usage:
|
| 14 |
+
python3 gpu_distill.py --data-dir /workspace/data --output-dir /workspace/output
|
| 15 |
+
"""
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
import time
|
| 20 |
+
import datetime
|
| 21 |
+
import argparse
|
| 22 |
+
import math
|
| 23 |
+
|
| 24 |
+
sys.stdout.reconfigure(line_buffering=True)
|
| 25 |
+
sys.stderr.reconfigure(line_buffering=True)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def log(msg, level="INFO"):
|
| 29 |
+
ts = datetime.datetime.now().strftime("%H:%M:%S")
|
| 30 |
+
print(f"[{ts}] [{level}] {msg}", flush=True)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def main():
|
| 34 |
+
parser = argparse.ArgumentParser()
|
| 35 |
+
parser.add_argument("--data-dir", default="/workspace/data")
|
| 36 |
+
parser.add_argument("--output-dir", default="/workspace/output")
|
| 37 |
+
parser.add_argument("--epochs", type=int, default=5)
|
| 38 |
+
parser.add_argument("--batch-size", type=int, default=8)
|
| 39 |
+
parser.add_argument("--lr", type=float, default=2e-4)
|
| 40 |
+
parser.add_argument("--lora-rank", type=int, default=16)
|
| 41 |
+
parser.add_argument("--lora-alpha", type=int, default=32)
|
| 42 |
+
parser.add_argument("--model-name", default="Qwen/Qwen3-0.6B")
|
| 43 |
+
parser.add_argument("--max-input-len", type=int, default=384, help="Max input tokens")
|
| 44 |
+
parser.add_argument("--max-output-len", type=int, default=64, help="Max output tokens")
|
| 45 |
+
parser.add_argument("--log-every", type=int, default=10)
|
| 46 |
+
parser.add_argument("--sample-every", type=int, default=2)
|
| 47 |
+
args = parser.parse_args()
|
| 48 |
+
|
| 49 |
+
log("=" * 60)
|
| 50 |
+
log("DISTILLATION: Markdown β Summary (LoRA fine-tune)")
|
| 51 |
+
log("=" * 60)
|
| 52 |
+
log(f"Config: epochs={args.epochs} batch={args.batch_size} lr={args.lr} "
|
| 53 |
+
f"lora_rank={args.lora_rank} input_len={args.max_input_len} output_len={args.max_output_len}")
|
| 54 |
+
|
| 55 |
+
# Auto-install missing deps (don't touch torch β use image's version)
|
| 56 |
+
import subprocess as _sp
|
| 57 |
+
for pkg in ["numpy", "transformers", "accelerate", "safetensors"]:
|
| 58 |
+
try:
|
| 59 |
+
__import__(pkg)
|
| 60 |
+
except ImportError:
|
| 61 |
+
log(f"Installing {pkg}...")
|
| 62 |
+
_sp.run([sys.executable, "-m", "pip", "install", "--break-system-packages",
|
| 63 |
+
"-q", pkg], check=True)
|
| 64 |
+
|
| 65 |
+
import numpy as np
|
| 66 |
+
import torch
|
| 67 |
+
import torch.nn as nn
|
| 68 |
+
from torch.utils.data import Dataset, DataLoader
|
| 69 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 70 |
+
|
| 71 |
+
log(f"PyTorch {torch.__version__} | CUDA: {torch.cuda.is_available()}")
|
| 72 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 73 |
+
if device.type == "cuda":
|
| 74 |
+
props = torch.cuda.get_device_properties(0)
|
| 75 |
+
log(f"GPU: {torch.cuda.get_device_name()} | VRAM: {props.total_memory / 1024**3:.1f} GB")
|
| 76 |
+
|
| 77 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 78 |
+
def vram_mb():
|
| 79 |
+
return torch.cuda.memory_allocated() / 1024**2 if device.type == "cuda" else 0
|
| 80 |
+
|
| 81 |
+
metrics = {
|
| 82 |
+
"config": vars(args), "device": str(device),
|
| 83 |
+
"gpu": torch.cuda.get_device_name() if device.type == "cuda" else "cpu",
|
| 84 |
+
"method": "distillation", "steps": [], "epochs": [], "samples": [],
|
| 85 |
+
"start_time": time.time(),
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
# ββ Load data ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 89 |
+
log("Loading data...")
|
| 90 |
+
t0 = time.time()
|
| 91 |
+
|
| 92 |
+
# Load texts (embedded_text from clouderic.db) and summaries
|
| 93 |
+
with open(os.path.join(args.data_dir, "texts.json")) as f:
|
| 94 |
+
text_data = json.load(f) # [{"id": str, "text": str}]
|
| 95 |
+
with open(os.path.join(args.data_dir, "summaries.json")) as f:
|
| 96 |
+
sum_data = json.load(f) # [{"id": str, "summary": str}]
|
| 97 |
+
|
| 98 |
+
sum_map = {s["id"]: s["summary"] for s in sum_data}
|
| 99 |
+
pairs = [(t["text"], sum_map[t["id"]]) for t in text_data
|
| 100 |
+
if t["id"] in sum_map and t["text"] and len(t["text"].strip()) > 20]
|
| 101 |
+
log(f"Loaded {len(pairs)} (text, summary) pairs in {time.time()-t0:.1f}s")
|
| 102 |
+
|
| 103 |
+
# Stats
|
| 104 |
+
text_lens = [len(t) for t, _ in pairs]
|
| 105 |
+
sum_lens = [len(s) for _, s in pairs]
|
| 106 |
+
log(f"Text lengths: mean={np.mean(text_lens):.0f} median={np.median(text_lens):.0f} "
|
| 107 |
+
f"max={max(text_lens)} chars")
|
| 108 |
+
log(f"Summary lengths: mean={np.mean(sum_lens):.0f} median={np.median(sum_lens):.0f} "
|
| 109 |
+
f"max={max(sum_lens)} chars")
|
| 110 |
+
|
| 111 |
+
# ββ Load model βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 112 |
+
log(f"Loading {args.model_name}...")
|
| 113 |
+
t0 = time.time()
|
| 114 |
+
tokenizer = AutoTokenizer.from_pretrained(args.model_name, trust_remote_code=True)
|
| 115 |
+
if tokenizer.pad_token is None:
|
| 116 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 117 |
+
tokenizer.padding_side = "left" # for decoder-only models
|
| 118 |
+
|
| 119 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 120 |
+
args.model_name, torch_dtype=torch.float16, trust_remote_code=True,
|
| 121 |
+
).to(device)
|
| 122 |
+
|
| 123 |
+
for param in model.parameters():
|
| 124 |
+
param.requires_grad = False
|
| 125 |
+
|
| 126 |
+
hidden_dim = model.config.hidden_size
|
| 127 |
+
log(f"Model loaded in {time.time()-t0:.1f}s: hidden={hidden_dim} | VRAM: {vram_mb():.0f}MB")
|
| 128 |
+
|
| 129 |
+
# ββ LoRA βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 130 |
+
class LoRALayer(nn.Module):
|
| 131 |
+
def __init__(self, original_layer, rank, alpha):
|
| 132 |
+
super().__init__()
|
| 133 |
+
self.original = original_layer
|
| 134 |
+
in_f, out_f = original_layer.in_features, original_layer.out_features
|
| 135 |
+
self.lora_A = nn.Linear(in_f, rank, bias=False)
|
| 136 |
+
self.lora_B = nn.Linear(rank, out_f, bias=False)
|
| 137 |
+
self.scaling = alpha / rank
|
| 138 |
+
nn.init.kaiming_uniform_(self.lora_A.weight, a=math.sqrt(5))
|
| 139 |
+
nn.init.zeros_(self.lora_B.weight)
|
| 140 |
+
|
| 141 |
+
def forward(self, x):
|
| 142 |
+
orig_out = self.original(x)
|
| 143 |
+
lora_out = self.lora_B(self.lora_A(x.to(self.lora_A.weight.dtype)))
|
| 144 |
+
return orig_out + lora_out.to(orig_out.dtype) * self.scaling
|
| 145 |
+
|
| 146 |
+
lora_modules = []
|
| 147 |
+
n_adapted = 0
|
| 148 |
+
for name, module in model.named_modules():
|
| 149 |
+
if hasattr(module, 'q_proj') and isinstance(module.q_proj, nn.Linear):
|
| 150 |
+
lora_q = LoRALayer(module.q_proj, args.lora_rank, args.lora_alpha).to(device)
|
| 151 |
+
module.q_proj = lora_q
|
| 152 |
+
lora_modules.append(lora_q)
|
| 153 |
+
n_adapted += 1
|
| 154 |
+
if hasattr(module, 'v_proj') and isinstance(module.v_proj, nn.Linear):
|
| 155 |
+
lora_v = LoRALayer(module.v_proj, args.lora_rank, args.lora_alpha).to(device)
|
| 156 |
+
module.v_proj = lora_v
|
| 157 |
+
lora_modules.append(lora_v)
|
| 158 |
+
n_adapted += 1
|
| 159 |
+
|
| 160 |
+
lora_params = []
|
| 161 |
+
for lm in lora_modules:
|
| 162 |
+
lora_params.extend(lm.lora_A.parameters())
|
| 163 |
+
lora_params.extend(lm.lora_B.parameters())
|
| 164 |
+
|
| 165 |
+
lora_total = sum(p.numel() for p in lora_params)
|
| 166 |
+
log(f"LoRA applied to {n_adapted} layers | {lora_total:,} trainable params | VRAM: {vram_mb():.0f}MB")
|
| 167 |
+
|
| 168 |
+
# ββ Dataset ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 169 |
+
PROMPT_TEMPLATE = "Summarize in one sentence:\n{text}\n\nSummary:"
|
| 170 |
+
|
| 171 |
+
class DistillDataset(Dataset):
|
| 172 |
+
def __init__(self, pairs, tokenizer, max_input, max_output):
|
| 173 |
+
self.items = []
|
| 174 |
+
for text, summary in pairs:
|
| 175 |
+
# Truncate text to fit
|
| 176 |
+
prompt = PROMPT_TEMPLATE.format(text=text[:2000])
|
| 177 |
+
# Tokenize prompt and summary separately
|
| 178 |
+
prompt_enc = tokenizer(prompt, truncation=True, max_length=max_input,
|
| 179 |
+
return_tensors="pt")
|
| 180 |
+
summary_enc = tokenizer(summary, truncation=True, max_length=max_output,
|
| 181 |
+
return_tensors="pt")
|
| 182 |
+
|
| 183 |
+
# Concatenate: [prompt_tokens] [summary_tokens] [eos]
|
| 184 |
+
input_ids = torch.cat([
|
| 185 |
+
prompt_enc["input_ids"].squeeze(0),
|
| 186 |
+
summary_enc["input_ids"].squeeze(0),
|
| 187 |
+
torch.tensor([tokenizer.eos_token_id]),
|
| 188 |
+
])
|
| 189 |
+
|
| 190 |
+
# Labels: -100 for prompt, actual ids for summary+eos
|
| 191 |
+
n_prompt = prompt_enc["input_ids"].shape[1]
|
| 192 |
+
labels = input_ids.clone()
|
| 193 |
+
labels[:n_prompt] = -100
|
| 194 |
+
|
| 195 |
+
# Truncate total to max_input + max_output
|
| 196 |
+
max_total = max_input + max_output
|
| 197 |
+
if len(input_ids) > max_total:
|
| 198 |
+
input_ids = input_ids[:max_total]
|
| 199 |
+
labels = labels[:max_total]
|
| 200 |
+
|
| 201 |
+
self.items.append((input_ids, labels))
|
| 202 |
+
|
| 203 |
+
def __len__(self):
|
| 204 |
+
return len(self.items)
|
| 205 |
+
|
| 206 |
+
def __getitem__(self, idx):
|
| 207 |
+
return self.items[idx]
|
| 208 |
+
|
| 209 |
+
def collate_fn(batch):
|
| 210 |
+
input_ids_list, labels_list = zip(*batch)
|
| 211 |
+
max_len = max(ids.shape[0] for ids in input_ids_list)
|
| 212 |
+
|
| 213 |
+
input_ids = torch.full((len(batch), max_len), tokenizer.pad_token_id, dtype=torch.long)
|
| 214 |
+
labels = torch.full((len(batch), max_len), -100, dtype=torch.long)
|
| 215 |
+
attention_mask = torch.zeros((len(batch), max_len), dtype=torch.long)
|
| 216 |
+
|
| 217 |
+
for i, (ids, lab) in enumerate(zip(input_ids_list, labels_list)):
|
| 218 |
+
# Right-align (pad on left for decoder-only)
|
| 219 |
+
offset = max_len - ids.shape[0]
|
| 220 |
+
input_ids[i, offset:] = ids
|
| 221 |
+
labels[i, offset:] = lab
|
| 222 |
+
attention_mask[i, offset:] = 1
|
| 223 |
+
|
| 224 |
+
return input_ids, labels, attention_mask
|
| 225 |
+
|
| 226 |
+
# Split
|
| 227 |
+
n_val = max(int(len(pairs) * 0.1), 1)
|
| 228 |
+
rng = np.random.RandomState(42)
|
| 229 |
+
indices = rng.permutation(len(pairs))
|
| 230 |
+
val_pairs = [pairs[i] for i in indices[:n_val]]
|
| 231 |
+
train_pairs = [pairs[i] for i in indices[n_val:]]
|
| 232 |
+
|
| 233 |
+
train_ds = DistillDataset(train_pairs, tokenizer, args.max_input_len, args.max_output_len)
|
| 234 |
+
val_ds = DistillDataset(val_pairs, tokenizer, args.max_input_len, args.max_output_len)
|
| 235 |
+
train_dl = DataLoader(train_ds, batch_size=args.batch_size, shuffle=True,
|
| 236 |
+
drop_last=True, collate_fn=collate_fn)
|
| 237 |
+
val_dl = DataLoader(val_ds, batch_size=args.batch_size, shuffle=False, collate_fn=collate_fn)
|
| 238 |
+
|
| 239 |
+
steps_per_epoch = len(train_dl)
|
| 240 |
+
total_steps = steps_per_epoch * args.epochs
|
| 241 |
+
log(f"Data: train={len(train_ds)} val={len(val_ds)} | {steps_per_epoch} steps/epoch, "
|
| 242 |
+
f"{total_steps} total")
|
| 243 |
+
|
| 244 |
+
# ββ Training βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 245 |
+
optimizer = torch.optim.AdamW(lora_params, lr=args.lr, weight_decay=0.01)
|
| 246 |
+
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=total_steps, eta_min=1e-6)
|
| 247 |
+
scaler = torch.amp.GradScaler("cuda") if device.type == "cuda" else None
|
| 248 |
+
best_val_loss = float("inf")
|
| 249 |
+
global_step = 0
|
| 250 |
+
|
| 251 |
+
log("")
|
| 252 |
+
log("=" * 60)
|
| 253 |
+
log("TRAINING START")
|
| 254 |
+
log("=" * 60)
|
| 255 |
+
train_start = time.time()
|
| 256 |
+
|
| 257 |
+
for epoch in range(args.epochs):
|
| 258 |
+
model.train()
|
| 259 |
+
epoch_loss, epoch_tokens = 0.0, 0
|
| 260 |
+
epoch_start = time.time()
|
| 261 |
+
log(f"")
|
| 262 |
+
log(f"ββ Epoch {epoch+1}/{args.epochs} ββ")
|
| 263 |
+
|
| 264 |
+
for step, (input_ids, labels, attn_mask) in enumerate(train_dl):
|
| 265 |
+
step_start = time.time()
|
| 266 |
+
input_ids = input_ids.to(device)
|
| 267 |
+
labels = labels.to(device)
|
| 268 |
+
attn_mask = attn_mask.to(device)
|
| 269 |
+
|
| 270 |
+
optimizer.zero_grad()
|
| 271 |
+
|
| 272 |
+
if scaler:
|
| 273 |
+
with torch.amp.autocast("cuda"):
|
| 274 |
+
outputs = model(input_ids=input_ids, attention_mask=attn_mask, labels=labels)
|
| 275 |
+
loss = outputs.loss
|
| 276 |
+
if torch.isnan(loss):
|
| 277 |
+
log(f"NaN at step {step+1}!", "ERROR")
|
| 278 |
+
break
|
| 279 |
+
scaler.scale(loss).backward()
|
| 280 |
+
scaler.unscale_(optimizer)
|
| 281 |
+
grad_norm = torch.nn.utils.clip_grad_norm_(lora_params, 1.0).item()
|
| 282 |
+
scaler.step(optimizer)
|
| 283 |
+
scaler.update()
|
| 284 |
+
else:
|
| 285 |
+
outputs = model(input_ids=input_ids, attention_mask=attn_mask, labels=labels)
|
| 286 |
+
loss = outputs.loss
|
| 287 |
+
loss.backward()
|
| 288 |
+
grad_norm = torch.nn.utils.clip_grad_norm_(lora_params, 1.0).item()
|
| 289 |
+
optimizer.step()
|
| 290 |
+
|
| 291 |
+
scheduler.step()
|
| 292 |
+
|
| 293 |
+
n_tokens = (labels != -100).sum().item()
|
| 294 |
+
step_time = time.time() - step_start
|
| 295 |
+
tps = n_tokens / step_time if step_time > 0 else 0
|
| 296 |
+
epoch_loss += loss.item() * n_tokens
|
| 297 |
+
epoch_tokens += n_tokens
|
| 298 |
+
global_step += 1
|
| 299 |
+
|
| 300 |
+
metrics["steps"].append({
|
| 301 |
+
"epoch": epoch+1, "step": step+1, "global_step": global_step,
|
| 302 |
+
"loss": round(loss.item(), 4), "lr": scheduler.get_last_lr()[0],
|
| 303 |
+
"grad_norm": round(grad_norm, 4), "vram_mb": round(vram_mb()),
|
| 304 |
+
"tokens_per_sec": round(tps),
|
| 305 |
+
})
|
| 306 |
+
|
| 307 |
+
if step % args.log_every == 0:
|
| 308 |
+
elapsed = time.time() - train_start
|
| 309 |
+
eta = elapsed / global_step * (total_steps - global_step) if global_step > 0 else 0
|
| 310 |
+
log(f" step {step+1:>3}/{steps_per_epoch} | loss={loss.item():.4f} | "
|
| 311 |
+
f"lr={scheduler.get_last_lr()[0]:.1e} | grad={grad_norm:.3f} | "
|
| 312 |
+
f"VRAM={vram_mb():.0f}MB | {tps:.0f} tok/s | ETA={eta/60:.0f}m")
|
| 313 |
+
|
| 314 |
+
if torch.isnan(loss):
|
| 315 |
+
break
|
| 316 |
+
|
| 317 |
+
avg_train = epoch_loss / max(epoch_tokens, 1)
|
| 318 |
+
|
| 319 |
+
# Validation
|
| 320 |
+
log(f" Validating...")
|
| 321 |
+
model.eval()
|
| 322 |
+
val_loss, val_tokens = 0.0, 0
|
| 323 |
+
with torch.no_grad():
|
| 324 |
+
for input_ids, labels, attn_mask in val_dl:
|
| 325 |
+
input_ids, labels, attn_mask = input_ids.to(device), labels.to(device), attn_mask.to(device)
|
| 326 |
+
with torch.amp.autocast("cuda") if device.type == "cuda" else torch.no_grad():
|
| 327 |
+
outputs = model(input_ids=input_ids, attention_mask=attn_mask, labels=labels)
|
| 328 |
+
n = (labels != -100).sum().item()
|
| 329 |
+
val_loss += outputs.loss.item() * n
|
| 330 |
+
val_tokens += n
|
| 331 |
+
|
| 332 |
+
avg_val = val_loss / max(val_tokens, 1)
|
| 333 |
+
epoch_time = time.time() - epoch_start
|
| 334 |
+
is_best = avg_val < best_val_loss
|
| 335 |
+
|
| 336 |
+
metrics["epochs"].append({
|
| 337 |
+
"epoch": epoch+1, "train_loss": round(avg_train, 4),
|
| 338 |
+
"val_loss": round(avg_val, 4), "time_s": round(epoch_time, 1), "best": is_best,
|
| 339 |
+
})
|
| 340 |
+
|
| 341 |
+
marker = " β
NEW BEST" if is_best else ""
|
| 342 |
+
log(f" Epoch {epoch+1}/{args.epochs} DONE | train={avg_train:.4f} val={avg_val:.4f} | "
|
| 343 |
+
f"{epoch_time:.0f}s{marker}")
|
| 344 |
+
|
| 345 |
+
if device.type == "cuda":
|
| 346 |
+
torch.cuda.empty_cache()
|
| 347 |
+
|
| 348 |
+
if is_best:
|
| 349 |
+
best_val_loss = avg_val
|
| 350 |
+
lora_state = {}
|
| 351 |
+
for name, module in model.named_modules():
|
| 352 |
+
if isinstance(module, LoRALayer):
|
| 353 |
+
lora_state[name + ".lora_A"] = module.lora_A.state_dict()
|
| 354 |
+
lora_state[name + ".lora_B"] = module.lora_B.state_dict()
|
| 355 |
+
torch.save({
|
| 356 |
+
"epoch": epoch, "val_loss": avg_val,
|
| 357 |
+
"lora_state": lora_state,
|
| 358 |
+
"config": vars(args),
|
| 359 |
+
}, os.path.join(args.output_dir, "best_distill.pt"))
|
| 360 |
+
|
| 361 |
+
# Samples
|
| 362 |
+
if (epoch + 1) % args.sample_every == 0 or epoch == args.epochs - 1 or is_best:
|
| 363 |
+
try:
|
| 364 |
+
log(f" Generating samples...")
|
| 365 |
+
model.eval()
|
| 366 |
+
sample_rng = np.random.RandomState(epoch)
|
| 367 |
+
sample_idx = sample_rng.choice(len(val_pairs), size=min(3, len(val_pairs)), replace=False)
|
| 368 |
+
|
| 369 |
+
for si in sample_idx:
|
| 370 |
+
text, ref = val_pairs[si]
|
| 371 |
+
prompt = PROMPT_TEMPLATE.format(text=text[:1500])
|
| 372 |
+
inputs = tokenizer(prompt, return_tensors="pt", truncation=True,
|
| 373 |
+
max_length=args.max_input_len).to(device)
|
| 374 |
+
|
| 375 |
+
with torch.no_grad():
|
| 376 |
+
gen = model.generate(
|
| 377 |
+
**inputs, max_new_tokens=args.max_output_len,
|
| 378 |
+
do_sample=False, temperature=1.0,
|
| 379 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 380 |
+
)
|
| 381 |
+
gen_text = tokenizer.decode(gen[0][inputs["input_ids"].shape[1]:],
|
| 382 |
+
skip_special_tokens=True)
|
| 383 |
+
|
| 384 |
+
del gen
|
| 385 |
+
if device.type == "cuda":
|
| 386 |
+
torch.cuda.empty_cache()
|
| 387 |
+
|
| 388 |
+
metrics["samples"].append({"epoch": epoch+1, "ref": ref[:200], "gen": gen_text[:200]})
|
| 389 |
+
log(f" REF: {ref[:100]}")
|
| 390 |
+
log(f" GEN: {gen_text[:100]}")
|
| 391 |
+
log(f"")
|
| 392 |
+
except Exception as e:
|
| 393 |
+
log(f" Sample generation failed: {e}", "WARN")
|
| 394 |
+
|
| 395 |
+
if device.type == "cuda":
|
| 396 |
+
torch.cuda.empty_cache()
|
| 397 |
+
|
| 398 |
+
# ββ Summary ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 399 |
+
total_time = time.time() - train_start
|
| 400 |
+
metrics["total_time_s"] = round(total_time, 1)
|
| 401 |
+
metrics["best_val_loss"] = round(best_val_loss, 4)
|
| 402 |
+
|
| 403 |
+
with open(os.path.join(args.output_dir, "training_metrics.json"), "w") as f:
|
| 404 |
+
json.dump(metrics, f, indent=2)
|
| 405 |
+
|
| 406 |
+
log("")
|
| 407 |
+
log("=" * 60)
|
| 408 |
+
log("TRAINING COMPLETE")
|
| 409 |
+
log("=" * 60)
|
| 410 |
+
log(f"Total time: {total_time/60:.1f} minutes")
|
| 411 |
+
log(f"Best val loss: {best_val_loss:.4f}")
|
| 412 |
+
log(f"")
|
| 413 |
+
log("Epoch | Train Loss | Val Loss | Time | Best")
|
| 414 |
+
log("-" * 50)
|
| 415 |
+
for e in metrics["epochs"]:
|
| 416 |
+
m = " β
" if e["best"] else ""
|
| 417 |
+
log(f" {e['epoch']:>3} | {e['train_loss']:.4f} | {e['val_loss']:.4f} | {e['time_s']:.0f}s{m}")
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
if __name__ == "__main__":
|
| 421 |
+
main()
|