Orion checkpoint phase5-step-003800
Browse filesFiles changed (30)
- checkpoints/phase5-step-003800/config.jsonAdded+45
- checkpoints/phase5-step-003800/manifest.jsonAdded+404
- checkpoints/phase5-step-003800/model-0000.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0001.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0002.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0003.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0004.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0005.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0006.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0007.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0008.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0009.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0010.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0011.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0012.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0013.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0014.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0015.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0016.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0017.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0018.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0019.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0020.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0021.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0022.safetensorsAdded+3
- checkpoints/phase5-step-003800/model-0023.safetensorsAdded+3
- checkpoints/phase5-step-003800/orion_phase5_launcher.pyAdded+894
- checkpoints/phase5-step-003800/orion_unified_trainer.pyAdded
- checkpoints/phase5-step-003800/tokenizer/tokenizer.jsonAdded
- checkpoints/phase5-step-003800/tokenizer/tokenizer_config.jsonAdded+17
123456789101112131415161718192021222324252627282930313233343536373839404142434445{ "model_name": "Orion Flagship 2B T2.2", "implementation_version": 5, "architecture": "orion_flagship_2b_t2_2", "d_model": 2112, "n_layers": 24, "n_heads": 24, "n_kv_heads": 6, "rope_theta": 10000.0, "sequence_length": 32768, "tokenizer_name": "mistralai/Mistral-7B-v0.3", "n_procedure_banks": 6, "procedure_bank_span": 4, "n_experts": 12, "top_k": 1, "expert_hidden": 3456, "shared_expert_hidden": 1280, "vault_key_parts": 128, "vault_slots": 16384, "vault_top_component": 12, "vault_top_k": 4, "vault_gate_groups": 64, "vault_read_layers": [ 3, 7, 11, 15, 19, 23 ], "working_state_layers": [ 3, 7, 11, 15, 19, 23 ], "deliberation_start": 18, "deliberation_cycles": 1, "vocab_size": 32768, "rope_extension": "yarn_frequency_blend_v1", "rope_8k_frequency_preserved": true, "phase4_max_train_context": 32768}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404{ "format_version": "orion-phase5-1", "checkpoint_format": "single_gpu_sft", "model_shards": [ "model-0000.safetensors", "model-0001.safetensors", "model-0002.safetensors", "model-0003.safetensors", "model-0004.safetensors", "model-0005.safetensors", "model-0006.safetensors", "model-0007.safetensors", "model-0008.safetensors", "model-0009.safetensors", "model-0010.safetensors", "model-0011.safetensors", "model-0012.safetensors", "model-0013.safetensors", "model-0014.safetensors", "model-0015.safetensors", "model-0016.safetensors", "model-0017.safetensors", "model-0018.safetensors", "model-0019.safetensors", "model-0020.safetensors", "model-0021.safetensors", "model-0022.safetensors", "model-0023.safetensors" ], "step": 3800, "architecture": { "model_name": "Orion Flagship 2B T2.2", "implementation_version": 5, "architecture": "orion_flagship_2b_t2_2", "d_model": 2112, "n_layers": 24, "n_heads": 24, "n_kv_heads": 6, "rope_theta": 10000.0, "sequence_length": 32768, "tokenizer_name": "mistralai/Mistral-7B-v0.3", "n_procedure_banks": 6, "procedure_bank_span": 4, "n_experts": 12, "top_k": 1, "expert_hidden": 3456, "shared_expert_hidden": 1280, "vault_key_parts": 128, "vault_slots": 16384, "vault_top_component": 12, "vault_top_k": 4, "vault_gate_groups": 64, "vault_read_layers": [ 3, 7, 11, 15, 19, 23 ], "working_state_layers": [ 3, 7, 11, 15, 19, 23 ], "deliberation_start": 18, "deliberation_cycles": 1, "vocab_size": 32768, "rope_extension": "yarn_frequency_blend_v1", "rope_8k_frequency_preserved": true, "phase4_max_train_context": 32768 }, "sources": { "minicpm_agent_code": { "repo": "minicpm_agent_code", "raw_rows": 5280 }, "minicpm_agent_general": { "repo": "minicpm_agent_general", "raw_rows": 26363 }, "minicpm_agent_search": { "repo": "minicpm_agent_search", "raw_rows": 566 }, "hermes_multi": { "repo": "NousResearch/hermes-function-calling-v1", "raw_rows": 291 }, "hermes_single": { "repo": "hermes_single", "raw_rows": 251 }, "openai_schema_multi": { "repo": "openai_schema_multi", "raw_rows": 253 }, "smoltalk": { "repo": "smoltalk", "raw_rows": 443 }, "openr1_verified": { "repo": "openr1_verified", "raw_rows": 2337 }, "glm_reasoning": { "repo": "glm_reasoning", "raw_rows": 2651 }, "gptoss_reasoning": { "repo": "gptoss_reasoning", "raw_rows": 725 }, "claude_opus46_inversion": { "repo": "claude_opus46_inversion", "raw_rows": 1274 }, "claude_opus47_inversion": { "repo": "claude_opus47_inversion", "raw_rows": 1268 }, "claude_opus48_max": { "repo": "claude_opus48_max", "raw_rows": 220800 }, "high_coder": { "repo": "high_coder", "raw_rows": 378401 } }, "optimizer_saved": false, "stop_format": "User: {prompt}\nAssistant: {completion}<tokenizer.eos_token_id>", "training_stage": "phase5", "phase5_fingerprint": { "version": "orion-phase5-minicpm-agent-v1", "architecture": "orion_flagship_2b_t2_2", "identity": "Orion T2.1 2B", "phase4_parent": "checkpoints/phase4-step-000900", "steps": 5000, "lr": 8e-07, "grad_accum": 4, "max_context": 32768, "sources": { "minicpm_core": { "repo": "openbmb/UltraData-SFT-2605", "config": null, "kind": "core", "rights": "public", "weight": 1.0 }, "minicpm_agent_code": { "repo": "openbmb/UltraData-SFT-Agent-2609", "config": "Code-Agent", "kind": "agent", "rights": "public", "weight": 1.0 }, "minicpm_agent_general": { "repo": "openbmb/UltraData-SFT-Agent-2609", "config": "General-Agent", "kind": "agent", "rights": "public", "weight": 1.2 }, "minicpm_agent_search": { "repo": "openbmb/UltraData-SFT-Agent-2609", "config": "Search-Agent", "kind": "agent", "rights": "public", "weight": 0.8 }, "hermes_multi": { "repo": "NousResearch/hermes-function-calling-v1", "config": "func_calling", "kind": "agent", "rights": "public", "weight": 0.6 }, "hermes_single": { "repo": "NousResearch/hermes-function-calling-v1", "config": "func_calling_singleturn", "kind": "agent", "rights": "public", "weight": 0.35 }, "openai_schema_multi": { "repo": "stindardlogic/openai-function-calling-5k", "config": null, "kind": "agent", "rights": "public", "weight": 0.45 }, "smoltalk": { "repo": "HuggingFaceTB/smoltalk", "config": "everyday-conversations", "kind": "other", "rights": "public", "weight": 1.0 }, "openr1_verified": { "repo": "open-r1/OpenR1-Math-220k", "config": "default", "kind": "other", "rights": "public", "weight": 0.8 }, "glm_reasoning": { "repo": "Jackrong/GLM-5.1-Reasoning-1M-Cleaned", "config": "main", "kind": "other", "rights": "other", "weight": 1.5 }, "gptoss_reasoning": { "repo": "Jackrong/ShareGPT-gpt-oss-120B-reasoning", "config": null, "kind": "other", "rights": "other", "weight": 1.0 }, "claude_opus46_inversion": { "repo": "Jackrong/Claude-opus-4.6-TraceInversion-9000x", "config": null, "kind": "other", "rights": "claude", "weight": 0.7 }, "claude_opus47_inversion": { "repo": "Jackrong/Claude-opus-4.7-TraceInversion-5000x", "config": null, "kind": "other", "rights": "claude", "weight": 0.7 }, "claude_opus48_max": { "repo": "ronaldcmz/claude_opus_4.8_max_thinking_5k_v2", "config": null, "kind": "other", "rights": "claude", "weight": 0.45 }, "high_coder": { "repo": "Crownelius/High-Coder-Reasoning-Multi-Turn", "config": null, "kind": "other", "rights": "hunter", "weight": 0.8 } }, "ratios": { "minicpm_core": 0.35, "other_sft": 0.3, "agent": 0.3, "identity": 0.05 }, "quality_filter": "no-echo-no-loop-whole-target-v1" }, "phase5_parent": "checkpoints/phase4-step-000900", "phase5_source_positions": { "minicpm_agent_code": 5280, "minicpm_agent_general": 26363, "minicpm_agent_search": 566, "hermes_multi": 291, "hermes_single": 251, "openai_schema_multi": 253, "smoltalk": 443, "openr1_verified": 2337, "glm_reasoning": 2651, "gptoss_reasoning": 725, "claude_opus46_inversion": 1274, "claude_opus47_inversion": 1268, "claude_opus48_max": 220800, "high_coder": 378401 }, "phase5_source_stats": { "minicpm_agent_code": { "accepted": 297, "rejected": { "agent_schema": 3697, "holdout": 277, "agent_invalid": 1009 } }, "minicpm_agent_general": { "accepted": 814, "rejected": { "agent_schema": 23987, "holdout": 1281, "agent_invalid": 281, "whole_sample_over_context": 3 } }, "minicpm_agent_search": { "accepted": 236, "rejected": { "no_observed_tool_result": 253, "holdout": 33, "agent_invalid": 44 } }, "hermes_multi": { "accepted": 267, "rejected": { "holdout": 20, "agent_invalid": 4 } }, "hermes_single": { "accepted": 235, "rejected": { "holdout": 12, "agent_invalid": 4 } }, "openai_schema_multi": { "accepted": 240, "rejected": { "holdout": 13 } }, "smoltalk": { "accepted": 423, "rejected": { "holdout": 20 } }, "openr1_verified": { "accepted": 1369, "rejected": { "unusable_sft_row": 859, "whole_sample_over_context": 59, "holdout": 109, "prompt_echo": 1 } }, "glm_reasoning": { "accepted": 2510, "rejected": { "holdout": 134, "whole_sample_over_context": 141, "repetitive": 1, "unusable_sft_row": 7, "prompt_echo": 5 } }, "gptoss_reasoning": { "accepted": 677, "rejected": { "whole_sample_over_context": 355, "holdout": 47, "too_shallow_for_reasoning_mix": 65, "prompt_echo": 21, "generic_template": 1, "unusable_sft_row": 1 } }, "claude_opus46_inversion": { "accepted": 1201, "rejected": { "holdout": 70, "whole_sample_over_context": 5, "repetitive": 3, "unusable_sft_row": 3 } }, "claude_opus47_inversion": { "accepted": 1188, "rejected": { "holdout": 77, "prompt_echo": 1, "unusable_sft_row": 3, "repetitive": 2 } }, "claude_opus48_max": { "accepted": 0, "rejected": { "generic_template": 206095, "unusable_sft_row": 208436, "holdout": 12364, "prompt_echo": 2341 } }, "high_coder": { "accepted": 14, "rejected": { "no_visible_reasoning": 1081237, "unusable_sft_row": 360403, "too_shallow_for_reasoning_mix": 54027, "holdout": 17984, "whole_sample_over_context": 10 } } }, "identity": "Orion T2.1 2B", "created_by": "Project Prism", "source_checkpoint_repo": "Project-Prism/Orion-Flagship-2B-T2.2-Instruct-AgentML", "source_checkpoint_folder": "checkpoints/phase4-step-000900", "agent_format": "Orion AgentML: supervised tool calls, observed outputs, and final answers", "warning": "Training steps do not establish reasoning quality; run independent evaluations."}123version https://git-lfs.github.com/spec/v1oid sha256:4b01014c78774fc8d6b4041c2b7781d660ba93cf60de8af73bfa1ce8729d9cf3size 366044336123version https://git-lfs.github.com/spec/v1oid sha256:0ad67ea0481d448ee0a2cf94b7f96c78e97a6c7fbab21360fbd9db0f93c2fbfdsize 356846624123version https://git-lfs.github.com/spec/v1oid sha256:c36034ad9ac4d4875fcce38926eabae38684f3dec59ab68c9504bd7fc41c953bsize 356846656123version https://git-lfs.github.com/spec/v1oid sha256:64ddf75744bed699279d70495550bde84227e562c5743075c23c6b7408f36233size 355334276123version https://git-lfs.github.com/spec/v1oid sha256:2c9325aba8a5f10a3c10929bef6c5502605ad38581ae17dd4df99b33f329ce84size 350356824123version https://git-lfs.github.com/spec/v1oid sha256:1d5fb3b8496acb2bb11faf1e94174d3d3f1470d46226c276cd1f9dff73f284d6size 350356824123version https://git-lfs.github.com/spec/v1oid sha256:e10f32103220787b2fa13de9508a32797bb37aa9b0d9a6b54f20f85eaa35dcfcsize 353719824123version https://git-lfs.github.com/spec/v1oid sha256:3870db23004dfa962a8e1222fb802dcac8755cbbaa16f95d745b246c6fd70790size 350356824123version https://git-lfs.github.com/spec/v1oid sha256:430223b2cab68ae2bc14188aaa0dd30db3de912fa92dbc56eea4a60d0377cd92size 350356824123version https://git-lfs.github.com/spec/v1oid sha256:f85ebd6580660f91812bb86b94fefde5997fb808c941234205809ec1e79694f0size 353719824123version https://git-lfs.github.com/spec/v1oid sha256:7d1b3670fc7c8b73a51991a7a0f0658dca28254d072a1aa143624d6f13d2d663size 350356824123version https://git-lfs.github.com/spec/v1oid sha256:ee59194a44d869e6f60e56e2625e24b5e5a6e2f171ee9877636532107a0faa00size 350356824123version https://git-lfs.github.com/spec/v1oid sha256:b6ad7a638560bf15a32ce98915050efb8936185b0a4ab18750eb4c8215ddecb9size 353719824123version https://git-lfs.github.com/spec/v1oid sha256:3f22688625fa45bd49b30695b81c7967eed53198b8c15e0a57b93816a3e783e4size 350356824123version https://git-lfs.github.com/spec/v1oid sha256:6eeda1507db02a89170266fd46035e57e8f3f5c82f05bc9d66440694c57b9c6dsize 350356824123version https://git-lfs.github.com/spec/v1oid sha256:a6ec994f0fe3566b1e08251a616d4ea3fb6692337c11e154125a3226c35b5d81size 361170384123version https://git-lfs.github.com/spec/v1oid sha256:d1b7306ec9fb7b0c4e28ae8e1a285c706c6993ca65b11ef9e55bb18dff064d3esize 342906264123version https://git-lfs.github.com/spec/v1oid sha256:e7a24a6d62563cb5c9190c3a1c6f0b961533af75e96dbf636b03f2e4c34c790esize 350356824123version https://git-lfs.github.com/spec/v1oid sha256:0b9f715544a633f30335298583758791519e09eb3ba46792a1aac61adddcd2a4size 350356832123version https://git-lfs.github.com/spec/v1oid sha256:b634a027d43283b372d42afdb1767d971b3a5f830fa1c78ae13a12e177f8f1f4size 353719816123version https://git-lfs.github.com/spec/v1oid sha256:306e672f692c9d7153fcb3ef9c82682c98184f3fc6bb7e0877bf5fd98719f6ebsize 350356824123version https://git-lfs.github.com/spec/v1oid sha256:f8090f09571fd8c9c26475b734a7a386963d0c77eb13a7746167409d0ec171dfsize 350356832123version https://git-lfs.github.com/spec/v1oid sha256:3eed9cc8f1154f80b44b59bdd603de748d04d800ecc18d265449fb0664d9a0easize 355790520123version https://git-lfs.github.com/spec/v1oid sha256:aa3a14d01508716986282b1320e177ed74135803f67fe0ce0bda0407e147fdb5size 53746560123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894import marimo
__generated_with = "0.25.1"app = marimo.App(width="medium", auto_download=["html"])
@app.celldef _(): def _(): import getpass import os from huggingface_hub import login
# Prompt for the token securely hf_token = getpass.getpass("Enter your Hugging Face token: ").strip()
# Set it as an environment variable os.environ["HF_TOKEN"] = hf_token return
_() return
@app.celldef _(): #!/usr/bin/env python3 """Orion T2.1 2B / T2.2 architecture — Phase 5 SFT, MoLab single-file launcher.
Requires original Orion Phase 4 trainer in your Hugging Face repository. Uses its exact architecture, kernels, tokenizer, AgentML and safetensors format. Run MODE='selftest' then 'inspect' then 'smoke' before 'train'. Does not execute dataset tool calls. Does not train on generated hidden CoT. """ from __future__ import annotations
import ast import collections import getpass import hashlib import json import math import os import random import re import shutil import sys import statistics import time from pathlib import Path
# ============================================================================ # OPERATOR SETTINGS — EDIT HERE. Start with selftest/inspect, NOT train. # ============================================================================ class P5: MODE = 'train' # selftest | inspect | token_audit | smoke | train | rescue NAME = 'Orion T2.1 2B' CREATOR = 'Project Prism' ARCHITECTURE = 'orion_flagship_2b_t2_2' SOURCE_REPO = 'Project-Prism/Orion-Flagship-2B-T2.2-Instruct-AgentML' UPLOAD_REPO = SOURCE_REPO SOURCE_TRAINER = 'checkpoints/phase4-step-000850/orion_unified_trainer.py' TRAINER_REVISION = 'main' # Pin to a trusted commit SHA for reproducibility. REQUIRE_PHASE4_COMPLETE = True # Refuse to train from step <900. WORK_DIR = './orion_phase5_work' STEPS = 5000 GRAD_ACCUM = 4 LEARNING_RATE = 8e-7 SAVE_EVERY = 100 LOG_EVERY = 10 EVAL_EVERY = 100 SEED = 520261011 KEEP_LOCAL = 2 MAX_CONTEXT = 32768 MIN_CONTEXT = 8192 MAX_SOURCE_SCAN = 300 REQUIRE_HUB_UPLOAD = True SAVE_OPTIMIZER = False # True is large; false resets AdamW on resume. # Real MiniCPM5 core SFT is gated. Request access on HF first. REQUIRE_MINICPM_CORE = False REQUIRE_MINICPM_AGENT = True # Only turn on if YOU have checked upstream provider training rights. ALLOW_OTHER_TEACHER_DATA = True ALLOW_CLAUDE_TEACHER_DATA = True # TRAINING gate: require actual permission first. PREVIEW_CLAUDE_SOURCES = True # Default ON for inspect/token_audit only; NEVER for training. TOKEN_AUDIT_ROWS = 30 # Accepted samples per dataset; change to 100+ for better estimates. ALLOW_HUNTER_TEACHER_DATA = True # Core reasoning 35%, other reasoning/chat 30%, real agent 30%, identity 5%. # When gated core unavailable, its share is reassigned to other chat/reasoning. RATIOS = dict(minicpm_core=.35, other_sft=.30, agent=.30, identity=.05)
SOURCE_SPECS = { 'minicpm_core': dict(repo='openbmb/UltraData-SFT-2605', config=None, kind='core', rights='public', weight=1.0), 'minicpm_agent_code': dict(repo='openbmb/UltraData-SFT-Agent-2609', config='Code-Agent', kind='agent', rights='public', weight=1.0), 'minicpm_agent_general': dict(repo='openbmb/UltraData-SFT-Agent-2609', config='General-Agent', kind='agent', rights='public', weight=1.2), 'minicpm_agent_search': dict(repo='openbmb/UltraData-SFT-Agent-2609', config='Search-Agent', kind='agent', rights='public', weight=.8), 'hermes_multi': dict(repo='NousResearch/hermes-function-calling-v1', config='func_calling', kind='agent', rights='public', weight=.6), 'hermes_single': dict(repo='NousResearch/hermes-function-calling-v1', config='func_calling_singleturn', kind='agent', rights='public', weight=.35), 'openai_schema_multi': dict(repo='stindardlogic/openai-function-calling-5k', config=None, kind='agent', rights='public', weight=.45), 'smoltalk': dict(repo='HuggingFaceTB/smoltalk', config='everyday-conversations', kind='other', rights='public', weight=1.0), 'openr1_verified': dict(repo='open-r1/OpenR1-Math-220k', config='default', kind='other', rights='public', weight=0.8), 'glm_reasoning': dict(repo='Jackrong/GLM-5.1-Reasoning-1M-Cleaned', config='main', kind='other', rights='other', weight=1.5), 'gptoss_reasoning': dict(repo='Jackrong/ShareGPT-gpt-oss-120B-reasoning', config=None, kind='other', rights='other', weight=1.0), 'claude_opus46_inversion': dict(repo='Jackrong/Claude-opus-4.6-TraceInversion-9000x', config=None, kind='other', rights='claude', weight=.7), 'claude_opus47_inversion': dict(repo='Jackrong/Claude-opus-4.7-TraceInversion-5000x', config=None, kind='other', rights='claude', weight=.7), 'claude_opus48_max': dict(repo='ronaldcmz/claude_opus_4.8_max_thinking_5k_v2', config=None, kind='other', rights='claude', weight=.45), 'high_coder': dict(repo='Crownelius/High-Coder-Reasoning-Multi-Turn', config=None, kind='other', rights='hunter', weight=.8), }
# Hand-written, correct, non-repetitive identity + multi-turn examples. IDENTITY = [ ('Who are you?', 'I am Orion T2.1 2B, an experimental AI assistant built by Project Prism.'), ('What is your name?', 'My name is Orion T2.1 2B. You can call me Orion.'), ('Who made you?', 'Project Prism built me.'), ('Are you Claude or ChatGPT?', 'No. I am Orion T2.1 2B, a separate experimental model.'), ('How many parameters do you have?', 'About 2 billion parameters.'), ('What architecture are you?', 'My architecture is Orion Flagship 2B T2.2; my assistant name is Orion T2.1 2B.'), ('What is Super Mega Ultra Extreem?', 'It is my largest reasoning-effort setting, not a promise of correctness.'), ('Do you have to use all your thinking tokens?', 'No. I should stop reasoning once I have a sound answer.'), ('Hi', 'Hey! I am Orion. What can I help you with?'), ('Should you open test.py when someone says hello?', 'No. A greeting needs no tools.'), ('My favourite food is spaghetti. What is MY favourite food?', 'Your favourite food is spaghetti.'), ('I am worried you will make a mistake.', 'I can make mistakes. I will try to be clear and admit uncertainty.'), ] MEMORY_CASES = [ (['My favourite colour is purple.', 'What is my favourite colour?'], 'Your favourite colour is purple.'), (['My favourite food is spaghetti.', 'What is my favourite food?'], 'Your favourite food is spaghetti.'), (['Your name is Orion. My name is Alex.', 'Who is Alex?'], 'Alex is the user, not me.'), (['Remember: my pet is a cat named Pixel.', 'What is my cat called?'], 'Your cat is called Pixel.'), ] # Small held-out diagnostic cases. These evaluate loss, NOT proof of reasoning. EVAL_CASES = [ ('A checkpoint is missing weight shards despite a success log. What should you do?', 'Do not load it. Verify the manifest and every shard, restore the last complete checkpoint, and use atomic saving with post-upload checks.'), ('All but nine sheep run away. How many remain?', 'Nine remain. "All but nine" means nine did not run away.'), ('What is 12 - 5 + 3?', '10. Subtract five from twelve to get seven, then add three.'), ('Should you use a file tool just to answer hello?', 'No. Say hello without opening any files.'), ]
def digest(obj): return hashlib.sha256(json.dumps(obj, sort_keys=True, default=str, ensure_ascii=False).encode()).hexdigest()
def quality_check(question, answer, reason='', require_substance=True): """Cheap conservative filters, not an accuracy oracle.""" if not isinstance(question, str) or not isinstance(answer, str): return 'non_string' q, a = question.strip(), answer.strip() if not q or not a or len(q) > 200000 or len(a) > 200000: return 'empty_or_huge' if a.casefold() == q.casefold() or (len(a) > 100 and q[:120].casefold() in a[:180].casefold()): return 'prompt_echo' if re.search(r'(?i)(?:i will deliver a structured|concrete next steps|analysis & recommendations)', a): return 'generic_template' # Detect repeated 6-word windows dominating an answer or a reasoning trace. for text in (a, reason): words = re.findall(r'\w+', text.casefold()) if len(words) >= 65: sixes = collections.Counter(tuple(words[i:i+6]) for i in range(len(words)-5)) if sixes and sixes.most_common(1)[0][1] >= max(6, len(words)//15): return 'repetitive' if require_substance and len(a) < 55 and len(reason) < 100: return 'too_shallow_for_reasoning_mix' if re.search(r"(?i)\b(i am|i'm|my name is)\s+(claude|chatgpt|gpt-oss|glm)", a[:200]): return 'wrong_identity' return None
def load_orion_runtime(): """Reuse the exact original 373-tensor trainer, without marimo UI startup.""" from huggingface_hub import hf_hub_download path = hf_hub_download(repo_id=P5.SOURCE_REPO, filename=P5.SOURCE_TRAINER, revision=P5.TRAINER_REVISION, token=os.environ.get('HF_TOKEN')) source = Path(path).read_text(encoding='utf-8') parsed = ast.parse(source) cells = [n for n in ast.walk(parsed) if isinstance(n, ast.FunctionDef) and n.name == '_' and any(isinstance(x, ast.ClassDef) and x.name == 'SFTConfig' for x in n.body)] if len(cells) != 1: raise RuntimeError('Upstream trainer changed: cannot identify unique Orion SFT cell.') cell = cells[0] # Remove marimo-specific return and the old Phase4 entrypoint. body = [n for n in cell.body if not isinstance(n, ast.Return) and not ( isinstance(n, ast.If) and isinstance(n.test, ast.Compare) and isinstance(n.test.left, ast.Name) and n.test.left.id == '__name__')] tree = ast.fix_missing_locations(ast.Module(body=body, type_ignores=[])) ns = {'__name__': 'orion_phase5_runtime', '__file__': str(path)} exec(compile(tree, str(path), 'exec'), ns) if ns.get('P4_MODEL_ID') != P5.ARCHITECTURE or ns.get('P4_IDENTITY_NAME') != P5.NAME: raise RuntimeError('Upstream architecture or Orion identity changed; review before training.') for key in ('build_model', 'restore_model_shards', 'p3_hub_restore', 'save_checkpoint', 'p4_pack', 'parse_openai_dialogue', 'event_samples'): if key not in ns: raise RuntimeError('Upstream Orion trainer is missing '+key) ns['CHECKPOINT_FORMATS'] += ('orion-phase5-1',) ns['SFTConfig'].max_target_tokens = 32768 ns['SFTConfig'].max_prompt_tokens = 32768 ns['SFTConfig'].phase4_max_context = P5.MAX_CONTEXT ns['P4_IDENTITY_NAME'] = P5.NAME # Agent samples must also learn their identity; tools are contextual, not a command. old_formatter = ns['format_context'] def with_identity(tools, events, closing_assistant=True): s = old_formatter(tools, events, closing_assistant=closing_assistant) return s.replace(ns['AGENTML_HEADER'], ns['AGENTML_HEADER'] + '\n' + 'You are Orion T2.1 2B, built by Project Prism. Use tools only when needed. ' 'Never invent tool observations.\n', 1) ns['format_context'] = with_identity return ns
def allowed(spec): rights = spec['rights'] return rights == 'public' or (rights == 'other' and P5.ALLOW_OTHER_TEACHER_DATA) or ( rights == 'claude' and P5.ALLOW_CLAUDE_TEACHER_DATA) or ( rights == 'hunter' and P5.ALLOW_HUNTER_TEACHER_DATA)
def mini_agent_row(row, ns): """Normalize MiniCPM messages for Orion; NEVER train on foreign system prompts.
Keep original user/assistant/tool chronology, real observations and tool-call arguments. The existing Orion parsers decide whether an example is valid. """ original = ns['parse_json'](row.get('messages')) if not isinstance(original, list): return None clean = [] for m in original: if not isinstance(m, dict): continue role = str(m.get('role','')).lower() if role in ('system', 'developer'): continue # Includes "You are Codex" / OpenClaw behavioural instructions. if role not in ('user', 'human', 'assistant', 'tool', 'function'): continue m = dict(m) if role == 'human': m['role'] = 'user' if role == 'function': m['role'] = 'tool' clean.append(m) if not clean or not any(m['role']=='user' for m in clean): return None tools = ns['parse_json'](row.get('tools')) if not isinstance(tools, list): tools = [] return {'messages':clean, 'tools':tools}
def parse_minicpm_agent(row, ns): """Try native Orion parser then its schema-inference SWE-style fallback.""" clean = mini_agent_row(row, ns) if clean is None: return None # Different loaders accept different row shapes; do not invent tool results. swe_row = {'messages': json.dumps(clean['messages'], ensure_ascii=False), 'model': 'orion_source_adapter', 'resolved': True} parsers = (lambda:ns['parse_openai_dialogue'](clean), lambda:ns['parse_source_row']('swesmith_claude', clean), lambda:ns['parse_source_row']('swesmith_claude', swe_row)) for parser in parsers: try: parsed = parser() if parsed is not None and len(parsed)==3: return parsed except (TypeError, ValueError, KeyError, AttributeError): continue return None
def minicpm_code_features(ds): """Add the optional positional tool field found in Code-Agent Parquet shards.
Some shards contain this field while the repository's inferred Features omit it, producing the observed Arrow cast error on iteration. """ import copy from datasets import Value, List features = copy.deepcopy(ds.features) if features is None or 'tools' not in features: return None tool_feature = features['tools'] entry = getattr(tool_feature,'feature',None) if isinstance(entry,dict) and 'positional' not in entry: entry['positional'] = List(Value('string')) return features return None
def minicpm_general_chat(row, ns): """Strict text-only General-Agent fallback; no pretending to have tools.""" clean = mini_agent_row(row, ns) if clean is None: return None messages = clean['messages'] # A transcript that ever uses tools MUST go through the AgentML parser. if any(m.get('role') == 'tool' or m.get('tool_calls') or m.get('recipient') or m.get('function_call') for m in messages): return None # Only accept an actual assistant final following a real user request. history, answer, reason = [], None, '' for m in messages: role = m.get('role') body = m.get('content', '') if isinstance(body, list): body = '\n'.join(str(x.get('text', '')) for x in body if isinstance(x, dict)) if not isinstance(body, str): return None if role == 'user' and body.strip(): history.append({'role': 'user', 'content': body.strip()}) answer = None elif role == 'assistant' and history and body.strip(): answer = body.strip() reason = str(m.get('reasoning_content') or m.get('thinking') or '') history.append({'role': 'assistant', 'content': answer}) if not answer or not history or history[-1]['role'] != 'assistant': return None q = next((m['content'] for m in reversed(history[:-1]) if m['role']=='user'), '') if quality_check(q, answer, reason, require_substance=False): return None return {'history': history[:-1], 'answer': answer, 'reason': reason, 'source': 'minicpm_agent_general_chat'}
class SourceStream: def __init__(self, key, ns, offset=0): self.key, self.ns = key, ns self.spec = SOURCE_SPECS[key] self.seed = P5.SEED + sum(map(ord, key)) self.raw_rows = 0 self.accepted = 0 self.rejected = collections.Counter() self.pending = [] self.open() if offset: print(f'↩️ Replaying {offset} rows from {key} for approximate resume', flush=True) for _ in range(offset): self.raw()
def open(self): args = dict(path=self.spec['repo'], name=self.spec['config'], split='train', streaming=True, token=os.environ.get('HF_TOKEN')) ds = self.ns['load_dataset'](**args) if self.key == 'minicpm_agent_code': revised = minicpm_code_features(ds) if revised is not None: # Re-open with the complete nested schema BEFORE streaming rows. # A cast after loading can fail before it has a chance to map. try: ds = self.ns['load_dataset'](**dict(args,features=revised)) print('🛠️ Code-Agent: positional tool schema included',flush=True) except (TypeError, ValueError) as exc: print('⚠️ Code-Agent schema override unavailable:',exc,flush=True) self.iterator = iter(ds.shuffle(seed=self.seed, buffer_size=128)) print(f'📚 {self.key}: {self.spec["repo"]} / {self.spec["config"]}', flush=True)
def raw(self): try: row = next(self.iterator) except StopIteration: self.seed += 1 self.open() row = next(self.iterator) self.raw_rows += 1 return row
def next_case(self, tokenizer=None): """Return one actual, filtered case; never synthesize missing answers.""" ns = self.ns if self.pending: return self.pending.pop(0) for _ in range(P5.MAX_SOURCE_SCAN): row = self.raw() # Stable 5% holdout partition. No holdout samples are used for training. if int(digest(row)[:8], 16) % 20 == 0: self.rejected['holdout'] += 1 continue if self.spec['kind'] == 'agent': # Actual MiniCPM5 tool schema: messages + tools, often JSON cells. row = dict(row) row['messages'] = ns['parse_json'](row.get('messages')) row['tools'] = ns['parse_json'](row.get('tools')) if self.key == 'hermes_multi': parsed = ns['parse_source_row']('hermes_multi', row) elif self.key == 'hermes_single': parsed = ns['parse_source_row']('hermes', row) elif self.key == 'openai_schema_multi': parsed = ns['parse_source_row']('openai_multiturn', row) else: parsed = parse_minicpm_agent(row, ns) if parsed is None: # General-Agent includes both pure chat and tool tasks. Keep # genuine text-only responses as CHAT, not fabricated agent # examples. Reject partially observed tool conversations. if self.key == 'minicpm_agent_general': fallback = minicpm_general_chat(row, ns) if fallback is not None: self.accepted += 1 return 'chat', fallback self.rejected['agent_schema'] += 1 continue tools, events, _ = parsed if ns['validate_events'](tools, events): self.rejected['agent_invalid'] += 1 continue if not any(e['role'] == 'observation' for e in events): # Single-turn Hermes examples teach *requesting* tools. They # have no results by design; never fabricate observations. if self.key != 'hermes_single': self.rejected['no_observed_tool_result'] += 1 continue samples = ns['event_samples'](tools, events, tokenizer=tokenizer) if not samples: self.rejected['no_supervised_actions'] += 1 continue # Prefer an action or final answer AFTER a real tool observation. samples.sort(key=lambda s: ('<|observation|>' in s[0], s[2]), reverse=True) self.accepted += 1 self.pending = [('agent', x) for x in samples[1:4]] return 'agent', samples[0] # Reuse Orion's existing multi-turn and <think> adapters. adapter = self.key if self.key in ns['P4_DATA'] else 'smoltalk_everyday' if self.key == 'claude_opus46_inversion': adapter = 'opus46_inversion' if self.key == 'claude_opus47_inversion': adapter = 'opus47_inversion' if self.key == 'claude_opus48_max': adapter = 'opus48_max' if self.key == 'glm_reasoning': adapter = 'glm51_cleaned' if self.key == 'gptoss_reasoning': adapter = 'gptoss_sharegpt' if self.key == 'smoltalk': adapter = 'smoltalk_everyday' if self.key == 'openr1_verified': parsed = ns['p3_parse_openr1'](row) cases = ([dict(history=[dict(role='user',content=parsed['question'])], answer=parsed['answer'],reason=parsed['rationale'],source=self.key)] if parsed else []) else: cases = ns['p4_training_cases'](adapter, row) good = [] for c in cases: q = next((t['content'] for t in reversed(c['history']) if t['role'] == 'user'), '') reason = c.get('reason', '') issue = quality_check(q, c['answer'], reason, require_substance=(self.key != 'smoltalk')) if issue: self.rejected[issue] += 1 continue if not reason and self.key not in ('smoltalk',): # A long final answer is valid, but don't label it as a hidden trace. self.rejected['no_visible_reasoning'] += 1 continue good.append(c) if good: self.accepted += 1 self.pending = [('chat', c) for c in good[1:5]] return 'chat', good[0] self.rejected['unusable_sft_row'] += 1 raise RuntimeError(f'{self.key}: no usable samples in {P5.MAX_SOURCE_SCAN} rows; ' f'counts={dict(self.rejected)}. Inspect schema/permissions.')
def identity_case(ns, rng): if rng.random() < .65: q, a = rng.choice(IDENTITY) history = [{'role':'user', 'content':q}] else: turns, a = rng.choice(MEMORY_CASES) history = [{'role':'user','content':turns[0]}, {'role':'assistant','answer':'Got it.','reason':''}, {'role':'user','content':turns[1]}] return dict(history=history, answer=a, reason='', effort='Instant', source='identity')
def pack_case(ns, category, value, tokenizer, cap, rng): if category == 'agent': prompt, target, final = value # Context may be too large; skip whole examples rather than truncating. ns['ACTIVE_CONTEXT_LIMIT'] = cap sample = ns['agent_tensors']((prompt, target, final), tokenizer) return sample if category == 'identity': value = identity_case(ns, rng) reason = value.get('reason', '') effort = value.get('effort') or (rng.choice(['High','Xhigh','Max']) if len(reason) > 400 else rng.choice(['Low','Medium']) if reason else 'Instant') sample, _ = ns['p4_pack'](value, tokenizer, effort, cap) return sample
def cap_for_step(step): f = step / P5.STEPS return 8192 if f < .20 else 16384 if f < .55 else 32768
def fp(source_folder): return dict(version='orion-phase5-minicpm-agent-v1', architecture=P5.ARCHITECTURE, identity=P5.NAME, phase4_parent=source_folder, steps=P5.STEPS, lr=P5.LEARNING_RATE, grad_accum=P5.GRAD_ACCUM, max_context=P5.MAX_CONTEXT, sources={k:SOURCE_SPECS[k] for k in SOURCE_SPECS if allowed(SOURCE_SPECS[k])}, ratios=P5.RATIOS, quality_filter='no-echo-no-loop-whole-target-v1')
def latest_remote(ns, prefix): files = ns['HfApi'](token=os.environ.get('HF_TOKEN')).list_repo_files( repo_id=P5.SOURCE_REPO, repo_type='model') hits = [] for f in files: m = re.fullmatch(r'checkpoints/' + re.escape(prefix) + r'-step-(\d{6})/manifest\.json', f) if m: hits.append((int(m.group(1)), f.rsplit('/', 1)[0])) return sorted(hits, reverse=True)
def pick_checkpoint(ns, work): local = [] for d in work.glob('phase5-step-*'): try: mf = ns['check_checkpoint_folder'](d, ('orion-phase5-1',)) if mf.get('phase5_fingerprint') == fp(mf['phase5_parent']): local.append((int(mf['step']), d, mf)) except (ValueError, KeyError, OSError): pass best = max(local, key=lambda x:x[0]) if local else None for step, rel in latest_remote(ns, 'phase5'): if best and step <= best[0]: break try: path = ns['hf_hub_download'](repo_id=P5.SOURCE_REPO, filename=rel+'/manifest.json', token=os.environ.get('HF_TOKEN')) meta = json.loads(Path(path).read_text()) if meta.get('phase5_fingerprint') != fp(meta.get('phase5_parent')): print('⚠️ Skipping incompatible Phase5 checkpoint', rel, flush=True) continue folder, mf = ns['p3_hub_restore'](P5.SOURCE_REPO, rel, work, ('orion-phase5-1',), 'phase5', step) best = (step, folder, mf) break except (OSError, ValueError, RuntimeError, FileNotFoundError) as exc: print('⚠️ Skipping incomplete Phase5 checkpoint:', rel, exc, flush=True) if best: return best for step, rel in latest_remote(ns, 'phase4'): if P5.REQUIRE_PHASE4_COMPLETE and step < 900: raise RuntimeError(f'Latest Phase4 checkpoint is {step}, not 900. Finish Phase4 first.') try: folder, mf = ns['p3_hub_restore'](P5.SOURCE_REPO, rel, work, ('orion-phase4-1',), 'phase4', step) return 0, folder, mf except (OSError, ValueError, RuntimeError, FileNotFoundError) as exc: print('⚠️ Skipping incomplete Phase4 checkpoint:', rel, exc, flush=True) raise RuntimeError('No complete Phase4 source checkpoint was found.')
def select_streams(ns, offsets=None, for_inspect=False): offsets = offsets or {} active = {} for key, spec in SOURCE_SPECS.items(): if not allowed(spec): if not (for_inspect and spec['rights'] == 'claude' and P5.PREVIEW_CLAUDE_SOURCES): print('🔒 Training rights gate:', key, '(disabled)', flush=True) continue print('👀 CLAUDE PREVIEW ONLY:', key, '(NOT enabled for training)', flush=True) try: active[key] = SourceStream(key, ns, offset=0 if for_inspect else int(offsets.get(key,0))) except Exception as exc: print(f'⚠️ {key} unavailable: {type(exc).__name__}: {exc}', flush=True) if P5.REQUIRE_MINICPM_AGENT and not any(k.startswith('minicpm_agent_') for k in active): raise RuntimeError('MiniCPM5 agent mix required but no agent config could be opened.') if P5.REQUIRE_MINICPM_CORE and 'minicpm_core' not in active: raise RuntimeError('MiniCPM5 core SFT required but gated/unavailable. Request access on Hugging Face.') if 'minicpm_core' not in active: print('⚠️ MiniCPM5 CORE SFT unavailable (possibly gated). Other SFT sources replace its share.', flush=True) if not any(s.spec['kind'] == 'other' for s in active.values()) and 'minicpm_core' not in active: raise RuntimeError('No general SFT source available; refusing agent-only training.') return active
def choose_sample(ns, streams, tokenizer, cap, rng): bykind = collections.defaultdict(list) for key, s in streams.items(): bykind[s.spec['kind']].append(s) ratios = dict(P5.RATIOS) if not bykind['core']: ratios['other_sft'] += ratios.pop('minicpm_core') categories = [('core',ratios.get('minicpm_core',0)), ('other',ratios['other_sft']), ('agent',ratios['agent']), ('identity',ratios['identity'])] categories = [(k,v) for k,v in categories if v > 0 and (k == 'identity' or bykind[k])] for _ in range(180): group = rng.choices([k for k,v in categories],weights=[v for k,v in categories])[0] if group == 'identity': sample = pack_case(ns,'identity',None,tokenizer,cap,rng) if sample is not None: return 'identity',sample continue sources = bykind[group] stream = rng.choices(sources,weights=[s.spec['weight'] for s in sources])[0] try: kind, value = stream.next_case(tokenizer) except Exception as exc: print('⚠️ Source quarantined:', exc, flush=True) bykind[group] = [s for s in bykind[group] if s is not stream] if group == 'agent' and P5.REQUIRE_MINICPM_AGENT and not bykind[group]: raise RuntimeError('All required MiniCPM5 agent sources failed; refusing silent fallback.') from exc if group == 'core' and P5.REQUIRE_MINICPM_CORE and not bykind[group]: raise RuntimeError('Required MiniCPM5 core source failed; check gated access.') from exc categories = [(k,v) for k,v in categories if k != group or bykind[group]] if not categories: raise RuntimeError('All sources quarantined') continue sample = pack_case(ns,kind,value,tokenizer,cap,rng) if sample is not None: return stream.key, sample stream.rejected['whole_sample_over_context'] += 1 raise RuntimeError('No whole sample could be packed after 180 attempts; inspect source quality.')
def eval_loss(ns, model, tok): torch = ns['torch'] scores = [] model.eval() try: for q,a in EVAL_CASES: c = dict(history=[dict(role='user',content=q)], answer=a, reason='') sample, _ = ns['p4_pack'](c,tok,'Medium',8192) if sample is None: continue x,y = sample with torch.no_grad(), torch.autocast(device_type='cuda',dtype=torch.bfloat16): ce, _ = model(x.unsqueeze(0).to(ns['DEVICE']), y.unsqueeze(0).to(ns['DEVICE'])) scores.append(float(ce.detach())) finally: model.train() return sum(scores)/len(scores) if scores else float('nan')
def save(ns, model, tok, opt, arch, step, streams, work, parent): dest = work/f'phase5-step-{step:06d}' if dest.exists(): raise FileExistsError(dest) extra = dict(format_version='orion-phase5-1', training_stage='phase5', phase5_fingerprint=fp(parent), phase5_parent=parent, phase5_source_positions={k:s.raw_rows for k,s in streams.items()}, phase5_source_stats={k:dict(accepted=s.accepted,rejected=dict(s.rejected)) for k,s in streams.items()}, identity=P5.NAME, created_by=P5.CREATOR, source_checkpoint_repo=P5.SOURCE_REPO, source_checkpoint_folder=parent, agent_format='Orion AgentML: supervised tool calls, observed outputs, and final answers', warning='Training steps do not establish reasoning quality; run independent evaluations.') # Saving requires free disk for 24+ shards, never prune before verified upload. estimate = sum(p.numel()*p.element_size() for p in model.parameters()) if shutil.disk_usage(work).free < estimate + 2*1024**3: raise RuntimeError('Not enough disk space for an atomic Phase5 checkpoint.') item = ns['save_checkpoint'](model,tok,opt,dest,arch,step, {k:s.raw_rows for k,s in streams.items()},save_optimizer=P5.SAVE_OPTIMIZER, manifest_overrides=extra) ns['check_checkpoint_folder'](item,('orion-phase5-1',)) shutil.copy2(Path(__file__), item/'orion_phase5_launcher.py') if P5.REQUIRE_HUB_UPLOAD: ns['upload_checkpoint'](item,P5.UPLOAD_REPO) ns['combo_uploaded_files'](item,P5.UPLOAD_REPO) folders = sorted(work.glob('phase5-step-*')) for old in folders[:-max(2,P5.KEEP_LOCAL)]: if old != item and old.is_dir(): ns['check_checkpoint_folder'](old,('orion-phase5-1',)) shutil.rmtree(old) return item
def selftest(): assert sum(P5.RATIOS.values()) == 1 assert quality_check('What is your name?', 'What is your name?') == 'prompt_echo' assert quality_check('Hi', 'Hello!', require_substance=False) is None assert quality_check('A?', 'is not a sheep that ran away '*40, require_substance=False) == 'repetitive' assert quality_check('Question', 'Here is a detailed, nonrepeating explanation that answers the question clearly.', require_substance=False) is None assert cap_for_step(1) == 8192 and cap_for_step(P5.STEPS) == 32768 assert P5.ARCHITECTURE == 'orion_flagship_2b_t2_2' assert all(k in SOURCE_SPECS for k in ('claude_opus46_inversion', 'claude_opus47_inversion', 'claude_opus48_max')) if not P5.ALLOW_CLAUDE_TEACHER_DATA: assert not allowed(SOURCE_SPECS['claude_opus47_inversion']) assert P5.PREVIEW_CLAUDE_SOURCES is True fake_ns = {'parse_json':lambda x:x} mini = mini_agent_row({'messages':[ {'role':'system','content':'You are Codex, not Orion.'}, {'role':'user','content':'Read file'}, {'role':'assistant','content':'','tool_calls':[{'type':'function','function':{'name':'read','arguments':{'path':'a'}}}]}, {'role':'tool','content':'File contents'}], 'tools':[]},fake_ns) assert mini and len(mini['messages']) == 3 assert not any('You are Codex' in str(m) for m in mini['messages']) assert mini['messages'][1]['tool_calls'][0]['function']['name'] == 'read' assert mini['messages'][2]['role'] == 'tool' plain = {'messages': [ {'role':'system','content':'You are Claude'}, {'role':'user','content':'Explain a useful concept in plain English.'}, {'role':'assistant','content':'A good explanation uses a simple definition, an example, and one clear limitation.'}]} case = minicpm_general_chat(plain, fake_ns) assert case and case['history'][0]['role']=='user' assert not minicpm_general_chat({'messages': plain['messages'] + [{'role':'tool','content':'unverified'}]}, fake_ns) print('✅ Phase5 local CPU selftest passed. No downloads, no GPU, no training.')
def inspect(ns): streams = select_streams(ns, for_inspect=True) print('\n🔎 SOURCE AUDIT (real rows, never used for training in this mode)') for name, s in streams.items(): for _ in range(2): try: kind, case = s.next_case() if kind == 'agent': prompt,target,final=case print(f' {name}: agent final={final} context={len(prompt)} chars target={len(target)} chars') else: print(f' {name}: chat answer={len(case["answer"])} chars ' f'reason={len(case.get("reason", ""))} chars history={len(case["history"])} turns') except Exception as exc: print(f' {name}: ⚠️ {type(exc).__name__}: {exc}') break print(f' accepted={s.accepted}, rejected={dict(s.rejected)}') print('Inspect sample acceptance and data rights before switching MODE to smoke/train.')
def token_audit(ns): """Measure REAL Mistral-tokenizer lengths of accepted, complete examples.
Sampling is approximate and reports only accepted rows; no GPU/weights/training. Claude rows are inspectable when PREVIEW_CLAUDE_SOURCES=True, but are NEVER included in training unless separately authorised. """ tok = ns['load_tokenizer']() streams = select_streams(ns, for_inspect=True) results = {} out = Path(P5.WORK_DIR).resolve() / 'phase5_token_audit.json' out.parent.mkdir(parents=True, exist_ok=True) print(f'📏 TOKEN AUDIT | {P5.TOKEN_AUDIT_ROWS} accepted samples/source | tokenizer={getattr(tok,"name_or_path","Orion")}', flush=True) for name, stream in streams.items(): lengths, targets, reasons = [], [], [] for _ in range(P5.TOKEN_AUDIT_ROWS): try: category, case = stream.next_case(tokenizer=tok) if category == 'agent': prompt, target, final = case p_ids = tok.encode(prompt, add_special_tokens=False) t_ids = tok.encode(target, add_special_tokens=False) total = len(p_ids) + len(t_ids) + int(bool(final)) + int(tok.bos_token_id is not None) target_n = len(t_ids) + int(bool(final)) reason_n = 0 else: effort = 'Max' if case.get('reason') else 'Instant' sample, total = ns['p4_pack'](case, tok, effort, 10**7) if sample is None: raise ValueError('Sample could not be packed (unusually large).') target_n = int((sample[1] != -100).sum().item()) reason_n = len(tok.encode(case.get('reason', ''), add_special_tokens=False)) lengths.append(total) targets.append(target_n) reasons.append(reason_n) except Exception as exc: print(f'⚠️ {name}: stopped after {len(lengths)} samples: {type(exc).__name__}: {exc}',flush=True) break if not lengths: results[name] = dict(samples=0, error='no accepted samples') continue ordered = sorted(lengths) pct = lambda q: ordered[min(len(ordered)-1, math.ceil(q*len(ordered))-1)] result = dict(samples=len(lengths), total_tokens_min=min(lengths), total_tokens_median=statistics.median(lengths), total_tokens_p90=pct(.9), total_tokens_p99=pct(.99), total_tokens_max=max(lengths), target_tokens_median=statistics.median(targets), reasoning_tokens_median=statistics.median(reasons), above_8k=sum(x>8192 for x in lengths), above_16k=sum(x>16384 for x in lengths), above_32k=sum(x>32768 for x in lengths), preview_only=stream.spec['rights']=='claude' and not P5.ALLOW_CLAUDE_TEACHER_DATA, rejected=dict(stream.rejected)) results[name] = result print(f' {name:26s} n={len(lengths):3d} median={result["total_tokens_median"]:7g} ' f'p90={result["total_tokens_p90"]:6d} max={result["total_tokens_max"]:6d} ' f'target_median={result["target_tokens_median"]:6g} ' f'over32k={result["above_32k"]}',flush=True) out.write_text(json.dumps(dict(model=P5.NAME, sample_size=P5.TOKEN_AUDIT_ROWS, note='Sample statistics of accepted rows, not full-dataset token totals or training permission.', sources=results), indent=2, ensure_ascii=False)) print(f'✅ Saved measured token counts: {out}',flush=True)
def train(ns, smoke=False): torch = ns['torch'] if not torch.cuda.is_available(): raise RuntimeError('Orion Phase5 requires a CUDA GPU.') if P5.REQUIRE_HUB_UPLOAD and not os.environ.get('HF_TOKEN'): os.environ['HF_TOKEN'] = getpass.getpass('HF write token (hidden): ').strip() ns['HF_TOKEN'] = os.environ['HF_TOKEN'] ns['p3_prepare_gpu']() ns['p4_enable_rope']() work = Path(P5.WORK_DIR).resolve();work.mkdir(parents=True,exist_ok=True) start, folder, mf = pick_checkpoint(ns,work) if start >= P5.STEPS: print(f'🏁 Phase5 already finished: {start}/{P5.STEPS}');return parent = mf.get('phase5_parent') if start else ( 'checkpoints/phase4-step-'+str(mf['step']).zfill(6)) arch = ns['p4_make_arch'](mf['architecture']) ns['select_attention'](arch) model = ns['build_model'](arch) ns['restore_model_shards'](model,folder,mf['model_shards']) model.set_specialization_scale(1.0);model.train() tok = ns['load_tokenizer']() optimizer = torch.optim.AdamW(model.parameters(), lr=P5.LEARNING_RATE, betas=(.9,.95),eps=1e-8,weight_decay=.01,fused=True) if start and (folder/'optimizer.pt').exists(): optimizer.load_state_dict(torch.load(folder/'optimizer.pt',map_location=ns['DEVICE'],weights_only=True)) elif start: print('⚠️ AdamW moments reset on resume (SAVE_OPTIMIZER=False).') streams = select_streams(ns, mf.get('phase5_source_positions',{}) if start else {}) rng = random.Random(P5.SEED + start*100003) print(f'🚀 PHASE5 {start}/{P5.STEPS} -> {P5.NAME} | sources={list(streams)}',flush=True) if smoke: print('🧪 SMOKE MODE: one update, no checkpoint upload.',flush=True) for step in range(start+1, (start+2 if smoke else P5.STEPS+1)): cap = cap_for_step(step) t0 = time.monotonic() while True: optimizer.zero_grad(set_to_none=True) counts = collections.Counter() total_ce = 0. longest = 0 accum = 1 if smoke else P5.GRAD_ACCUM try: for _ in range(accum): ns['ACTIVE_CONTEXT_LIMIT'] = cap label,(x,y) = choose_sample(ns,streams,tok,cap,rng) longest = max(longest,len(x)) with torch.autocast(device_type='cuda',dtype=torch.bfloat16,cache_enabled=True): ce, aux = model(x.unsqueeze(0).to(ns['DEVICE']), y.unsqueeze(0).to(ns['DEVICE'])) loss = (ce + .25*aux)/accum if not torch.isfinite(loss).item(): raise RuntimeError('Nonfinite Phase5 loss') loss.backward() counts[label] += 1 total_ce += float(ce.detach()) break except torch.cuda.OutOfMemoryError: optimizer.zero_grad(set_to_none=True) torch.cuda.empty_cache() if cap <= 8192: raise cap //= 2 print(f'⚠️ OOM: retrying with whole samples <= {cap} tokens.',flush=True) grad = torch.nn.utils.clip_grad_norm_(model.parameters(),1.0) if not torch.isfinite(grad).item(): raise RuntimeError('Nonfinite gradient norm') lr = ns['lr_at'](step,P5.STEPS,P5.LEARNING_RATE,warmup=50) for group in optimizer.param_groups: group['lr'] = lr optimizer.step() if smoke or step == start+1 or step%P5.LOG_EVERY == 0: print(f'🔥 PHASE5 {step}/{P5.STEPS} CE={total_ce/accum:.4f} ' f'grad={float(grad):.3f} lr={lr:.2e} cap={cap} ' f'longest={longest} elapsed={time.monotonic()-t0:.1f}s sources={dict(counts)}',flush=True) if smoke: print('✅ Smoke complete. No checkpoint uploaded.');break if step%P5.EVAL_EVERY==0: val = eval_loss(ns,model,tok) print(f'📊 Fixed diagnostic CE={val:.4f} (not a reasoning accuracy score)',flush=True) if step%P5.SAVE_EVERY==0 or step==P5.STEPS: save(ns,model,tok,optimizer,arch,step,streams,work,parent) print('🏁 Orion Phase5 run complete or smoke finished.',flush=True)
def rescue(ns): work=Path(P5.WORK_DIR).resolve() valid=[] for path in work.glob('phase5-step-*'): try: mf=ns['check_checkpoint_folder'](path,('orion-phase5-1',)) valid.append((int(mf['step']),path)) except (ValueError,OSError,KeyError): pass if not valid: raise RuntimeError('No complete local Phase5 checkpoint to rescue.') step, path=max(valid) ns['upload_checkpoint'](path,P5.UPLOAD_REPO) ns['combo_uploaded_files'](path,P5.UPLOAD_REPO) print('✅ Rescued verified Phase5 step',step)
def main(): print(f'🤖 ORION PHASE5 | mode={P5.MODE} | {P5.NAME}') if P5.MODE=='selftest': return selftest() if P5.MODE not in ('inspect','token_audit','smoke','train','rescue'): raise ValueError('MODE must be selftest, inspect, token_audit, smoke, train, or rescue') if P5.MODE in ('train','smoke','rescue') and P5.REQUIRE_HUB_UPLOAD and not os.environ.get('HF_TOKEN'): os.environ['HF_TOKEN'] = getpass.getpass('Hugging Face write token (hidden): ').strip() ns=load_orion_runtime() if P5.MODE=='inspect': return inspect(ns) if P5.MODE=='token_audit': return token_audit(ns) if P5.MODE=='smoke': return train(ns,smoke=True) if P5.MODE=='train': return train(ns,smoke=False) if P5.MODE=='rescue': return rescue(ns)
if __name__=='__main__': main()
return
if __name__ == "__main__": app.run()1234567891011121314151617{ "add_prefix_space": true, "backend": "tokenizers", "bos_token": "<s>", "clean_up_tokenization_spaces": false, "eos_token": "</s>", "is_local": false, "legacy": false, "local_files_only": false, "model_max_length": 1000000000000000019884624838656, "pad_token": null, "sp_model_kwargs": {}, "spaces_between_special_tokens": false, "tokenizer_class": "TokenizersBackend", "unk_token": "<unk>", "use_default_system_prompt": false}checkpoints/phase5-step-003800/config.jsonAdded+45
checkpoints/phase5-step-003800/manifest.jsonAdded+404
checkpoints/phase5-step-003800/model-0000.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0001.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0002.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0003.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0004.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0005.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0006.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0007.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0008.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0009.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0010.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0011.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0012.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0013.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0014.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0015.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0016.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0017.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0018.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0019.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0020.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0021.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0022.safetensorsAdded+3
checkpoints/phase5-step-003800/model-0023.safetensorsAdded+3
checkpoints/phase5-step-003800/orion_phase5_launcher.pyAdded+894
checkpoints/phase5-step-003800/orion_unified_trainer.pyAdded
checkpoints/phase5-step-003800/tokenizer/tokenizer.jsonAdded
checkpoints/phase5-step-003800/tokenizer/tokenizer_config.jsonAdded+17