FigQuant GPU training test (with dtype fix)
Browse files- figquant_gpu_fixed.py +92 -0
figquant_gpu_fixed.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""FigQuant training on GPU with the dtype fix applied."""
|
| 3 |
+
import os, sys, subprocess, time, gc
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
subprocess.check_call([sys.executable, "-m", "pip", "install", "-q",
|
| 7 |
+
"transformers", "accelerate", "datasets", "sentencepiece", "protobuf", "psutil", "numpy"])
|
| 8 |
+
subprocess.check_call(["git", "clone", "https://github.com/ticketguy/littlefig.git", "/app/littlefig"])
|
| 9 |
+
subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "-e", "/app/littlefig[train]"])
|
| 10 |
+
sys.path.insert(0, "/app/littlefig/src")
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
|
| 14 |
+
def log(msg): print(f"[GPU] {msg}", flush=True)
|
| 15 |
+
|
| 16 |
+
log(f"PyTorch {torch.__version__}, CUDA={torch.cuda.is_available()}")
|
| 17 |
+
if torch.cuda.is_available():
|
| 18 |
+
log(f"GPU: {torch.cuda.get_device_name()} ({torch.cuda.get_device_properties(0).total_memory/1e9:.1f}GB)")
|
| 19 |
+
|
| 20 |
+
from little_fig.engine import FigModel
|
| 21 |
+
from little_fig.engine.tier import TrainingTier
|
| 22 |
+
from datasets import load_dataset
|
| 23 |
+
from torch.utils.data import DataLoader
|
| 24 |
+
|
| 25 |
+
MODEL = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
|
| 26 |
+
ds = load_dataset("tatsu-lab/alpaca", split="train").select(range(1000))
|
| 27 |
+
log(f"Data: {len(ds)} examples")
|
| 28 |
+
|
| 29 |
+
log("Loading FigQuant (lowram mode)...")
|
| 30 |
+
gc.collect(); torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats()
|
| 31 |
+
|
| 32 |
+
model = FigModel.from_pretrained(MODEL, lora_r=16, lora_alpha=32,
|
| 33 |
+
tier=TrainingTier.STREAMING_LORA, target_modules=["q_proj","k_proj","v_proj","o_proj"],
|
| 34 |
+
fast=False) # lowram mode
|
| 35 |
+
tok = model.tokenizer
|
| 36 |
+
|
| 37 |
+
examples = [dict(r) for r in ds]
|
| 38 |
+
def tok_fn(ex):
|
| 39 |
+
inst=ex.get("instruction",""); inp=ex.get("input","").strip(); out=ex.get("output","")
|
| 40 |
+
txt = f"### Instruction:\n{inst}\n\n### Input:\n{inp}\n\n### Response:\n{out}" if inp else \
|
| 41 |
+
f"### Instruction:\n{inst}\n\n### Response:\n{out}"
|
| 42 |
+
e = tok(txt, truncation=True, max_length=512, padding="max_length")
|
| 43 |
+
return {"input_ids": e["input_ids"], "labels": e["input_ids"].copy(), "attention_mask": e["attention_mask"]}
|
| 44 |
+
tokenized = [tok_fn(ex) for ex in examples]
|
| 45 |
+
|
| 46 |
+
class DS(torch.utils.data.Dataset):
|
| 47 |
+
def __init__(s, d): s.d = d
|
| 48 |
+
def __len__(s): return len(s.d)
|
| 49 |
+
def __getitem__(s, i): return {k: torch.tensor(v, dtype=torch.long) for k, v in s.d[i].items()}
|
| 50 |
+
|
| 51 |
+
dl = DataLoader(DS(tokenized), batch_size=4, shuffle=True, drop_last=True)
|
| 52 |
+
dev = torch.device("cuda"); model = model.to(dev)
|
| 53 |
+
params = model.get_trainable_parameters()
|
| 54 |
+
opt = torch.optim.AdamW(params, lr=2e-4, weight_decay=0.01)
|
| 55 |
+
model.model.train()
|
| 56 |
+
|
| 57 |
+
losses = []; gs = 0; al = 0.0
|
| 58 |
+
torch.cuda.reset_peak_memory_stats()
|
| 59 |
+
t0 = time.time()
|
| 60 |
+
|
| 61 |
+
for batch in dl:
|
| 62 |
+
if gs >= 400: break # 100 optimizer steps × 4 grad accum
|
| 63 |
+
batch = {k: v.to(dev) for k, v in batch.items()}
|
| 64 |
+
with torch.autocast("cuda", dtype=torch.float16):
|
| 65 |
+
loss = model(input_ids=batch["input_ids"], attention_mask=batch["attention_mask"],
|
| 66 |
+
labels=batch["labels"]).loss / 4
|
| 67 |
+
loss.backward()
|
| 68 |
+
al += loss.item(); gs += 1
|
| 69 |
+
if gs % 4 == 0:
|
| 70 |
+
torch.nn.utils.clip_grad_norm_(params, 1.0)
|
| 71 |
+
opt.step(); opt.zero_grad()
|
| 72 |
+
s = gs // 4; losses.append(al); al = 0.0
|
| 73 |
+
if s % 20 == 0: log(f" step={s} loss={losses[-1]:.4f}")
|
| 74 |
+
|
| 75 |
+
tt = time.time() - t0
|
| 76 |
+
peak = torch.cuda.max_memory_allocated() / 1e6
|
| 77 |
+
|
| 78 |
+
log(f"\n{'='*50}")
|
| 79 |
+
log(f" FigQuant LoRA (lowram) on GPU — RESULTS")
|
| 80 |
+
log(f"{'='*50}")
|
| 81 |
+
log(f" Final loss: {losses[-1]:.4f}")
|
| 82 |
+
log(f" Time: {tt:.0f}s")
|
| 83 |
+
log(f" GPU Memory: {peak:.0f} MB")
|
| 84 |
+
log(f" Steps: {len(losses)}")
|
| 85 |
+
log(f"")
|
| 86 |
+
log(f" COMPARISON (same model, same data, same config):")
|
| 87 |
+
log(f" {'Method':>16} {'Loss':>8} {'Time':>7} {'GPU MB':>8}")
|
| 88 |
+
log(f" {'─'*44}")
|
| 89 |
+
log(f" {'FP16 LoRA':>16} {'0.2252':>8} {'1309s':>7} {'3585':>8}")
|
| 90 |
+
log(f" {'BnB NF4 QLoRA':>16} {'0.2399':>8} {'1423s':>7} {'2441':>8}")
|
| 91 |
+
log(f" {'FigQuant LoRA':>16} {losses[-1]:>8.4f} {tt:>6.0f}s {peak:>7.0f}")
|
| 92 |
+
log(f"{'='*50}")
|