Cortex-OSS-Flash-1.0 / code /upload_to_hf_atomic.py
Cortex-Intelligence's picture
Stage 1 atomic safetensors checkpoint: step 30000 (7.8643B tokens)
e3bed1e verified
Raw History Blame Contribute Delete
7.5 kB
"""Atomic uploader for Cortex-OSS-Flash-1.0 Stage 1 pure-.safetensors checkpoints.
Uses HfApi.create_commit so all 4 rank shards, model.safetensors, metadata,
train_state.json, logs, and docs land in a single atomic commit on HF Hub.
"""
import argparse
import json
import os
import time
from huggingface_hub import CommitOperationAdd, HfApi
def verify_ckpt_dir(ckpt_dir: str) -> dict:
state_path = os.path.join(ckpt_dir, "train_state.json")
if not os.path.exists(state_path):
raise FileNotFoundError(f"Missing {state_path}")
with open(state_path, "r", encoding="utf-8") as f:
state = json.load(f)
step = int(state["step"])
world_size = int(state.get("world_size", 4))
model_st = os.path.join(ckpt_dir, "model.safetensors")
if not os.path.exists(model_st) or os.path.getsize(model_st) < 100 * 1024 * 1024:
raise RuntimeError(f"Invalid or missing {model_st}")
for r in range(world_size):
st_p = os.path.join(ckpt_dir, f"rank-{r}.safetensors")
meta_p = os.path.join(ckpt_dir, f"rank-{r}_meta.json")
if not os.path.exists(st_p) or os.path.getsize(st_p) < 1024 ** 3:
raise RuntimeError(f"Invalid or missing {st_p}")
if not os.path.exists(meta_p):
raise RuntimeError(f"Missing {meta_p}")
with open(meta_p, "r", encoding="utf-8") as mf:
m = json.load(mf)
if int(m.get("step", -1)) != step:
raise RuntimeError(
f"Step mismatch in {meta_p}: expected {step}, got {m.get('step')}"
)
return state
def get_token() -> str:
tok = os.environ.get("HF_TOKEN")
if tok:
return tok.strip()
cache_path = os.path.expanduser("~/.cache/huggingface/token")
if os.path.exists(cache_path):
with open(cache_path, "r", encoding="utf-8") as f:
tok = f.read().strip()
if tok:
return tok
raise RuntimeError("HF_TOKEN not found in environment or ~/.cache/huggingface/token")
def upload_checkpoint_atomic(
repo_id: str,
ckpt_dir: str,
tokenizer_dir: str = "tokenizer",
manifest: str = "data_manifests/stage1_manifest.json",
metrics_jsonl: str = "logs/stage1_metrics.jsonl",
include_code: bool = True,
) -> dict:
os.environ["HF_XET_HIGH_PERFORMANCE"] = "1"
token = get_token()
state = verify_ckpt_dir(ckpt_dir)
step = int(state["step"])
tokens_b = state.get("tokens_seen", 0) / 1e9
toks_src = state.get("tokens_by_source", {})
toks_src_lines = (
"\n".join(f" - `{k}`: {v:,d} tokens ({v/1e9:.4f}B)" for k, v in toks_src.items())
if toks_src
else " - (not recorded)"
)
ops = []
# Dense model.safetensors at repo root and checkpoint/latest/
model_st = os.path.join(ckpt_dir, "model.safetensors")
ops.append(CommitOperationAdd(path_in_repo="model.safetensors", path_or_fileobj=model_st))
ops.append(CommitOperationAdd(path_in_repo="checkpoint/latest/model.safetensors", path_or_fileobj=model_st))
# Sharded rank files + metadata + train_state.json
state_path = os.path.join(ckpt_dir, "train_state.json")
ops.append(CommitOperationAdd(path_in_repo="checkpoint/latest/train_state.json", path_or_fileobj=state_path))
for r in range(int(state.get("world_size", 4))):
ops.append(CommitOperationAdd(
path_in_repo=f"checkpoint/latest/rank-{r}.safetensors",
path_or_fileobj=os.path.join(ckpt_dir, f"rank-{r}.safetensors"),
))
ops.append(CommitOperationAdd(
path_in_repo=f"checkpoint/latest/rank-{r}_meta.json",
path_or_fileobj=os.path.join(ckpt_dir, f"rank-{r}_meta.json"),
))
# Docs, logs, manifest, code
extra_files = [
("AGENTS.md", "AGENTS.md"),
(manifest, "data_manifests/stage1_manifest.json"),
(metrics_jsonl, "logs/stage1_metrics.jsonl"),
]
if include_code:
for fn in (
"train_a100_wikipedia.py",
"a100_opt_patches.py",
"stage1_dataloader.py",
"train_stage1_cortex.py",
"upload_to_hf.py",
):
p_code = os.path.join("code", fn)
if os.path.exists(p_code):
extra_files.append((p_code, f"code/{fn}"))
elif os.path.exists(fn):
extra_files.append((fn, f"code/{fn}"))
for fn in ("upload_to_hf_atomic.py", "ckpt_watcher.py"):
p_scr = os.path.join("scripts", fn)
if os.path.exists(p_scr):
extra_files.append((p_scr, f"code/{fn}"))
for lp, rp in extra_files:
if os.path.exists(lp):
ops.append(CommitOperationAdd(path_in_repo=rp, path_or_fileobj=lp))
readme_text = f"""---
tags:
- pretraining
- safetensors
- ultramemv2
- engram
- normuon
- recurrent-depth
---
# Cortex-OSS-Flash-1.0 (Stage 1 Pretraining Checkpoint — Pure Safetensors)
Resumable 4× A100-80GB Stage 1 pretraining checkpoint stored in pure **`.safetensors` + JSON** (zero `.pt` pickle files): dense weights (`model.safetensors`), sharded NorMuon/AdamW optimizers, 4-way sharded Engram + UltraMemV2 sparse tables & Adam states (`checkpoint/latest/rank-{{0..3}}.safetensors`), routing bias/EMA, and exact per-source streaming dataset cursors (`checkpoint/latest/rank-{{0..3}}_meta.json`).
See `AGENTS.md` for complete project context, lessons learned, and the exact fast-resume playbook.
## Checkpoint Summary
- **Step**: {step}
- **Tokens seen**: {tokens_b:.4f}B / 110.0B (Stage 1)
- **Tokens seen by dataset**:
{toks_src_lines}
- **WSD LR schedule**: 2,000-step linear warmup, constant peak LR (`lr_scale = 1.0`, WSD decay NOT activated)
- **Depth & FIM**: Exact mean loop `10.00L`, `TBPTT = 2`, 50/50 PSM/SPM domain-weighted FIM (`50%` code, `10%` other), `2π + 0.25*tanh` FiLM clamp, Engram causal `DepthwiseConv1d(k=4)+SiLU`
- **Latest metrics**: `{json.dumps(state.get("latest_metrics", {}))}`
"""
ops.append(CommitOperationAdd(path_in_repo="README.md", path_or_fileobj=readme_text.encode("utf-8")))
api = HfApi(token=token)
t0 = time.perf_counter()
print(f"[HF-UPLOAD] Starting atomic commit of step {step} ({tokens_b:.4f}B tokens, {len(ops)} files) to {repo_id}...", flush=True)
commit_info = api.create_commit(
repo_id=repo_id,
repo_type="model",
operations=ops,
commit_message=f"Stage 1 atomic safetensors checkpoint: step {step} ({tokens_b:.4f}B tokens)",
)
dt = time.perf_counter() - t0
print(f"[HF-UPLOAD] Atomic commit complete for step {step} in {dt:.1f}s (oid={commit_info.oid})", flush=True)
return {"step": step, "tokens_b": tokens_b, "oid": commit_info.oid, "seconds": round(dt, 1)}
def main():
p = argparse.ArgumentParser()
p.add_argument("--repo-id", type=str, default="Cortex-Intelligence/Cortex-OSS-Flash-1.0")
p.add_argument("--ckpt-dir", type=str, required=True)
p.add_argument("--tokenizer-dir", type=str, default="tokenizer")
p.add_argument("--manifest", type=str, default="data_manifests/stage1_manifest.json")
p.add_argument("--metrics-jsonl", type=str, default="logs/stage1_metrics.jsonl")
args = p.parse_args()
res = upload_checkpoint_atomic(
repo_id=args.repo_id,
ckpt_dir=args.ckpt_dir,
tokenizer_dir=args.tokenizer_dir,
manifest=args.manifest,
metrics_jsonl=args.metrics_jsonl,
)
print(json.dumps(res, indent=2), flush=True)
if __name__ == "__main__":
main()