CLIWorks's picture
Upload README.md with huggingface_hub
e6a4a5f verified
metadata
language:
  - en
license: apache-2.0
tags:
  - fp8
  - torchao
  - tile-kernels
  - moe
  - byte-level
  - blackwell
  - pretraining
  - fineweb-edu
pretty_name: Spider-FLEXITOKENS FP8 Training Data & Code
size_categories:
  - 10B<n<100B

Spider-FLEXITOKENS FP8 Training

FP8 training pipeline for Spider-FLEXITOKENS on NVIDIA Blackwell GPUs (sm_120) using torchao Float8Linear and optional TileKernels fused MoE routing.

Architecture

Spider is a Recurrent-Depth Transformer (RDT) with:

  • 1B parameters (996M), hidden_size=2048
  • Byte-level vocab: 272 tokens (256 UTF-8 bytes + 16 specials: BOS=257, EOS=258, PAD=256)
  • 6 recurrent layers with MoE (32 experts, top-2 routing) + MLA attention
  • 2 prelude + 2 coda dense layers
  • Engram conditional memory at recurrent layers 1 and 4
  • FlexiTokens via BoundaryPredictor + downsample/upsample
  • ACT halting with LTI injection + LoRA adapter per loop iteration
  • Gradient checkpointing on recurrent layers

Training Scripts

File Description
fp8_train.py Pure torchao FP8 training (Python MoE loop)
tk-train.py torchao FP8 + TileKernels fused MoE routing
fp8-ready-spider.py Model definition (Python MoE loop) — used by fp8_train.py
tk-spider.py Model definition (TileKernels MoE) — used by tk-train.py

fp8_train.py

Standard torchao FP8 training. Uses Python loops for MoE expert routing (top-2 gating, expert dispatch, weighted reduction). All linear layers (except embeddings, norms, routers, predictors) are converted to Float8Linear with the tensorwise recipe.

tk-train.py

Same as fp8_train.py but replaces the Python MoE loop with TileKernels fused CUDA kernels:

  • topk_gate — fused top-k gating
  • normalize_weight — gate weight normalization
  • get_fused_mapping — expert-token mapping computation
  • expand_to_fused — token-to-expert expansion
  • reduce_fused — expert output reduction
  • aux_fi — auxiliary load-balancing loss

Falls back to Python MoE loop if TileKernels is unavailable.

Requirements

  • GPU: NVIDIA Blackwell (sm_120) or Hopper (sm_90)
  • CUDA: 13.2+
  • PyTorch: 2.11.0+ (with CUDA 13.x support)
  • torchao: pip install torchao (for Float8Linear FP8 training)
  • TileKernels (optional, for tk-train.py): included in tile_kernels/ directory
  • bitsandbytes (optional): for 8-bit AdamW optimizer
  • loguru (optional): logging; falls back to stdlib logging
  • numpy: for memory-mapped dataset loading

Data

FineWeb-Edu Byte-Level Dataset

Pre-tokenized FineWeb-Edu at byte level (~17B tokens, 14 shards):

  • Format: uint16 .bin files, no header
  • Vocab: BOS=257, EOS=258, PAD=256, raw bytes 0-255
  • Each shard: ~2.5GB, ~1.2B tokens
  • metadata.json with shard info
from torch.utils.data import IterableDataset, DataLoader, get_worker_info
import numpy as np, os, torch

class LocalByteLevelDataset(IterableDataset):
    def __init__(self, data_dir, seq_len=2048, rank=0, world_size=1):
        self.seq_len = seq_len
        self.data_dir = data_dir
        self.rank = rank
        self.world_size = world_size
        self._files = self._discover_files()

    def _discover_files(self):
        import glob as _glob
        files = sorted(_glob.glob(os.path.join(self.data_dir, "**/*.bin"), recursive=True))
        return [f for i, f in enumerate(files) if i % self.world_size == self.rank]

    def __iter__(self):
        worker = get_worker_info()
        num_workers = worker.num_workers if worker else 1
        worker_id = worker.id if worker else 0
        files = [f for i, f in enumerate(self._files) if i % num_workers == worker_id]
        for filepath in files:
            arr = np.memmap(filepath, dtype=np.uint16, mode='r')
            pos = 0
            while pos + self.seq_len + 1 <= len(arr):
                chunk = arr[pos:pos + self.seq_len + 1]
                pos += self.seq_len + 1
                x = torch.tensor(chunk[:-1], dtype=torch.long)
                y = torch.tensor(chunk[1:], dtype=torch.long)
                y[y == 256] = -100  # PAD_ID = -100 for loss
                yield x, y

Usage

FP8 Training (torchao only)

python3 fp8_train.py \
    --seq_len 256 --micro_batch 112 --grad_accum 4 \
    --precision fp8 --n_loops 6

