Download code/upload_to_hf.py from Cortex-Intelligence/Cortex-OSS-Flash-1.0: direct link, hf CLI and curl.
- Browser
- Download file 7.5 kB
-
https://huggingface.co/Cortex-Intelligence/Cortex-OSS-Flash-1.0/resolve/f1bde010ca1c757d083cd13614ce04448bc5d142/code/upload_to_hf.py
- Command line
-
hf download hf://Cortex-Intelligence/Cortex-OSS-Flash-1.0@f1bde010ca1c757d083cd13614ce04448bc5d142/code/upload_to_hf.py
-
curl -L -o upload_to_hf.py https://huggingface.co/Cortex-Intelligence/Cortex-OSS-Flash-1.0/resolve/f1bde010ca1c757d083cd13614ce04448bc5d142/code/upload_to_hf.py
7.5 kB
| """Upload pure .safetensors Cortex-OSS-Flash-1.0 Stage 1 checkpoint, tokenizer, AGENTS.md & scripts to HF Hub.""" | |
| import argparse | |
| import json | |
| import os | |
| import time | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| from huggingface_hub import HfApi | |
| 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, default=os.path.expanduser("~/cortex_ckpts/latest_safetensors")) | |
| 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") | |
| p.add_argument("--prune-legacy-pt", action="store_true", help="Remove old checkpoint/latest/rank-*.pt on HF after upload") | |
| args = p.parse_args() | |
| os.environ["HF_XET_HIGH_PERFORMANCE"] = "1" | |
| token = os.environ.get("HF_TOKEN") | |
| if not token: | |
| raise RuntimeError("HF_TOKEN environment variable must be set") | |
| api = HfApi(token=token) | |
| t0 = time.perf_counter() | |
| state_path = os.path.join(args.ckpt_dir, "train_state.json") | |
| state = {} | |
| if os.path.exists(state_path): | |
| with open(state_path, "r", encoding="utf-8") as f: | |
| state = json.load(f) | |
| step = state.get("step", "unknown") | |
| 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)" | |
| uploads = [] | |
| # 1. Tokenizer files at repo root + tokenizer/ | |
| for fn in ("tokenizer.json", "tokenizer_config.json", "special_tokens_map.json"): | |
| lp = os.path.join(args.tokenizer_dir, fn) | |
| if os.path.exists(lp): | |
| uploads.append((lp, fn)) | |
| uploads.append((lp, f"tokenizer/{fn}")) | |
| # 2. Dense model.safetensors at repo root + checkpoint/latest/ | |
| model_st = os.path.join(args.ckpt_dir, "model.safetensors") | |
| if os.path.exists(model_st): | |
| uploads.append((model_st, "model.safetensors")) | |
| uploads.append((model_st, "checkpoint/latest/model.safetensors")) | |
| # 3. Code, AGENTS.md, manifest, and training logs | |
| for lp, rp in [ | |
| ("AGENTS.md", "AGENTS.md"), | |
| (args.manifest, "data_manifests/stage1_manifest.json"), | |
| (args.metrics_jsonl, "logs/stage1_metrics.jsonl"), | |
| ("train_a100_wikipedia.py", "code/train_a100_wikipedia.py"), | |
| ("a100_opt_patches.py", "code/a100_opt_patches.py"), | |
| ("stage1_dataloader.py", "code/stage1_dataloader.py"), | |
| ("train_stage1_cortex.py", "code/train_stage1_cortex.py"), | |
| ("scripts/upload_to_hf.py", "code/upload_to_hf.py"), | |
| ]: | |
| if os.path.exists(lp): | |
| uploads.append((lp, rp)) | |
| # 4. Pure .safetensors + JSON sharded checkpoint | |
| if os.path.exists(state_path): | |
| uploads.append((state_path, "checkpoint/latest/train_state.json")) | |
| for r in range(4): | |
| st_local = os.path.join(args.ckpt_dir, f"rank-{r}.safetensors") | |
| meta_local = os.path.join(args.ckpt_dir, f"rank-{r}_meta.json") | |
| if os.path.exists(st_local): | |
| uploads.append((st_local, f"checkpoint/latest/rank-{r}.safetensors")) | |
| if os.path.exists(meta_local): | |
| uploads.append((meta_local, f"checkpoint/latest/rank-{r}_meta.json")) | |
| 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, Session 1 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", {}))}` | |
| ## Exact Resume Command (4× A100-80GB) | |
| ```bash | |
| PYTHONPATH=code torchrun --nproc_per_node=4 code/train_stage1_cortex.py \\ | |
| --manifest data_manifests/stage1_manifest.json \\ | |
| --tokenizer-path tokenizer/tokenizer.json \\ | |
| --resume-dir checkpoint/latest \\ | |
| --micro-batch-size {state.get("micro_batch_size", 64)} \\ | |
| --grad-accum {state.get("grad_accum", 1)} \\ | |
| --seq-len {state.get("seq_len", 1024)} \\ | |
| --enable-fim --fim-rate-code 0.50 --fim-rate-other 0.10 | |
| ``` | |
| """ | |
| readme_local = os.path.join(args.ckpt_dir, "README_upload.md") | |
| with open(readme_local, "w", encoding="utf-8") as f: | |
| f.write(readme_text) | |
| uploads.append((readme_local, "README.md")) | |
| print(f"Uploading {len(uploads)} files (pure .safetensors + JSON) to {args.repo_id} (step={step})...", flush=True) | |
| small_files = [(l, r) for l, r in uploads if not r.endswith(".safetensors") or os.path.getsize(l) < 500 * 1024 * 1024] | |
| large_files = [(l, r) for l, r in uploads if r.endswith(".safetensors") and os.path.getsize(l) >= 500 * 1024 * 1024] | |
| for lp, rp in small_files: | |
| api.upload_file( | |
| path_or_fileobj=lp, | |
| path_in_repo=rp, | |
| repo_id=args.repo_id, | |
| repo_type="model", | |
| commit_message=f"Stage 1 safetensors step {step}: {rp}", | |
| ) | |
| print(f" [OK] {rp}", flush=True) | |
| def _upload_large(item): | |
| lp, rp = item | |
| sz_gb = os.path.getsize(lp) / (1024 ** 3) | |
| t1 = time.perf_counter() | |
| api.upload_file( | |
| path_or_fileobj=lp, | |
| path_in_repo=rp, | |
| repo_id=args.repo_id, | |
| repo_type="model", | |
| commit_message=f"Stage 1 safetensors step {step}: {rp}", | |
| ) | |
| return rp, sz_gb, time.perf_counter() - t1 | |
| with ThreadPoolExecutor(max_workers=2) as pool: | |
| futs = [pool.submit(_upload_large, item) for item in large_files] | |
| for fut in as_completed(futs): | |
| rp, sz_gb, dt = fut.result() | |
| print(f" [OK] {rp} ({sz_gb:.2f} GiB in {dt:.1f}s, {sz_gb*8/max(dt,1e-3):.2f} Gbps)", flush=True) | |
| if args.prune_legacy_pt: | |
| existing = set(api.list_repo_files(args.repo_id, repo_type="model")) | |
| for r in range(4): | |
| old_pt = f"checkpoint/latest/rank-{r}.pt" | |
| if old_pt in existing: | |
| api.delete_file( | |
| path_in_repo=old_pt, | |
| repo_id=args.repo_id, | |
| repo_type="model", | |
| commit_message=f"Remove legacy pickle {old_pt} (replaced by .safetensors)", | |
| ) | |
| print(f" [DEL] {old_pt}", flush=True) | |
| print(f"All safetensors uploads to {args.repo_id} completed in {time.perf_counter() - t0:.1f}s!", flush=True) | |
| if __name__ == "__main__": | |
| main() | |