Cortex-Intelligence's picture
AGENTS.md: Session 2 update (step 29855)
f1bde01 verified
|
Raw History Blame Contribute Delete
16.2 kB

AGENTS.md β€” Cortex-OSS-Flash-1.0 Pretraining Context & Seamless Resume Guide

This document provides complete project context, current Stage 1 training state, hard-won lessons/mistakes from Session 1 (so future agents never repeat them), and an exact step-by-step fast-resume playbook for fresh 4Γ— A100-80GB sessions.


1. Project Overview & Architecture

Model: Cortex-OSS-Flash-1.0 β€” Unified L2-Pinned Configurable-Depth Reasoning Core + Dual-Tier Sparse Memory (~11.67B total parameters: ~170M dense + 11.50B 4-way sharded sparse tables).

  • Dense Core (train_a100_wikipedia.py, never modify directly β€” all upgrades are runtime-patched in a100_opt_patches.py and train_stage1_cortex.py):
    • Prelude(1) β†’ Layer-2 DeepSeek Engram (with residual causal DepthwiseConv1d(1024, 1024, k=4, groups=1024) + SiLU) β†’ SharedCore(2-block recurrent cell Γ— r iters) β†’ Coda(1) β†’ Factorized Tied LM Head (D_VOCAB=1024, vocab_size=49,152, <|endoftext|>=49024).
    • Block 0: FLA Triton chunk_gated_delta_rule (GDN-2) + OrthoInj ZOH anchor injection.
    • Block 1: FlashAttention-2 SWA (W=256, natural-log LSE for MoLA) + SwiGLU + MoD-Gated UltraMemV2 (top 25% tokens).
    • ContinuousLoopCond: Continuous Fourier/sinusoidal depth conditioning patched to max frequency 2Ο€ (freqs in [1.00Ο€, 2.00Ο€]) and 0.25 * torch.tanh(...) FiLM clamp so (1 + s) ∈ [0.75, 1.25] at any unseen depth (24L, 32L, 40L, 80L).
    • Hoisted TALA-Base (dim=512), ECHO multi-horizon auxiliary head (ECHO_FIXED_DEPTH=1, 12.5% batch fused into single-pass Liger CE with Main + r_mid).
  • Dual-Tier 4-Way Sharded Sparse Memory (pure BF16 on 4Γ— A100-80GB, ~8.8 GiB/GPU allocated at init, ~38.4 GiB peak VRAM at B=64Γ—1):
    • Tier 1 Engram: 8 heads (2 heads/GPU), 1,464,844 rows/head Γ— 128 dim = 1.50B params, canonical vocab 35,574 (-27.6% surface redundancy), residual causal DepthwiseConv1d(k=4)+SiLU (5,120 params).
    • Tier 2 UltraMemV2 TDQKR: 2 heads, 3125Β² = 9.766M slots/head Γ— 512 dim = 10.00B params, topK=16/head (32 total).
  • L7 + L8 A100 Optimizations (a100_opt_patches.py):
    • strong_ultramem_balance=True (ULTRAMEM_BIAS_GAMMA=3.5e-2, clamp [-2.5, 2.5], overload pushback cap 6.0Γ—)
    • smooth_prog_depth=True (CONTRACTION_REG_COEFF=0.01, Stage 1 exact mean loop 10.00L via (3, 4, 5, 7) with probs (0.38, 0.34, 0.23, 0.05) and TBPTT = 2)
    • use_fa2_swa=True (FlashAttention-2 W=256), fast_sparse=True, int32_indices=True, fused_ce=True (Liger), fast_muon_scalars=True, async_engram=True
    • install_overlapped_dense_allreduce(model, world_size, bucket_mb=32.0) + async-pipelined install_sharded_muon(src, opt_dense) + secondary CUDA stream sparse_opt_stream.
  • Training Objective & FIM Upgrade (stage1_dataloader.py + train_stage1_cortex.py):
    • 50/50 PSM (<|fim_pre|> pre <|fim_suf|> suf <|fim_mid|> mid <|endoftext|>) and SPM (<|fim_suf|> suf <|fim_pre|> pre <|fim_mid|> mid <|endoftext|>) reusing existing tokenizer IDs inside 0..49151 (<|fim_pre|>=49036, <|fim_mid|>=49037, <|fim_suf|>=49038, <|endoftext|>=49024, zero tok_emb resize).
    • Domain-weighted FIM rate: 50% on UltraData-Stack-v3-L2, 10% on the other 5 sources (~18.7% overall).
    • Applied strictly inside single-document ≀1024-token windows before packing (skips docs <64 tokens, guarantees <PRE>/<SUF>/<MID>/<EOS> never straddle packed sequence boundaries).

