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+
#!/usr/bin/env python3
|
| 2 |
+
"""Spider-FLEXITOKENS training pipeline with torchao FP8.
|
| 3 |
+
|
| 4 |
+
Uses torchao's Float8Linear for FP8 training on Blackwell (sm_120):
|
| 5 |
+
- rowwise_with_gw_hp recipe: row-wise scaling + high-precision grad weight
|
| 6 |
+
- Activations/weights quantized to float8_e4m3fn in forward/backward
|
| 7 |
+
- High-precision accumulation preserved for stability
|
| 8 |
+
- ~2x VRAM reduction vs BF16 on linear layers
|
| 9 |
+
|
| 10 |
+
Falls back to BF16 if torchao is unavailable.
|
| 11 |
+
|
| 12 |
+
Architecture: SpiderForConditionalGeneration (RDT, MoE, MLA, FlexiTokens).
|
| 13 |
+
Byte-level vocab 272, pre-tokenized FineWeb-Edu shards at /fineweb_bytelevel/.
|
| 14 |
+
|
| 15 |
+
Usage:
|
| 16 |
+
python fp8_train.py
|
| 17 |
+
python fp8_train.py --mock_data --max_steps 50
|
| 18 |
+
python fp8_train.py --micro_batch 64 --seq_len 128 --precision fp8
|
| 19 |
+
python fp8_train.py --resume checkpoints-fp8/spider-step50.pt
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
import os
|
| 23 |
+
import gc
|
| 24 |
+
import math
|
| 25 |
+
import sys
|
| 26 |
+
import time
|
| 27 |
+
import argparse
|
| 28 |
+
import re
|
| 29 |
+
import enum
|
| 30 |
+
from contextlib import nullcontext
|
| 31 |
+
|
| 32 |
+
import torch
|
| 33 |
+
import torch.nn as nn
|
| 34 |
+
import torch.nn.functional as F
|
| 35 |
+
from torch.nn import CrossEntropyLoss
|
| 36 |
+
from torch.utils.data import IterableDataset, DataLoader, get_worker_info
|
| 37 |
+
|
| 38 |
+
from datasets import load_dataset
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
import bitsandbytes as bnb
|
| 42 |
+
AdamW8bit = bnb.optim.AdamW8bit
|
| 43 |
+
_HAS_8BIT = True
|
| 44 |
+
except ImportError:
|
| 45 |
+
_HAS_8BIT = False
|
| 46 |
+
AdamW8bit = None
|
| 47 |
+
|
| 48 |
+
try:
|
| 49 |
+
from torchao.float8 import convert_to_float8_training, Float8LinearConfig
|
| 50 |
+
_HAS_TORCHAO_FP8 = True
|
| 51 |
+
except ImportError:
|
| 52 |
+
_HAS_TORCHAO_FP8 = False
|
| 53 |
+
|
| 54 |
+
import importlib
|
| 55 |
+
_fp8_spider = importlib.import_module("fp8-ready-spider")
|
| 56 |
+
SpiderConfig = _fp8_spider.SpiderConfig
|
| 57 |
+
SpiderForConditionalGeneration = _fp8_spider.SpiderForConditionalGeneration
|
| 58 |
+
SENTINEL_TOKENS = _fp8_spider.SENTINEL_TOKENS
|
| 59 |
+
|
| 60 |
+
try:
|
| 61 |
+
from loguru import logger
|
| 62 |
+
logger.remove()
|
| 63 |
+
logger.add(sys.stderr, format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}")
|
| 64 |
+
logger.add("train_fp8.log", rotation="100 MB", retention="10 days",
|
| 65 |
+
format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}")
|
| 66 |
+
except ImportError:
|
| 67 |
+
import logging
|
| 68 |
+
logging.basicConfig(level=logging.INFO)
|
| 69 |
+
class _LoguruShim:
|
| 70 |
+
def info(self, msg): logging.info(msg)
|
| 71 |
+
def success(self, msg): logging.info(msg)
|
| 72 |
+
def warning(self, msg): logging.warning(msg)
|
| 73 |
+
def error(self, msg): logging.error(msg)
|
| 74 |
+
logger = _LoguruShim()
|
| 75 |
+
|
| 76 |
+
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
|
| 77 |
+
|
| 78 |
+
BOS_ID = SENTINEL_TOKENS['BOS']
|
| 79 |
+
EOS_ID = SENTINEL_TOKENS['EOS']
|
| 80 |
+
PAD_ID = SENTINEL_TOKENS['PAD']
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# ============================================================================
|
| 84 |
+
# Precision Mode
|
| 85 |
+
# ============================================================================
|
| 86 |
+
|
| 87 |
+
class PrecisionMode(enum.Enum):
|
| 88 |
+
BF16 = "bf16"
|
| 89 |
+
FP8 = "fp8"
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def detect_precision_mode() -> PrecisionMode:
|
| 93 |
+
if not torch.cuda.is_available():
|
| 94 |
+
return PrecisionMode.BF16
|
| 95 |
+
cc = torch.cuda.get_device_capability()
|
| 96 |
+
if cc[0] >= 12 and _HAS_TORCHAO_FP8:
|
| 97 |
+
return PrecisionMode.FP8
|
| 98 |
+
if cc[0] >= 8 and _HAS_TORCHAO_FP8:
|
| 99 |
+
return PrecisionMode.FP8
|
| 100 |
+
return PrecisionMode.BF16
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def configure_fp8_training(model, recipe_name="tensorwise"):
|
| 104 |
+
base = Float8LinearConfig.from_recipe_name(recipe_name)
|
| 105 |
+
config = Float8LinearConfig(
|
| 106 |
+
cast_config_input=base.cast_config_input,
|
| 107 |
+
cast_config_weight=base.cast_config_weight,
|
| 108 |
+
cast_config_grad_output=base.cast_config_grad_output,
|
| 109 |
+
cast_config_input_for_grad_weight=base.cast_config_input_for_grad_weight,
|
| 110 |
+
cast_config_weight_for_grad_input=base.cast_config_weight_for_grad_input,
|
| 111 |
+
cast_config_grad_output_for_grad_weight=base.cast_config_grad_output_for_grad_weight,
|
| 112 |
+
gemm_config_output=base.gemm_config_output,
|
| 113 |
+
gemm_config_grad_input=base.gemm_config_grad_input,
|
| 114 |
+
gemm_config_grad_weight=base.gemm_config_grad_weight,
|
| 115 |
+
enable_fsdp_float8_all_gather=base.enable_fsdp_float8_all_gather,
|
| 116 |
+
round_scales_to_power_of_2=base.round_scales_to_power_of_2,
|
| 117 |
+
pad_inner_dim=True,
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
def module_filter_fn(mod, fqn):
|
| 121 |
+
skip = any(s in fqn for s in (
|
| 122 |
+
"boundary_predictor",
|
| 123 |
+
"loop_embedding",
|
| 124 |
+
"engram",
|
| 125 |
+
"layernorm",
|
| 126 |
+
"norm",
|
| 127 |
+
"embed_tokens",
|
| 128 |
+
"lm_head",
|
| 129 |
+
"halt_predictor",
|
| 130 |
+
"router",
|
| 131 |
+
))
|
| 132 |
+
return not skip
|
| 133 |
+
|
| 134 |
+
model = convert_to_float8_training(
|
| 135 |
+
model,
|
| 136 |
+
module_filter_fn=module_filter_fn,
|
| 137 |
+
config=config,
|
| 138 |
+
)
|
| 139 |
+
return model
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ============================================================================
|
| 143 |
+
# Byte-Level Datasets
|
| 144 |
+
# ============================================================================
|
| 145 |
+
|
| 146 |
+
class ByteLevelDataset(IterableDataset):
|
| 147 |
+
def __init__(self, dataset_name="HuggingFaceFW/fineweb-edu",
|
| 148 |
+
subset="sample-10BT", split="train",
|
| 149 |
+
seq_len=2048, max_bytes=2048, rank=0, world_size=1):
|
| 150 |
+
self.seq_len = seq_len
|
| 151 |
+
self.max_bytes = max_bytes
|
| 152 |
+
self.dataset_name = dataset_name
|
| 153 |
+
self.subset = subset
|
| 154 |
+
self.split = split
|
| 155 |
+
self.rank = rank
|
| 156 |
+
self.world_size = world_size
|
| 157 |
+
|
| 158 |
+
def _encode_sample(self, text):
|
| 159 |
+
byte_ids = list(text.encode('utf-8'))[:self.max_bytes]
|
| 160 |
+
return [BOS_ID] + byte_ids + [EOS_ID]
|
| 161 |
+
|
| 162 |
+
def __iter__(self):
|
| 163 |
+
worker = get_worker_info()
|
| 164 |
+
num_workers = worker.num_workers if worker else 1
|
| 165 |
+
worker_id = worker.id if worker else 0
|
| 166 |
+
total_shards = self.world_size * num_workers
|
| 167 |
+
shard_index = self.rank * num_workers + worker_id
|
| 168 |
+
ds = load_dataset(self.dataset_name, name=self.subset,
|
| 169 |
+
split=self.split, streaming=True
|
| 170 |
+
).shard(num_shards=total_shards, index=shard_index)
|
| 171 |
+
buf = []
|
| 172 |
+
for sample in ds:
|
| 173 |
+
text = sample.get("text", "")
|
| 174 |
+
if not text:
|
| 175 |
+
continue
|
| 176 |
+
byte_ids = self._encode_sample(text)
|
| 177 |
+
buf.extend(byte_ids)
|
| 178 |
+
while len(buf) >= self.seq_len + 1:
|
| 179 |
+
chunk = buf[:self.seq_len + 1]
|
| 180 |
+
buf = buf[self.seq_len + 1:]
|
| 181 |
+
x = torch.tensor(chunk[:-1], dtype=torch.long)
|
| 182 |
+
y = torch.tensor(chunk[1:], dtype=torch.long)
|
| 183 |
+
y[y == PAD_ID] = -100
|
| 184 |
+
yield x, y
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class LocalByteLevelDataset(IterableDataset):
|
| 188 |
+
def __init__(self, data_dir, seq_len=2048, rank=0, world_size=1):
|
| 189 |
+
self.seq_len = seq_len
|
| 190 |
+
self.data_dir = data_dir
|
| 191 |
+
self.rank = rank
|
| 192 |
+
self.world_size = world_size
|
| 193 |
+
self._files = self._discover_files()
|
| 194 |
+
|
| 195 |
+
def _discover_files(self):
|
| 196 |
+
import glob as _glob
|
| 197 |
+
files = sorted(
|
| 198 |
+
_glob.glob(os.path.join(self.data_dir, "**/*.bin"), recursive=True)
|
| 199 |
+
)
|
| 200 |
+
return [f for i, f in enumerate(files) if i % self.world_size == self.rank]
|
| 201 |
+
|
| 202 |
+
def __iter__(self):
|
| 203 |
+
import numpy as np
|
| 204 |
+
worker = get_worker_info()
|
| 205 |
+
num_workers = worker.num_workers if worker else 1
|
| 206 |
+
worker_id = worker.id if worker else 0
|
| 207 |
+
files = [f for i, f in enumerate(self._files) if i % num_workers == worker_id]
|
| 208 |
+
token_buffer = []
|
| 209 |
+
for filepath in files:
|
| 210 |
+
if filepath.endswith(".bin"):
|
| 211 |
+
arr = np.memmap(filepath, dtype=np.uint16, mode='r')
|
| 212 |
+
pos = 0
|
| 213 |
+
while pos + self.seq_len + 1 <= len(arr):
|
| 214 |
+
chunk = arr[pos:pos + self.seq_len + 1]
|
| 215 |
+
pos += self.seq_len + 1
|
| 216 |
+
x = torch.tensor(chunk[:-1], dtype=torch.long)
|
| 217 |
+
y = torch.tensor(chunk[1:], dtype=torch.long)
|
| 218 |
+
y[y == PAD_ID] = -100
|
| 219 |
+
yield x, y
|
| 220 |
+
token_buffer.extend(arr[pos:].tolist())
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
class MockByteLevelDataset(IterableDataset):
|
| 224 |
+
SAMPLES = [
|
| 225 |
+
"Hello world, this is a test of the byte-level encoding system.",
|
| 226 |
+
"The quick brown fox jumps over the lazy dog.",
|
| 227 |
+
"Spider is a recurrent latent reasoning architecture with engram memory.",
|
| 228 |
+
"Boundary predictors learn to merge byte sequences into meaningful tokens.",
|
| 229 |
+
"FineWeb-Edu contains high-quality educational content for pretraining.",
|
| 230 |
+
"\u042d\u0442\u043e \u0442\u0435\u043a\u0441\u0442 \u043d\u0430 \u0440\u0443\u0441\u0441\u043a\u043e\u043c \u044f\u0437\u044b\u043a\u0435.",
|
| 231 |
+
"def fibonacci(n): return n if n <= 1 else fibonacci(n-1) + fibonacci(n-2)",
|
| 232 |
+
"The integral of x^2 from 0 to 1 equals 1/3.",
|
| 233 |
+
]
|
| 234 |
+
|
| 235 |
+
def __init__(self, seq_len=512, max_bytes=512, num_samples=1000):
|
| 236 |
+
self.seq_len = seq_len
|
| 237 |
+
self.max_bytes = max_bytes
|
| 238 |
+
self.num_samples = num_samples
|
| 239 |
+
|
| 240 |
+
def __iter__(self):
|
| 241 |
+
buf = []
|
| 242 |
+
count = 0
|
| 243 |
+
while count < self.num_samples:
|
| 244 |
+
for text in self.SAMPLES:
|
| 245 |
+
byte_ids = list(text.encode('utf-8'))[:self.max_bytes]
|
| 246 |
+
ids = [BOS_ID] + byte_ids + [EOS_ID]
|
| 247 |
+
buf.extend(ids)
|
| 248 |
+
while len(buf) >= self.seq_len + 1:
|
| 249 |
+
chunk = buf[:self.seq_len + 1]
|
| 250 |
+
buf = buf[self.seq_len + 1:]
|
| 251 |
+
x = torch.tensor(chunk[:-1], dtype=torch.long)
|
| 252 |
+
y = torch.tensor(chunk[1:], dtype=torch.long)
|
| 253 |
+
y[y == PAD_ID] = -100
|
| 254 |
+
yield x, y
|
| 255 |
+
count += 1
|
| 256 |
+
if count >= self.num_samples:
|
| 257 |
+
return
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
# ============================================================================
|
| 261 |
+
# Checkpointing
|
| 262 |
+
# ============================================================================
|
| 263 |
+
|
| 264 |
+
def save_step_checkpoint(model, optimizer, step, epoch, cfg, ckpt_dir, master,
|
| 265 |
+
ddp=False, current_best_loss=float("inf")):
|
| 266 |
+
model_state = model.state_dict()
|
| 267 |
+
optim_state = optimizer.state_dict()
|
| 268 |
+
if not master:
|
| 269 |
+
return None, 0
|
| 270 |
+
os.makedirs(ckpt_dir, exist_ok=True)
|
| 271 |
+
ckpt_path = os.path.join(ckpt_dir, f"spider-step{step}.pt")
|
| 272 |
+
tmp_path = ckpt_path + ".tmp"
|
| 273 |
+
torch.save({
|
| 274 |
+
"step": step, "epoch": epoch,
|
| 275 |
+
"model_state_dict": model_state,
|
| 276 |
+
"optimizer_state_dict": optim_state,
|
| 277 |
+
"cfg": cfg, "best_loss": current_best_loss,
|
| 278 |
+
}, tmp_path)
|
| 279 |
+
os.replace(tmp_path, ckpt_path)
|
| 280 |
+
size_mb = os.path.getsize(ckpt_path) / (1024 * 1024)
|
| 281 |
+
step_pattern = re.compile(r"spider-step\d+\.pt$")
|
| 282 |
+
step_ckpts = sorted(
|
| 283 |
+
[os.path.join(ckpt_dir, f) for f in os.listdir(ckpt_dir) if step_pattern.search(f)],
|
| 284 |
+
key=os.path.getmtime,
|
| 285 |
+
)
|
| 286 |
+
while len(step_ckpts) > 2:
|
| 287 |
+
old = step_ckpts.pop(0)
|
| 288 |
+
os.remove(old)
|
| 289 |
+
return ckpt_path, size_mb
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def load_checkpoint(model, optimizer, path, ddp=False):
|
| 293 |
+
ckpt = torch.load(path, map_location="cpu", weights_only=False)
|
| 294 |
+
if "model_state_dict" not in ckpt:
|
| 295 |
+
model.load_state_dict(ckpt, strict=False)
|
| 296 |
+
return 0, 0, float("inf")
|
| 297 |
+
model.load_state_dict(ckpt["model_state_dict"])
|
| 298 |
+
try:
|
| 299 |
+
optimizer.load_state_dict(ckpt["optimizer_state_dict"])
|
| 300 |
+
except (ValueError, KeyError, RuntimeError) as e:
|
| 301 |
+
logger.warning(f"Optimizer state mismatch: {e}. Skipping optimizer state.")
|
| 302 |
+
saved_best_loss = ckpt.get("best_loss", float("inf"))
|
| 303 |
+
return int(ckpt["step"]), int(ckpt.get("epoch", 0)), saved_best_loss
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
# ============================================================================
|
| 307 |
+
# LR Schedule
|
| 308 |
+
# ============================================================================
|
| 309 |
+
|
| 310 |
+
def get_lr(step, warmup, total, max_lr, min_lr):
|
| 311 |
+
if step < warmup:
|
| 312 |
+
return max_lr * step / warmup
|
| 313 |
+
if step >= total:
|
| 314 |
+
return min_lr
|
| 315 |
+
decay = (step - warmup) / (total - warmup)
|
| 316 |
+
return min_lr + 0.5 * (max_lr - min_lr) * (1.0 + math.cos(math.pi * decay))
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
# ============================================================================
|
| 320 |
+
# Main
|
| 321 |
+
# ============================================================================
|
| 322 |
+
|
| 323 |
+
def parse_args():
|
| 324 |
+
parser = argparse.ArgumentParser(description="Spider-FLEXITOKENS FP8/BF16 training")
|
| 325 |
+
parser.add_argument("--resume", type=str, default="")
|
| 326 |
+
parser.add_argument("--reset_steps", action="store_true", help="Load weights but reset step/epoch to 0")
|
| 327 |
+
parser.add_argument("--max_steps", type=int, default=0)
|
| 328 |
+
parser.add_argument("--mock_data", action="store_true")
|
| 329 |
+
parser.add_argument("--seq_len", type=int, default=0)
|
| 330 |
+
parser.add_argument("--micro_batch", type=int, default=0)
|
| 331 |
+
parser.add_argument("--grad_accum", type=int, default=0, help="Gradient accumulation steps (0=auto)")
|
| 332 |
+
parser.add_argument("--n_loops", type=int, default=0)
|
| 333 |
+
parser.add_argument("--lr", type=float, default=0)
|
| 334 |
+
parser.add_argument("--ckpt_dir", type=str, default="checkpoints-fp8")
|
| 335 |
+
parser.add_argument("--data_dir", type=str, default="/home/lamcodealong/fineweb_bytelevel")
|
| 336 |
+
parser.add_argument("--no_gradient_checkpointing", action="store_true")
|
| 337 |
+
parser.add_argument("--precision", type=str, default="auto",
|
| 338 |
+
choices=["auto", "bf16", "fp8"],
|
| 339 |
+
help="Training precision: auto (detect), bf16, fp8 (torchao)")
|
| 340 |
+
parser.add_argument("--compile", action="store_true",
|
| 341 |
+
help="torch.compile the model for optimized kernels")
|
| 342 |
+
return parser.parse_args()
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def main():
|
| 346 |
+
args = parse_args()
|
| 347 |
+
|
| 348 |
+
ddp = int(os.environ.get("RANK", -1)) != -1
|
| 349 |
+
if ddp:
|
| 350 |
+
import torch.distributed as dist
|
| 351 |
+
dist.init_process_group("nccl")
|
| 352 |
+
rank = int(os.environ["RANK"])
|
| 353 |
+
local_rank = int(os.environ["LOCAL_RANK"])
|
| 354 |
+
world_size = int(os.environ["WORLD_SIZE"])
|
| 355 |
+
device = f"cuda:{local_rank}"
|
| 356 |
+
torch.cuda.set_device(device)
|
| 357 |
+
else:
|
| 358 |
+
rank = local_rank = 0
|
| 359 |
+
world_size = 1
|
| 360 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 361 |
+
master = rank == 0
|
| 362 |
+
|
| 363 |
+
seq_len = args.seq_len or int(os.environ.get("SEQ_LEN", "2048"))
|
| 364 |
+
micro_batch = args.micro_batch or int(os.environ.get("MICRO_BATCH", "64"))
|
| 365 |
+
target_tokens = int(os.environ.get("TARGET_TOKENS", "10_000_000_000"))
|
| 366 |
+
grad_accum = args.grad_accum if args.grad_accum and args.grad_accum > 0 else int(os.environ.get("GRAD_ACCUM", "1"))
|
| 367 |
+
n_loops = args.n_loops or int(os.environ.get("N_LOOPS", "6"))
|
| 368 |
+
lr = args.lr or float(os.environ.get("LR", "3e-4"))
|
| 369 |
+
wd = 0.1
|
| 370 |
+
warmup_steps = 200
|
| 371 |
+
log_every = 10
|
| 372 |
+
ckpt_every = int(os.environ.get("CKPT_EVERY", "50"))
|
| 373 |
+
ckpt_dir = args.ckpt_dir
|
| 374 |
+
|
| 375 |
+
global_batch_tok = world_size * micro_batch * grad_accum * seq_len
|
| 376 |
+
total_steps = target_tokens // global_batch_tok
|
| 377 |
+
if args.max_steps > 0:
|
| 378 |
+
total_steps = min(total_steps, args.max_steps)
|
| 379 |
+
|
| 380 |
+
cfg = SpiderConfig()
|
| 381 |
+
bf16_ok = torch.cuda.is_available() and torch.cuda.is_bf16_supported()
|
| 382 |
+
amp_dtype = torch.bfloat16 if bf16_ok else torch.float16
|
| 383 |
+
|
| 384 |
+
if args.precision == "auto":
|
| 385 |
+
prec_mode = detect_precision_mode()
|
| 386 |
+
elif args.precision == "fp8":
|
| 387 |
+
prec_mode = PrecisionMode.FP8
|
| 388 |
+
else:
|
| 389 |
+
prec_mode = PrecisionMode.BF16
|
| 390 |
+
|
| 391 |
+
if prec_mode == PrecisionMode.FP8 and not _HAS_TORCHAO_FP8:
|
| 392 |
+
logger.warning("torchao FP8 not available, falling back to BF16")
|
| 393 |
+
prec_mode = PrecisionMode.BF16
|
| 394 |
+
|
| 395 |
+
if master:
|
| 396 |
+
logger.info(
|
| 397 |
+
f"[Spider-FLEXITOKENS] hidden=2048 | 6 recurrent | 32 experts top-2 | "
|
| 398 |
+
f"n_loops={n_loops} | seq_len={seq_len} | micro_batch={micro_batch} | "
|
| 399 |
+
f"grad_accum={grad_accum} | global_batch_tokens={global_batch_tok:,} | "
|
| 400 |
+
f"total_steps={total_steps:,}"
|
| 401 |
+
)
|
| 402 |
+
logger.info(
|
| 403 |
+
f"Byte-level vocab: 272 | Precision: {prec_mode.value} | "
|
| 404 |
+
f"Gradient checkpointing: {'disabled' if args.no_gradient_checkpointing else 'enabled'}"
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
model = SpiderForConditionalGeneration(cfg).to(amp_dtype)
|
| 408 |
+
|
| 409 |
+
if prec_mode == PrecisionMode.FP8:
|
| 410 |
+
try:
|
| 411 |
+
recipe = "tensorwise"
|
| 412 |
+
model = configure_fp8_training(model, recipe_name=recipe)
|
| 413 |
+
if master:
|
| 414 |
+
n_fp8 = sum(1 for m in model.modules() if m.__class__.__name__ == "Float8Linear")
|
| 415 |
+
n_linear = sum(1 for m in model.modules() if isinstance(m, nn.Linear))
|
| 416 |
+
logger.info(f"torchao FP8: {n_fp8} Float8Linear / {n_fp8 + n_linear} total linear layers (recipe={recipe})")
|
| 417 |
+
except Exception as e:
|
| 418 |
+
if master:
|
| 419 |
+
logger.warning(f"FP8 setup failed ({e}), falling back to BF16")
|
| 420 |
+
prec_mode = PrecisionMode.BF16
|
| 421 |
+
|
| 422 |
+
if not args.no_gradient_checkpointing:
|
| 423 |
+
model.gradient_checkpointing_enable()
|
| 424 |
+
model.enable_input_require_grads()
|
| 425 |
+
|
| 426 |
+
model = model.to(device)
|
| 427 |
+
|
| 428 |
+
if args.compile:
|
| 429 |
+
model = torch.compile(model, mode="default")
|
| 430 |
+
if master:
|
| 431 |
+
logger.info("Model compiled with torch.compile (reduce-overhead)")
|
| 432 |
+
|
| 433 |
+
if ddp:
|
| 434 |
+
model = torch.nn.parallel.DistributedDataParallel(
|
| 435 |
+
model, device_ids=[local_rank], output_device=local_rank,
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
if master:
|
| 439 |
+
n_params = sum(p.numel() for p in model.parameters())
|
| 440 |
+
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 441 |
+
logger.info(
|
| 442 |
+
f"Parameters: {n_params:,} total | {trainable:,} trainable | Precision: {prec_mode.value}"
|
| 443 |
+
)
|
| 444 |
+
|
| 445 |
+
if _HAS_8BIT:
|
| 446 |
+
optimizer = AdamW8bit(
|
| 447 |
+
model.parameters(), lr=lr, weight_decay=wd,
|
| 448 |
+
betas=(0.9, 0.95), eps=1e-8,
|
| 449 |
+
)
|
| 450 |
+
if master:
|
| 451 |
+
logger.info("Optimizer: 8-bit AdamW (saves ~50% optimizer VRAM)")
|
| 452 |
+
else:
|
| 453 |
+
optimizer = torch.optim.AdamW(
|
| 454 |
+
model.parameters(), lr=lr, weight_decay=wd,
|
| 455 |
+
betas=(0.9, 0.95), foreach=True, eps=1e-8,
|
| 456 |
+
)
|
| 457 |
+
if master:
|
| 458 |
+
logger.info("Optimizer: standard AdamW")
|
| 459 |
+
|
| 460 |
+
start_step = 0
|
| 461 |
+
start_epoch = 1
|
| 462 |
+
best_loss = float("inf")
|
| 463 |
+
if args.resume and os.path.exists(args.resume):
|
| 464 |
+
if master:
|
| 465 |
+
logger.info(f"Resuming from checkpoint: {args.resume}")
|
| 466 |
+
start_step, start_epoch, best_loss = load_checkpoint(model, optimizer, args.resume, ddp)
|
| 467 |
+
if args.reset_steps:
|
| 468 |
+
if master:
|
| 469 |
+
logger.info(f"Reset steps: step {start_step} -> 0, epoch {start_epoch} -> 1")
|
| 470 |
+
start_step = 0
|
| 471 |
+
start_epoch = 1
|
| 472 |
+
best_loss = float("inf")
|
| 473 |
+
for group in optimizer.param_groups:
|
| 474 |
+
for p in group['params']:
|
| 475 |
+
state = optimizer.state.get(p, {})
|
| 476 |
+
for k in ('exp_avg', 'exp_avg_sq', 'max_exp_avg_sq'):
|
| 477 |
+
if k in state:
|
| 478 |
+
state[k].zero_()
|
| 479 |
+
if master:
|
| 480 |
+
logger.info("Optimizer state reset (momentum/variance zeroed)")
|
| 481 |
+
if master:
|
| 482 |
+
logger.info(f"Resumed at step {start_step}, epoch {start_epoch}, best_loss={best_loss:.4f}")
|
| 483 |
+
else:
|
| 484 |
+
existing_ckpts = sorted(
|
| 485 |
+
[os.path.join(ckpt_dir, f) for f in os.listdir(ckpt_dir)
|
| 486 |
+
if f.startswith("spider-") and f.endswith(".pt") and not f.endswith(".tmp")]
|
| 487 |
+
) if os.path.isdir(ckpt_dir) else []
|
| 488 |
+
if existing_ckpts:
|
| 489 |
+
latest = existing_ckpts[-1]
|
| 490 |
+
if master:
|
| 491 |
+
logger.info(f"Auto-resuming from: {latest}")
|
| 492 |
+
start_step, start_epoch, best_loss = load_checkpoint(model, optimizer, latest, ddp)
|
| 493 |
+
if master:
|
| 494 |
+
logger.info(f"Resumed at step {start_step}, epoch {start_epoch}, best_loss={best_loss:.4f}")
|
| 495 |
+
|
| 496 |
+
if master:
|
| 497 |
+
logger.info("Running FP8 warmup (2 fwd+bwd passes to compile kernels)...")
|
| 498 |
+
model.train()
|
| 499 |
+
for _w in range(2):
|
| 500 |
+
_wx = torch.randint(4, 256, (2, seq_len), device=device)
|
| 501 |
+
_wy = torch.randint(4, 256, (2, seq_len), device=device)
|
| 502 |
+
_wo = model(_wx, labels=_wy, n_loops=n_loops)
|
| 503 |
+
_wo['loss'].backward()
|
| 504 |
+
optimizer.zero_grad(set_to_none=True)
|
| 505 |
+
del _wx, _wy, _wo
|
| 506 |
+
torch.cuda.synchronize()
|
| 507 |
+
if master:
|
| 508 |
+
peak_warmup = torch.cuda.max_memory_allocated() / 1024**3
|
| 509 |
+
logger.info(f"Warmup done | Peak VRAM: {peak_warmup:.1f}GB")
|
| 510 |
+
|
| 511 |
+
if args.mock_data:
|
| 512 |
+
dataset = MockByteLevelDataset(seq_len=seq_len, num_samples=5000)
|
| 513 |
+
elif args.data_dir and os.path.isdir(args.data_dir):
|
| 514 |
+
dataset = LocalByteLevelDataset(
|
| 515 |
+
data_dir=args.data_dir, seq_len=seq_len,
|
| 516 |
+
rank=rank, world_size=world_size,
|
| 517 |
+
)
|
| 518 |
+
else:
|
| 519 |
+
dataset = ByteLevelDataset(seq_len=seq_len, rank=rank, world_size=world_size)
|
| 520 |
+
|
| 521 |
+
loader = DataLoader(
|
| 522 |
+
dataset,
|
| 523 |
+
batch_size=micro_batch,
|
| 524 |
+
num_workers=4 if not args.mock_data else 0,
|
| 525 |
+
pin_memory=True,
|
| 526 |
+
prefetch_factor=4 if not args.mock_data else None,
|
| 527 |
+
persistent_workers=True if not args.mock_data else False,
|
| 528 |
+
drop_last=False,
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
class _Prefetcher:
|
| 532 |
+
def __init__(self, loader, device):
|
| 533 |
+
self.loader = loader
|
| 534 |
+
self.device = device
|
| 535 |
+
self._stream = torch.cuda.Stream()
|
| 536 |
+
self._next_x = None
|
| 537 |
+
self._next_y = None
|
| 538 |
+
|
| 539 |
+
def _preload(self, data_iter):
|
| 540 |
+
try:
|
| 541 |
+
x, y = next(data_iter)
|
| 542 |
+
except StopIteration:
|
| 543 |
+
return None, None, data_iter
|
| 544 |
+
with torch.cuda.stream(self._stream):
|
| 545 |
+
self._next_x = x.to(self.device, non_blocking=True)
|
| 546 |
+
self._next_y = y.to(self.device, non_blocking=True)
|
| 547 |
+
return self._next_x, self._next_y, data_iter
|
| 548 |
+
|
| 549 |
+
def next(self, data_iter):
|
| 550 |
+
if self._next_x is not None:
|
| 551 |
+
torch.cuda.current_stream().wait_stream(self._stream)
|
| 552 |
+
x, y = self._next_x, self._next_y
|
| 553 |
+
else:
|
| 554 |
+
try:
|
| 555 |
+
x, y = next(data_iter)
|
| 556 |
+
except StopIteration:
|
| 557 |
+
return None, None, data_iter
|
| 558 |
+
x = x.to(self.device, non_blocking=True)
|
| 559 |
+
y = y.to(self.device, non_blocking=True)
|
| 560 |
+
self._next_x = None
|
| 561 |
+
self._next_y = None
|
| 562 |
+
nx, ny, data_iter = self._preload(data_iter)
|
| 563 |
+
return x, y, data_iter
|
| 564 |
+
|
| 565 |
+
prefetcher = _Prefetcher(loader, device)
|
| 566 |
+
|
| 567 |
+
if prec_mode == PrecisionMode.FP8:
|
| 568 |
+
amp_ctx = nullcontext()
|
| 569 |
+
else:
|
| 570 |
+
amp_ctx = (
|
| 571 |
+
torch.amp.autocast(device_type="cuda", dtype=amp_dtype)
|
| 572 |
+
if "cuda" in device
|
| 573 |
+
else nullcontext()
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
if master:
|
| 577 |
+
logger.info(f"Starting training from step {start_step} to {total_steps}")
|
| 578 |
+
|
| 579 |
+
model.train()
|
| 580 |
+
step = start_step
|
| 581 |
+
tokens_seen = start_step * global_batch_tok
|
| 582 |
+
t0_loop = time.time()
|
| 583 |
+
data_iter = iter(loader)
|
| 584 |
+
|
| 585 |
+
for epoch in range(start_epoch, 1000):
|
| 586 |
+
while step < total_steps:
|
| 587 |
+
current_lr = get_lr(step, warmup_steps, total_steps, lr, lr * 0.1)
|
| 588 |
+
for pg in optimizer.param_groups:
|
| 589 |
+
pg['lr'] = current_lr
|
| 590 |
+
|
| 591 |
+
optimizer.zero_grad(set_to_none=True)
|
| 592 |
+
loss_accum = 0.0
|
| 593 |
+
|
| 594 |
+
for micro_step in range(grad_accum):
|
| 595 |
+
x, y, data_iter = prefetcher.next(data_iter)
|
| 596 |
+
if x is None:
|
| 597 |
+
data_iter = iter(loader)
|
| 598 |
+
x, y, data_iter = prefetcher.next(data_iter)
|
| 599 |
+
|
| 600 |
+
sync = (
|
| 601 |
+
nullcontext()
|
| 602 |
+
if (not ddp or micro_step == grad_accum - 1)
|
| 603 |
+
else model.no_sync()
|
| 604 |
+
) if ddp else nullcontext()
|
| 605 |
+
|
| 606 |
+
with sync, amp_ctx:
|
| 607 |
+
output = model(x, labels=y, n_loops=n_loops)
|
| 608 |
+
loss = output['loss'] / grad_accum
|
| 609 |
+
loss.backward()
|
| 610 |
+
|
| 611 |
+
loss_accum += loss.item() * grad_accum
|
| 612 |
+
|
| 613 |
+
if master and step == start_step and micro_step == 0:
|
| 614 |
+
peak_vram = torch.cuda.max_memory_allocated() / 1024**3
|
| 615 |
+
logger.info(f"First forward+backward | Peak VRAM: {peak_vram:.1f}GB")
|
| 616 |
+
|
| 617 |
+
nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
|
| 618 |
+
optimizer.step()
|
| 619 |
+
|
| 620 |
+
step += 1
|
| 621 |
+
tokens_seen += global_batch_tok
|
| 622 |
+
|
| 623 |
+
if step % 10 == 0:
|
| 624 |
+
gc.collect()
|
| 625 |
+
torch.cuda.empty_cache()
|
| 626 |
+
|
| 627 |
+
if step % log_every == 0 and master:
|
| 628 |
+
elapsed = time.time() - t0_loop
|
| 629 |
+
tps = log_every * global_batch_tok / elapsed if elapsed > 0 else 0
|
| 630 |
+
loss_val = loss_accum
|
| 631 |
+
if loss_val < best_loss:
|
| 632 |
+
best_loss = loss_val
|
| 633 |
+
logger.info(
|
| 634 |
+
f"Epoch {epoch} | step {step}/{total_steps} | loss {loss_val:.4f} | "
|
| 635 |
+
f"lr {current_lr:.2e} | {tps/1e3:.1f}k tok/s | "
|
| 636 |
+
f"prec {prec_mode.value} | tokens {tokens_seen/1e6:.2f}M"
|
| 637 |
+
)
|
| 638 |
+
t0_loop = time.time()
|
| 639 |
+
|
| 640 |
+
if step % ckpt_every == 0 and master:
|
| 641 |
+
ckpt_path, ckpt_mb = save_step_checkpoint(
|
| 642 |
+
model, optimizer, step, epoch, cfg, ckpt_dir, master,
|
| 643 |
+
ddp=ddp, current_best_loss=best_loss,
|
| 644 |
+
)
|
| 645 |
+
if ckpt_path:
|
| 646 |
+
logger.info(f"Checkpoint saved: {ckpt_path} ({ckpt_mb:.0f} MB)")
|
| 647 |
+
|
| 648 |
+
if step >= total_steps:
|
| 649 |
+
break
|
| 650 |
+
|
| 651 |
+
if step >= total_steps:
|
| 652 |
+
break
|
| 653 |
+
|
| 654 |
+
if master:
|
| 655 |
+
final_path = os.path.join(ckpt_dir, "spider-final.pt")
|
| 656 |
+
os.makedirs(ckpt_dir, exist_ok=True)
|
| 657 |
+
torch.save({
|
| 658 |
+
"step": step, "epoch": epoch,
|
| 659 |
+
"model_state_dict": model.state_dict(),
|
| 660 |
+
"optimizer_state_dict": optimizer.state_dict(),
|
| 661 |
+
"cfg": cfg, "best_loss": best_loss,
|
| 662 |
+
}, final_path)
|
| 663 |
+
logger.info(f"Final checkpoint saved: {final_path}")
|
| 664 |
+
logger.info(f"Training complete. Total steps: {step}, Best loss: {best_loss:.4f}")
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
if __name__ == "__main__":
|
| 668 |
+
main()
|