Download train.py from HapiDev/bugscope-2.35b: direct link, hf CLI and curl.
- Browser
- Download file 12.4 kB
-
https://huggingface.co/HapiDev/bugscope-2.35b/resolve/main/train.py
- Command line
-
hf download hf://HapiDev/bugscope-2.35b/train.py
-
curl -L -o train.py https://huggingface.co/HapiDev/bugscope-2.35b/resolve/main/train.py
12.4 kB
| import json, math, os, sys, time, glob | |
| from collections import deque | |
| from pathlib import Path | |
| from typing import Optional | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from torch.utils.data import Dataset, DataLoader | |
| from config import BugScopeConfig, SPECIAL_TOKENS | |
| from model import BugScopeModel | |
| class BugScopeTokenizer: | |
| def __init__(self): | |
| try: | |
| import tiktoken | |
| self._enc = tiktoken.get_encoding("gpt2") | |
| except ImportError: | |
| self._enc = None | |
| def encode(self, text, max_len=None): | |
| pieces = [] | |
| remaining = text | |
| while remaining: | |
| earliest_pos = len(remaining) | |
| earliest_tok = None | |
| for tok_str, tok_id in SPECIAL_TOKENS.items(): | |
| pos = remaining.find(tok_str) | |
| if pos != -1 and pos < earliest_pos: | |
| earliest_pos = pos | |
| earliest_tok = (tok_str, tok_id) | |
| if earliest_tok is None: | |
| pieces.extend(self._enc.encode(remaining, allowed_special=set()) if self._enc else list(remaining.encode())) | |
| break | |
| tok_str, tok_id = earliest_tok | |
| if earliest_pos > 0: | |
| pieces.extend(self._enc.encode(remaining[:earliest_pos], allowed_special=set()) if self._enc else list(remaining[:earliest_pos].encode())) | |
| pieces.append(tok_id) | |
| remaining = remaining[earliest_pos + len(tok_str):] | |
| if max_len: pieces = pieces[:max_len] | |
| return pieces | |
| def decode(self, ids): | |
| parts, plain = [], [] | |
| inv = {v:k for k,v in SPECIAL_TOKENS.items()} | |
| for t in ids: | |
| if t in inv: | |
| if plain: parts.append(self._enc.decode(plain) if self._enc else bytes(plain).decode('utf-8','replace')); plain=[] | |
| parts.append(inv[t]) | |
| else: plain.append(t) | |
| if plain: parts.append(self._enc.decode(plain) if self._enc else bytes(plain).decode('utf-8','replace')) | |
| return "".join(parts) | |
| def pad_id(self): return SPECIAL_TOKENS["<|pad|>"] | |
| class BugFixDataset(Dataset): | |
| def __init__(self, path, tokenizer, max_seq_len=2048): | |
| self.tokenizer, self.max_seq_len, self.examples = tokenizer, max_seq_len, [] | |
| print(f"[dataset] Loading {path} ...") | |
| with open(path) as f: | |
| for line in f: | |
| line = line.strip() | |
| if line: | |
| d = json.loads(line) | |
| if d.get("formatted"): self.examples.append(d["formatted"]) | |
| print(f"[dataset] {len(self.examples)} examples loaded") | |
| def __len__(self): return len(self.examples) | |
| def __getitem__(self, idx): | |
| ids = self.tokenizer.encode(self.examples[idx], max_len=self.max_seq_len) | |
| pad_len = self.max_seq_len - len(ids) | |
| input_ids = (ids[:-1] + [self.tokenizer.pad_id] * max(0, pad_len+1))[:self.max_seq_len] | |
| targets = (ids[1:] + [self.tokenizer.pad_id] * max(0, pad_len+1))[:self.max_seq_len] | |
| return torch.tensor(input_ids, dtype=torch.long), torch.tensor(targets, dtype=torch.long) | |
| def get_lr(step, warmup, max_steps, max_lr, min_lr): | |
| if step < warmup: return max_lr * (step+1) / (warmup+1) | |
| if step >= max_steps: return min_lr | |
| progress = (step - warmup) / (max_steps - warmup) | |
| return min_lr + 0.5 * (max_lr - min_lr) * (1.0 + math.cos(math.pi * progress)) | |
| class LossWatchdog: | |
| def __init__(self, patience=3000, spike=3.0, window=500): | |
| self.patience, self.spike, self.recent = patience, spike, deque(maxlen=window) | |
| self.best_loss, self.best_step = float("inf"), 0 | |
| self.triggered, self.reason = False, "" | |
| def check(self, loss, step): | |
| if not math.isfinite(loss): | |
| self.triggered, self.reason = True, f"Loss is {loss} at step {step}" | |
| return True | |
| self.recent.append(loss) | |
| if loss < self.best_loss: self.best_loss, self.best_step = loss, step | |
| if step - self.best_step > self.patience and step > self.patience: | |
| self.triggered = True | |
| self.reason = f"Stalled: best={self.best_loss:.4f}@{self.best_step}, now={loss:.4f}@{step}" | |
| return True | |
| if len(self.recent) >= 250: | |
| avg = sum(self.recent) / len(self.recent) | |
| if loss > avg * self.spike: | |
| self.triggered, self.reason = True, f"Spike: {loss:.4f} > {self.spike}x avg {avg:.4f}" | |
| return True | |
| return False | |
| def train_phase(model, dataloader, phase_name, max_steps, max_lr, warmup_steps, | |
| grad_accum_steps=1, checkpoint_dir="checkpoints", checkpoint_every=999999, | |
| resume_step=0, device="cuda", dtype_str="bfloat16", log_every=50): | |
| os.makedirs(checkpoint_dir, exist_ok=True) | |
| dtype = {"bfloat16":torch.bfloat16,"float16":torch.float16,"float32":torch.float32}[dtype_str] | |
| optimizer = torch.optim.AdamW(model.parameters(), lr=max_lr, betas=(0.9,0.95), weight_decay=0.1) | |
| min_lr = max_lr * 0.1 | |
| watchdog = LossWatchdog() | |
| model.train() | |
| step, total_loss, total_tokens, t0 = resume_step, 0.0, 0, time.time() | |
| data_iter = iter(dataloader) | |
| bs = dataloader.batch_size | |
| eff = bs * grad_accum_steps | |
| print(f"\n{'='*60}") | |
| print(f" Phase: {phase_name}") | |
| print(f" Steps: {max_steps} LR: {max_lr} Warmup: {warmup_steps}") | |
| print(f" Batch: {bs} x accum {grad_accum_steps} = {eff} effective") | |
| print(f" Checkpoint every {checkpoint_every} steps") | |
| print(f"{'='*60}\n") | |
| while step < max_steps: | |
| optimizer.zero_grad(set_to_none=True) | |
| accum_loss = 0.0 | |
| for _ in range(grad_accum_steps): | |
| try: input_ids, targets = next(data_iter) | |
| except StopIteration: data_iter = iter(dataloader); input_ids, targets = next(data_iter) | |
| input_ids, targets = input_ids.to(device), targets.to(device) | |
| with torch.amp.autocast("cuda", dtype=dtype): | |
| _, loss, _ = model(input_ids, targets) | |
| loss = loss / grad_accum_steps | |
| loss.backward() | |
| accum_loss += loss.item() | |
| total_tokens += input_ids.numel() | |
| grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) | |
| lr = get_lr(step, warmup_steps, max_steps, max_lr, min_lr) | |
| for pg in optimizer.param_groups: pg["lr"] = lr | |
| optimizer.step() | |
| total_loss += accum_loss | |
| step += 1 | |
| if watchdog.check(accum_loss, step): | |
| print(f"\n WATCHDOG: {watchdog.reason}") | |
| _save(model, step, phase_name, checkpoint_dir, "_watchdog") | |
| break | |
| if step % log_every == 0: | |
| avg = total_loss / log_every | |
| elapsed = time.time() - t0 | |
| tps = total_tokens / elapsed if elapsed > 0 else 0 | |
| eta = (max_steps - step) * elapsed / log_every / 3600 if elapsed > 0 else 0 | |
| mem = torch.cuda.max_memory_allocated() / 1e9 | |
| print(f" [{phase_name}] step {step:>6d}/{max_steps} | loss {avg:.4f} | lr {lr:.2e} | " | |
| f"gnorm {grad_norm:.2f} | {tps:.0f} tok/s | mem {mem:.1f}G | eta {eta:.1f}h") | |
| total_loss, total_tokens, t0 = 0.0, 0, time.time() | |
| if step % checkpoint_every == 0: | |
| _save(model, step, phase_name, checkpoint_dir) | |
| if not watchdog.triggered: | |
| _save(model, step, phase_name, checkpoint_dir, "_final") | |
| print(f"\n [{phase_name}] Done at step {step}") | |
| return not watchdog.triggered | |
| def _save(model, step, phase, ckpt_dir, suffix=""): | |
| path = os.path.join(ckpt_dir, f"{phase}_step{step}{suffix}.pt") | |
| torch.save({"step":step, "model":model.state_dict(), "config":model.cfg, "phase":phase}, path) | |
| size = os.path.getsize(path) / 1e6 | |
| print(f" [ckpt] Saved {path} ({size:.0f} MB)") | |
| # Auto-delete old checkpoints | |
| ckpts = sorted(glob.glob(os.path.join(ckpt_dir, f"{phase}_step*.pt"))) | |
| ckpts = [c for c in ckpts if "final" not in c and "watchdog" not in c] | |
| while len(ckpts) > 2: | |
| os.remove(ckpts.pop(0)) | |
| def main(): | |
| import argparse | |
| p = argparse.ArgumentParser() | |
| p.add_argument("--phase", type=int, default=2) | |
| p.add_argument("--bugfix-data", default="data/bugfix_train.jsonl") | |
| p.add_argument("--hard-data", default="data/bugfix_train_hard.jsonl") | |
| p.add_argument("--checkpoint-dir", default="checkpoints") | |
| p.add_argument("--resume", default=None) | |
| p.add_argument("--dtype", default="bfloat16") | |
| p.add_argument("--no-compile", action="store_true") | |
| p.add_argument("--batch-size", type=int, default=2) | |
| p.add_argument("--grad-accum", type=int, default=16) | |
| args = p.parse_args() | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| props = torch.cuda.get_device_properties(0) | |
| print(f"[gpu] {props.name} ({props.total_memory/1e9:.1f} GB)") | |
| cfg = BugScopeConfig() | |
| model = BugScopeModel(cfg).to(device) | |
| print(f"[model] {model.param_count_str()} ({model.param_count():,} params)") | |
| print(f"[model] {cfg.n_layers}L / {cfg.hidden_dim}d / {cfg.n_heads}Qh / {cfg.n_kv_heads}KVh") | |
| print(f"[model] Effective batch: {args.batch_size} x {args.grad_accum} = {args.batch_size * args.grad_accum}") | |
| resume_step = 0 | |
| if args.resume and os.path.isfile(args.resume): | |
| print(f"[resume] Loading {args.resume}") | |
| ckpt = torch.load(args.resume, map_location=device, weights_only=False) | |
| model.load_state_dict(ckpt["model"]) | |
| resume_step = ckpt.get("step", 0) | |
| print(f"[resume] From step {resume_step}") | |
| tokenizer = BugScopeTokenizer() | |
| if args.phase in (0, 2) and os.path.isfile(args.bugfix_data): | |
| print(f"\n{'='*60}\n PHASE 2: Bug-Fix Format Training\n{'='*60}") | |
| ds = BugFixDataset(args.bugfix_data, tokenizer, cfg.max_seq_len) | |
| dl = DataLoader(ds, batch_size=args.batch_size, shuffle=True, num_workers=4, | |
| pin_memory=True, drop_last=True) | |
| target_epochs = 2 | |
| steps_per_epoch = len(ds) // (args.batch_size * args.grad_accum) | |
| total_steps = steps_per_epoch * target_epochs | |
| print(f" Dataset: {len(ds)} examples") | |
| print(f" Steps/epoch: ~{steps_per_epoch}") | |
| print(f" Target: {target_epochs} epochs = {total_steps} steps") | |
| success = train_phase(model, dl, "phase2_bugfix", total_steps, 1e-4, | |
| min(1000, total_steps//10), args.grad_accum, | |
| args.checkpoint_dir, checkpoint_every=999999, | |
| resume_step=resume_step, device=device, dtype_str=args.dtype) | |
| if not success: | |
| print("[ABORT] Phase 2 failed") | |
| return | |
| if args.phase in (0, 3) and os.path.isfile(args.hard_data): | |
| print(f"\n{'='*60}\n PHASE 3: Hard Bug Specialization\n{'='*60}") | |
| ds = BugFixDataset(args.hard_data, tokenizer, cfg.max_seq_len) | |
| dl = DataLoader(ds, batch_size=args.batch_size, shuffle=True, num_workers=4, | |
| pin_memory=True, drop_last=True) | |
| steps_per_epoch = max(1, len(ds) // (args.batch_size * args.grad_accum)) | |
| total_steps = steps_per_epoch * 2 | |
| print(f" Hard dataset: {len(ds)} examples") | |
| print(f" Target: 2 epochs = {total_steps} steps") | |
| train_phase(model, dl, "phase3_hard", total_steps, 5e-5, | |
| min(500, total_steps//10), args.grad_accum, | |
| args.checkpoint_dir, checkpoint_every=999999, | |
| device=device, dtype_str=args.dtype) | |
| if args.phase in (0, 4): | |
| print(f"\n{'='*60}\n Phase 4: INT8 Quantization\n{'='*60}") | |
| for name in ["phase3_hard_final","phase2_bugfix_final"]: | |
| path = os.path.join(args.checkpoint_dir, f"{name}.pt") | |
| if os.path.isfile(path): | |
| ckpt = torch.load(path, map_location="cpu", weights_only=False) | |
| q_model = BugScopeModel(cfg) | |
| q_model.load_state_dict(ckpt["model"]) | |
| q_model.eval() | |
| quantized = torch.ao.quantization.quantize_dynamic(q_model, {nn.Linear}, dtype=torch.qint8) | |
| q_path = os.path.join(args.checkpoint_dir, "bugscope_int8.pt") | |
| torch.save({"model":quantized.state_dict(),"config":cfg}, q_path) | |
| print(f"[quant] Saved {q_path}") | |
| break | |
| print(f"\n{'='*60}\n TRAINING COMPLETE\n{'='*60}") | |
| if __name__ == "__main__": main() | |