Datasets:
File size: 8,905 Bytes
e6a4a5f e28692d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | ---
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](https://huggingface.co/CLIWorks/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
```python
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)
```bash
python3 fp8_train.py \
--seq_len 256 --micro_batch 112 --grad_accum 4 \
--precision fp8 --n_loops 6
```
### FP8 + TileKernels Training
```bash
# 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
```bash
python3 fp8_train.py --resume checkpoints-fp8/spider-step2650.pt
```
### Fresh Start (Load Weights, Reset Optimizer)
```bash
python3 fp8_train.py --resume checkpoints-fp8/spider-step2650.pt --reset_steps
```
### With torch.compile
```bash
python3 fp8_train.py --compile --precision fp8
```
### Mock Data (Quick Test)
```bash
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:
```bash
cd tile_kernels && pip install -e .
```
## Tokenizer
Byte-level encoding (no learned tokenizer needed):
```python
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.
|