2. Current State (End of Session 1)

  • HF Repository: Cortex-Intelligence/Cortex-OSS-Flash-1.0 (private)
  • Checkpoint Format: Pure .safetensors + JSON (zero .pt pickle files, end-to-end 4-rank resume β†’ save β†’ reload verified):
    • model.safetensors (repo root & checkpoint/latest/): dense model weights & buffers (220.21 MiB, 133 tensors)
    • checkpoint/latest/rank-{0..3}.safetensors: 4-way sharded Engram + UltraMemV2 sparse tables & Adam states, sharded NorMuon/AdamW tensors, RNG state tensors (8.28 / 8.26 / 8.26 / 8.26 GiB, 33.06 GiB sharded + 0.22 GiB dense = 33.29 GiB total)
    • checkpoint/latest/rank-{0..3}_meta.json: exact step, tokens seen, per-source stream cursors (file_idx, row_group_idx, doc_in_rg, epoch, seqs_consumed), mixer RNG state, depth_rng_state, opt_dense metadata
    • checkpoint/latest/train_state.json: run summary & per-dataset token counts
  • Progress:
    • Step: 15,521 / 419,616 (Stage 1 = 110.0B tokens out of 200B total run)
    • Total tokens seen: 4.0687B (3.70% of Stage 1)
    • LR schedule: Past 2,000-step warmup, constant peak LR lr_scale = 1.000 (WSD decay is OFF until Stage 4 at 90% of 200B)
    • Depth: mean_loops = 9.98, TBPTT = 2
    • Throughput: ~330–349k tok/s sustained on 4Γ— A100-80GB at B=64Γ—1 (global_B=256, 262,144 tok/step)
    • UltraMemV2 balance: router_entropy = 0.9972, MaxLoad = 3.47Γ—
  • Tokens Seen by Dataset (exact within Β±0.1% of target Stage 1 mix):
    • fineweb_edu (HuggingFaceFW/fineweb-edu, int_score >= 4, target 43.6%): 1,774.8M (43.6%)
    • ultradata_stack_v3_l2 (LvcidPsyche/UltraData-Stack-v3-L2, quality_score >= 5, target 21.8%): 886.3M (21.8%)
    • nemotron_cc_math_4plus (nvidia/Nemotron-CC-Math-v1 4plus, target 13.6%): 554.1M (13.6%)
    • scibase_filtered (Cortex-Intelligence/Scibase-filtered, target 9.1%): 370.5M (9.1%)
    • sangraha_ver_rom (ai4bharat/sangraha verified/* + synthetic/*_Latn, target 6.4%): 259.6M (6.4%)
    • wikipedia_en (wikimedia/wikipedia 20231101.en, target 5.5%): 223.4M (5.5%)
  • Held-out FineWeb-Edu Validation at Step 15,521:
    • low (8L): loss 3.0247 | PPL 20.59 | StepRMS = 0.2852
    • medium (16L): loss 3.0038 | PPL 20.16 | StepRMS = 0.0175
    • high (24L, unseen): loss 3.2016 | PPL 24.57 | StepRMS = 0.1748
    • xhigh (32L, unseen): loss 3.5428 | PPL 34.56 | StepRMS = 0.1248
    • max (40L, unseen): loss 3.7153 | PPL 41.07 | StepRMS = 0.1554

3. Session 1 Mistakes & Pitfalls (DO NOT REPEAT)

  1. Multi-threaded fsspec/aiohttp + pyarrow(use_threads=True) + background pin_memory() caused SIGSEGV (Signal 11) under torch.compile:
    • Fix already applied in stage1_dataloader.py: Stage one parquet shard at a time to local SSD (~/cortex_shard_cache) using hf_hub_download, read with use_threads=False, set TOKENIZERS_PARALLELISM=false, keep CPU tensors unpinned in background threads, and delete each shard immediately after consumption. Never re-introduce fsspec remote streaming or pin_memory() in worker threads.
  2. Trying to build flash-attn from source / looking for PyPI wheels on PyTorch 2.11 + CUDA 12.8 + Python 3.12:
    • This GPU image has no nvcc and PyPI has no flash-attn wheel for torch2.11.
    • Fix: Install the exact prebuilt wheel directly in 5 seconds (see Section 4 below). Do NOT waste GPU minutes searching or trying to compile flash-attn.
  3. One-time torch.compile (max-autotune-no-cudagraphs) takes ~12 minutes on a fresh GPU node:
    • Step 1 will sit in Inductor GEMM autotuning for 10–13 minutes before printing Step 1. Do NOT interrupt it. It caches to `/.cache/a100_train/torchinductor_cache` so any subsequent restart on the same node starts in ~2 minutes.
  4. Do NOT run a separate synthetic 5-step compile probe before training if you already know B=64Γ—1 fits:
    • We already proved B=64Γ—1 (global_B=256, 262,144 tok/step) uses only 38.4 GiB / 80 GiB peak VRAM (including the 16L probe bucket). Go straight into the resumed training command so autotuning happens once inside the real run.
  5. Non-zero-init architecture changes mid-run cause 1-step spikes:
    • Changing ContinuousLoopCond freqs (16Ο€ β†’ 2Ο€) at Step 5,000 caused a 1-step transient (LML=43.5 at Step 5,001, recovered in <60 steps). By contrast, zero-initializing Engram Conv1d at Step 7,500 gave a 0.000 spike exact-identity resume. Any future mid-run architectural addition MUST be zero-initialized as an exact identity at init.
  6. HF_HUB_ENABLE_HF_TRANSFER is deprecated in huggingface_hub >= 2.4:
    • Use HF_XET_HIGH_PERFORMANCE=1 instead β€” it achieves ~100 MB/s+ (33.3 GiB uploaded in ~3 minutes).
  7. Always reserve ~20–25 minutes of wall-clock margin inside your GPU budget:
    • Final validation + checkpoint save takes ~45s; uploading 33.3 GiB to HF takes ~3–4 minutes. Set --max-wall-seconds to (remaining_gpu_seconds - 1500).
  8. Never write HF_TOKEN into workspace files, chat messages, OR inline shell command strings:
    • Passing HF_TOKEN=... inline on a bash command line exposes it in command logs (.bg-logs/). Always store HF_TOKEN as an environment secret (e.g., via Qualia Secrets / request_secret) so scripts read os.environ["HF_TOKEN"] without exposing it in logs. Rotate any token that was previously pasted in chat or shell commands.
  9. Always use PYTHONPATH=. (or PYTHONPATH=code if running from a fresh HF snapshot) so train_stage1_cortex.py can import train_a100_wikipedia, a100_opt_patches, and stage1_dataloader.
  10. Watch TotL vs LML when reading logs:
    • TotL includes 0.25*ECHO + 0.15*r_mid + 0.25*mono_hinge + aux. Compare LML (not TotL) against held-out validation loss.

4. Seamless Fast-Resume Playbook (Fresh 4Γ— A100-80GB Session)

Step 1: Request 4Γ— A100-80GB (a100x4-48c680g) and install dependencies (~20 seconds)

Run ONE single bash command on the fresh 4Γ— A100 node:

pip install -q safetensors tokenizers aiohttp liger-kernel flash-linear-attention \
  "https://github.com/lesj0610/flash-attention/releases/download/v2.8.3-cu12-torch2.11/flash_attn-2.8.3+cu12torch2.11cxx11abiTRUE-cp312-cp312-linux_x86_64.whl"

Quick 2-second sanity check:

python -c 'import torch, safetensors, flash_attn, liger_kernel, fla; print("ALL KERNELS OK:", torch.cuda.device_count(), "GPUs")'

Step 2: Set HF_TOKEN via Secret/Env and Download Latest .safetensors Checkpoint (~3 minutes)

Ensure HF_TOKEN is set in the environment via Qualia Secrets (do not paste inline on the command line). Skip the download if ~/cortex_ckpts/latest_safetensors is already on the same node's local SSD. In a brand-new workspace, omit allow_patterns to also pull code/, data_manifests/, and tokenizer/:

HF_XET_HIGH_PERFORMANCE=1 python -c '
import os
from huggingface_hub import snapshot_download
snapshot_download(
    repo_id="Cortex-Intelligence/Cortex-OSS-Flash-1.0",
    repo_type="model",
    allow_patterns=["checkpoint/latest/*"],
    local_dir=os.path.expanduser("~/cortex_hf_resume"),
    token=os.environ["HF_TOKEN"],
)
print("Download complete!")
'

The resume directory is ~/cortex_hf_resume/checkpoint/latest (contains model.safetensors, rank-{0..3}.safetensors, rank-{0..3}_meta.json, train_state.json).

Step 3: Launch Resumed Stage 1 Pretraining (4Γ— A100-80GB)

Set --max-wall-seconds to (your_gpu_budget_seconds - 1500) (e.g., 14400 for a 4.5h budget after ~5 min setup/download). From the workspace root (or with PYTHONPATH=code if running code/train_stage1_cortex.py from a fresh HF download):

HF_XET_HIGH_PERFORMANCE=1 TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 \
torchrun --nproc_per_node=4 --master_port=29500 train_stage1_cortex.py \
  --manifest data_manifests/stage1_manifest.json \
  --tokenizer-path tokenizer/tokenizer.json \
  --resume-dir ~/cortex_hf_resume/checkpoint/latest \
  --seq-len 1024 \
  --micro-batch-size 64 \
  --grad-accum 1 \
  --warmup-steps 2000 \
  --total-run-tokens 200000000000 \
  --max-steps 420000 \
  --max-wall-seconds 14400 \
  --log-every 20 \
  --eval-every 500 \
  --save-every 2500 \
  --ckpt-root ~/cortex_ckpts \
  --metrics-jsonl logs/stage1_metrics.jsonl \
  --qualia-table cortex-stage1-pretrain \
  --enable-fim \
  --fim-rate-code 0.50 \
  --fim-rate-other 0.10 \
  --skip-preflight

What to expect on resume (verified end-to-end across all 4 ranks):

  • Step 15,522 will take 10–13 minutes on a fresh node (one-time torch.compile autotune), then steady-state runs at **`335–350k tok/s`** (~0.76s/step).
  • Step 15,522 resumes with zero loss spike (LML ~ 2.29, MemEnt ~ 0.997, MaxLd ~ 3.2Γ—, lr_scale = 1.000, tokens_seen_B = 4.069).
  • Checkpoints save in pure .safetensors + JSON every 2,500 steps (41s) and cleanly at --max-wall-seconds into `/cortex_ckpts/latest`.

Step 4: Upload Final .safetensors Checkpoint to HF Hub (~2–3 minutes)

HF_XET_HIGH_PERFORMANCE=1 PYTHONUNBUFFERED=1 python scripts/upload_to_hf.py \
  --repo-id Cortex-Intelligence/Cortex-OSS-Flash-1.0 \
  --ckpt-dir ~/cortex_ckpts/latest \
  --tokenizer-dir tokenizer \
  --manifest data_manifests/stage1_manifest.json \
  --metrics-jsonl logs/stage1_metrics.jsonl

After verifying all files on Cortex-Intelligence/Cortex-OSS-Flash-1.0, shut down the notebook kernel so the 4Γ— A100 node stops billing.


5. Key Workspace Files

  • train_a100_wikipedia.py β€” Base model architecture & Triton kernels (immutable reference).
  • a100_opt_patches.py β€” L7 + L8 A100 optimizations (FA2 SWA, overlapped dense AllReduce, sharded NorMuon, UltraMemV2 balance, progressive depth).
  • stage1_dataloader.py β€” Resumable 6-source local-SSD-staged streaming dataloader with 50/50 PSM/SPM domain-weighted FIM.
  • train_stage1_cortex.py β€” Main 4Γ— A100 Stage 1 pretraining runner with FiLM 2Ο€ + 0.25*tanh, Engram causal DepthwiseConv1d+SiLU, exact 10.00L / TBPTT=2 schedule, per-dataset token tracking, and native .safetensors checkpointing & resume.
  • scripts/upload_to_hf.py β€” Parallel HF_XET_HIGH_PERFORMANCE=1 uploader for .safetensors checkpoints, tokenizer, AGENTS.md, manifest, logs, and code.
  • scripts/convert_ckpt_to_safetensors.py β€” Utility that converted legacy .pt checkpoints to .safetensors + JSON.
  • data_manifests/stage1_manifest.json β€” Deterministic parquet shard manifest for all 6 Stage 1 datasets.
  • tokenizer/ β€” tokenizer.json, tokenizer_config.json, special_tokens_map.json (vocab_size=49,152).
  • logs/stage1_metrics.jsonl β€” Full step-by-step & validation metrics log.

6. Session 2 Update (resumed on 4x A100-80GB, step 15,521 -> 29,855)

  • State: step 29,855, 7.8263B tokens seen (7.1% of Stage 1's 110B). Checkpoint in checkpoint/latest on HF is a consistent 4-rank step-29,855 save. Throughput ~335-345k tok/s, --max-wall-seconds 10800 stopped cleanly.
  • Held-out FineWeb-Edu val loss at step 29,855: 8L 2.983, 16L 2.966, 24L 3.363 (unseen), 32L 4.699 (unseen), 40L 4.815 (unseen).
  • Watch item: unseen-depth (32L/40L) loss reached its best near step 25,000 (3.10 / 3.36) and then degraded sharply by step 29,500 while 8L/16L kept improving. Consider checking ContinuousLoopCond / contraction regularization and keep monitoring high/xhigh/max evals before Stage 2.
  • SIGTERM is safe: a stopped agent turn sends SIGTERM; the trainer finishes the step, runs validation and saves a full checkpoint ([STOP] Clean budget/signal stop). Wait for the workers to exit before copying the checkpoint; never relaunch while the save is in progress.
  • Copy the resume dir before relaunching (cp -r ~/cortex_ckpts/latest ~/cortex_resume2, wait for cp to finish) so a later save into --ckpt-root cannot clobber the checkpoint being read.
  • HF private storage limit (Private storage limit reached) blocked one upload. A failed multi-file upload leaves a mixed-step repo; restore with CommitOperationCopy(src_revision=<old sha>) (server-side, no extra storage) and re-upload only when space is available.
  • HF_TOKEN: set via Qualia secret, never inline. The token pasted in chat in Session 2 appears in workspace .bg-logs/; rotate it.
  • Metrics tables: trainer writes cortex-stage1-pretrain; scripts/sync_qualia_metrics.py --eval-only --min-eval-step N mirrors validation rows into cortex-stage1-eval.