FP8 + TileKernels Training

# Make TileKernels importable
export PYTHONPATH="$HOME/TileKernels:$PYTHONPATH"

python3 tk-train.py \
    --seq_len 256 --micro_batch 112 --grad_accum 4 \
    --precision fp8 --n_loops 6

Resume from Checkpoint

python3 fp8_train.py --resume checkpoints-fp8/spider-step2650.pt

Fresh Start (Load Weights, Reset Optimizer)

python3 fp8_train.py --resume checkpoints-fp8/spider-step2650.pt --reset_steps

With torch.compile

python3 fp8_train.py --compile --precision fp8

Mock Data (Quick Test)

python3 fp8_train.py --mock_data --max_steps 20 --seq_len 128 --micro_batch 2

CLI Flags

Flag Default Description
--seq_len 2048 Sequence length
--micro_batch 64 Micro batch size per GPU
--grad_accum 1 (env: GRAD_ACCUM) Gradient accumulation steps
--n_loops 6 (env: N_LOOPS) RDT loop iterations
--lr 3e-4 (env: LR) Peak learning rate
--precision auto auto, fp8, or bf16
--compile off Enable torch.compile(mode="default")
--resume auto-detect Path to checkpoint
--reset_steps off Load weights, zero optimizer, reset step=0
--ckpt_dir checkpoints-fp8 / checkpoints-tk Checkpoint directory
--data_dir /home/lamcodealong/fineweb_bytelevel Local .bin data directory
--mock_data off Use synthetic data for testing
--max_steps 0 (unlimited) Max training steps
--no_gradient_checkpointing off Disable grad checkpointing

Environment Variables

Variable Default Description
SEQ_LEN 2048 Override --seq_len
MICRO_BATCH 64 Override --micro_batch
GRAD_ACCUM 1 Override --grad_accum
N_LOOPS 6 Override --n_loops
LR 3e-4 Override --lr
TARGET_TOKENS 10B Total training tokens
CKPT_EVERY 50 Steps between checkpoints

FP8 Configuration

  • Recipe: tensorwise (axiswise incompatible with grad checkpointing + reshape on sm_120)
  • Module filter: Skips boundary_predictor, loop_embedding, engram, layernorm, norm, embed_tokens, lm_head, halt_predictor, router
  • pad_inner_dim=True: Pads linear layer inner dims for FP8 alignment
  • Warmup: 2 fwd+bwd passes with dummy data before training starts (kernel compilation)

Performance

Benchmarked on RTX PRO 6000 (Blackwell sm_120, 96GB VRAM):

Config Throughput Peak VRAM
FP8, mb=112, seq=256, ga=4 ~11.8k tok/s 25.3 GB
FP8, mb=64, seq=2048, ga=1 ~2.2k tok/s ~42 GB

Checkpoints

Latest checkpoint: spider-step2650.pt (3.8GB)

  • Contains: model_state_dict, optimizer_state_dict, step, epoch, cfg, best_loss
  • Step 2650, loss ~1.9

TileKernels

TileKernels provides fused CUDA/Triton kernels for MoE operations. Only the MoE routing kernels are used here (no weight dtype changes):

  • tile_kernels.moe.topk_gate — fused top-k gating
  • tile_kernels.moe.normalize_weight — gate weight L2 normalization
  • tile_kernels.moe.get_fused_mapping — compute expert-token dispatch mapping
  • tile_kernels.moe.expand_to_fused — expand tokens to expert slots
  • tile_kernels.moe.reduce_fused — reduce expert outputs back to tokens
  • tile_kernels.moe.aux_fi — auxiliary load-balancing loss

Install from the included tile_kernels/ directory:

cd tile_kernels && pip install -e .

Tokenizer

Byte-level encoding (no learned tokenizer needed):

def encode(text: str) -> list[int]:
    return [257] + list(text.encode('utf-8')) + [258]  # BOS + bytes + EOS

def decode(ids: list[int]) -> str:
    return bytes(i for i in ids if 0 <= i <= 255).decode('utf-8', errors='replace')

Special tokens: PAD=256, BOS=257, EOS=258, IMG_START=0, IMG_END=1, IMG_PATCH=2, IMG_NEWLINE=3, plus boundary and loop sentinels.

Known Limitations

  • DeepGEMM: Blocked on sm_120 (Unknown recipe arch_major: 12)
  • FlashMLA: sm_100f kernels produce CUTLASS errors on sm_120
  • TransformerEngine: cublasLtGroupedMatrixLayoutInit_internal symbol error
  • torchao axiswise recipe: Incompatible with gradient checkpointing + reshape on sm_120
  • torch.compile reduce-overhead mode: Has issues; use mode="default" only

License

Same as Spider-FLEXITOKENS.