Download AGENTS.md from Cortex-Intelligence/Cortex-OSS-Flash-1.0: direct link, hf CLI and curl.
- Browser
- Download file 16.2 kB
-
https://huggingface.co/Cortex-Intelligence/Cortex-OSS-Flash-1.0/resolve/main/AGENTS.md
- Command line
-
hf download hf://Cortex-Intelligence/Cortex-OSS-Flash-1.0/AGENTS.md
-
curl -L -o AGENTS.md https://huggingface.co/Cortex-Intelligence/Cortex-OSS-Flash-1.0/resolve/main/AGENTS.md
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 ina100_opt_patches.pyandtrain_stage1_cortex.py):Prelude(1)βLayer-2 DeepSeek Engram(with residual causalDepthwiseConv1d(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 frequency2Ο(freqsin[1.00Ο, 2.00Ο]) and0.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),ECHOmulti-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,844rows/head Γ128dim = 1.50B params, canonical vocab35,574(-27.6% surface redundancy), residual causalDepthwiseConv1d(k=4)+SiLU(5,120 params). - Tier 2 UltraMemV2 TDQKR: 2 heads,
3125Β² = 9.766Mslots/head Γ512dim = 10.00B params,topK=16/head(32 total).
- Tier 1 Engram: 8 heads (2 heads/GPU),
- 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 cap6.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)andTBPTT = 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=Trueinstall_overlapped_dense_allreduce(model, world_size, bucket_mb=32.0)+ async-pipelinedinstall_sharded_muon(src, opt_dense)+ secondary CUDA streamsparse_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 inside0..49151(<|fim_pre|>=49036,<|fim_mid|>=49037,<|fim_suf|>=49038,<|endoftext|>=49024, zerotok_embresize). - 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<64tokens, guarantees<PRE>/<SUF>/<MID>/<EOS>never straddle packed sequence boundaries).
- 50/50 PSM (
2. Current State (End of Session 1)
- HF Repository:
Cortex-Intelligence/Cortex-OSS-Flash-1.0(private) - Checkpoint Format: Pure
.safetensors+ JSON (zero.ptpickle 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 GiBsharded +0.22 GiBdense =33.29 GiBtotal)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_densemetadatacheckpoint/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/ssustained on 4Γ A100-80GB atB=64Γ1(global_B=256,262,144 tok/step) - UltraMemV2 balance:
router_entropy = 0.9972,MaxLoad = 3.47Γ
- Step:
- 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-v14plus, target 13.6%): 554.1M (13.6%)scibase_filtered(Cortex-Intelligence/Scibase-filtered, target 9.1%): 370.5M (9.1%)sangraha_ver_rom(ai4bharat/sangrahaverified/*+synthetic/*_Latn, target 6.4%): 259.6M (6.4%)wikipedia_en(wikimedia/wikipedia20231101.en, target 5.5%): 223.4M (5.5%)
- Held-out FineWeb-Edu Validation at Step 15,521:
low (8L): loss3.0247| PPL20.59|StepRMS = 0.2852medium (16L): loss3.0038| PPL20.16|StepRMS = 0.0175high (24L, unseen): loss3.2016| PPL24.57|StepRMS = 0.1748xhigh (32L, unseen): loss3.5428| PPL34.56|StepRMS = 0.1248max (40L, unseen): loss3.7153| PPL41.07|StepRMS = 0.1554
3. Session 1 Mistakes & Pitfalls (DO NOT REPEAT)
- Multi-threaded
fsspec/aiohttp+pyarrow(use_threads=True)+ backgroundpin_memory()caused SIGSEGV (Signal 11) undertorch.compile:- Fix already applied in
stage1_dataloader.py: Stage one parquet shard at a time to local SSD (~/cortex_shard_cache) usinghf_hub_download, read withuse_threads=False, setTOKENIZERS_PARALLELISM=false, keep CPU tensors unpinned in background threads, and delete each shard immediately after consumption. Never re-introducefsspecremote streaming orpin_memory()in worker threads.
- Fix already applied in
- Trying to build
flash-attnfrom source / looking for PyPI wheels on PyTorch 2.11 + CUDA 12.8 + Python 3.12:- This GPU image has no
nvccand PyPI has noflash-attnwheel fortorch2.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.
- This GPU image has no
- 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.
- Step 1 will sit in Inductor GEMM autotuning for
- Do NOT run a separate synthetic 5-step compile probe before training if you already know
B=64Γ1fits:- 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.
- We already proved
- Non-zero-init architecture changes mid-run cause 1-step spikes:
- Changing
ContinuousLoopCondfreqs(16Ο β 2Ο) at Step 5,000 caused a 1-step transient (LML=43.5at Step 5,001, recovered in <60 steps). By contrast, zero-initializingEngram Conv1dat 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.
- Changing
HF_HUB_ENABLE_HF_TRANSFERis deprecated inhuggingface_hub >= 2.4:- Use
HF_XET_HIGH_PERFORMANCE=1instead β it achieves ~100 MB/s+ (33.3 GiB uploaded in ~3 minutes).
- Use
- 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-secondsto(remaining_gpu_seconds - 1500).
- Final validation + checkpoint save takes ~45s; uploading 33.3 GiB to HF takes ~3β4 minutes. Set
- Never write
HF_TOKENinto 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 storeHF_TOKENas an environment secret (e.g., via Qualia Secrets /request_secret) so scripts reados.environ["HF_TOKEN"]without exposing it in logs. Rotate any token that was previously pasted in chat or shell commands.
- Passing
- Always use
PYTHONPATH=.(orPYTHONPATH=codeif running from a fresh HF snapshot) sotrain_stage1_cortex.pycan importtrain_a100_wikipedia,a100_opt_patches, andstage1_dataloader. - Watch
TotLvsLMLwhen reading logs:TotLincludes0.25*ECHO + 0.15*r_mid + 0.25*mono_hinge + aux. CompareLML(notTotL) 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,522will take10β13 minutes on a fresh node (one-time335β350k tok/s`** (~0.76s/step).torch.compileautotune), then steady-state runs at **` - Step
15,522resumes 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/cortex_ckpts/latest`.--max-wall-secondsinto `
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 FiLM2Ο + 0.25*tanh, Engram causalDepthwiseConv1d+SiLU, exact 10.00L / TBPTT=2 schedule, per-dataset token tracking, and native.safetensorscheckpointing & resume.scripts/upload_to_hf.pyβ ParallelHF_XET_HIGH_PERFORMANCE=1uploader for.safetensorscheckpoints, tokenizer,AGENTS.md, manifest, logs, and code.scripts/convert_ckpt_to_safetensors.pyβ Utility that converted legacy.ptcheckpoints 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.8263Btokens seen (7.1%of Stage 1's 110B). Checkpoint incheckpoint/lateston HF is a consistent 4-rank step-29,855 save. Throughput~335-345k tok/s,--max-wall-seconds 10800stopped cleanly. - Held-out FineWeb-Edu val loss at step 29,855: 8L
2.983, 16L2.966, 24L3.363(unseen), 32L4.699(unseen), 40L4.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 checkingContinuousLoopCond/ contraction regularization and keep monitoringhigh/xhigh/maxevals 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 forcpto finish) so a later save into--ckpt-rootcannot 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 withCommitOperationCopy(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 Nmirrors validation rows intocortex-stage1-eval.