diff --git a/src/inferrsi/knowledge/atoms/model-sol-analysis.huggingarch-model-sol.json b/src/inferrsi/knowledge/atoms/model-sol-analysis.huggingarch-model-sol.json new file mode 100644 index 000000000..54f0f2adc --- /dev/null +++ b/src/inferrsi/knowledge/atoms/model-sol-analysis.huggingarch-model-sol.json @@ -0,0 +1,174 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Model-level prefill and decode speed-of-light analysis for decoder-only (optionally multimodal) inference under a declared parallel layout; extends performance-ceiling-analysis L1 from one operation to a whole model without replacing its evidence rules", + "hardware": "any; per-dtype peaks, memory bandwidth and link bandwidths must be supplied with sources", + "prerequisites": "Model config and forward source at a pinned revision, the checkpoint's tensor headers where a checkpoint exists, the serving framework release that will run, and the layout and workload; reading the skill does not authorize execution", + "input_contract": "Model config, forward source and checkpoint headers; serving framework and release with source anchors for every fusion; per-world parallel degrees, ranks per node and node count; batch, input, output, prefix and verify tokens, and the measured expert load skew when expert placement makes per-rank work depend on routing; per-dtype compute peaks at the sustained clock, memory and link bandwidths with sources; any launch floor or link latency labelled as an assumption", + "produced_artifact": "A per-phase table with per-op counts and binding resource, per-resource totals, the conditional bound and its binding resources, the serial per-op estimate, headline TTFT, TPOT and throughput figures each labelled bound or estimate, every anchor and gate result, assumptions and unknowns; analytical only, not a measured result", + "failure_modes": [ + "The serial per-op sum is reported as a bound, or used to reject a faster measurement", + "Counts come from the unfused graph, overstating launches and activation round-trips, or from fusions the framework does not run, understating bytes", + "A degree that does not divide a weight is silently replaced by a divisor that does", + "Expert load skew is left at its default, making routed time and exchange optimistic", + "A windowed layer is priced as global, or a dense layer as windowed, because the cache growth law was not checked", + "Prefill attention is counted as a full square rather than causal pairs", + "An unmeasured launch floor or link latency, or a spec-sheet peak below the sustained clock, enters the bound", + "A measured envelope replaces the analytical figure instead of sitting beside it" + ], + "refusal_point": "Stops when an anchor gate fails or cannot be judged, when a required peak, used fabric rate or required expert-parallel load skew is missing, or when weights plus one request's KV do not fit a rank. Unanchored fusion permits only a labelled unfused estimate when its counts are available." + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "The serial estimate assumes full compute/memory overlap within an op, no overlap between ops and no pipeline bubble. The source uses one link latency for every fabric.", + "Counts are only as good as the anchors and the framework binding behind them; behaviour that lives only in weights or custom runtime code is out of reach.", + "Decoder-only models, optionally multimodal; encoder-decoder models are out of scope.", + "Checkout-only local skill; no automatic execution or promotion.", + "Only declared references are required; other cross-skill links are navigation.", + "Historical revisions require a matching checkout or a retained store." + ], + "empirical_validation": "not_run", + "title": "HuggingArch: model-level speed-of-light method, source reading", + "attribution": [ + { + "type": "git", + "url": "https://github.com/shenh10/HuggingArch", + "commit": "e69d20a028e5b17524aa48b53bddf8b9aad5d15b", + "revision_precision": "full", + "license": "MIT", + "observed_at": "2026-11-10", + "paths": [ + "docs/inference_cost_model.md", + "docs/evaluation_model.md", + "docs/symbolic_evaluation.md", + "docs/design.md", + "docs/parallelism.md", + "docs/kv_cache_storage.md", + "docs/attention_families.md", + "docs/moe_expert_axis.md", + "docs/quantization.md", + "docs/validation.md", + "docs/measured_calibration.md", + "docs/known_limitations.md", + "README.md", + "backend/inference/row_roofline.py", + "backend/inference/phases.py", + "backend/inference/phase_formulas.py", + "backend/arch/eval/binding.py", + "backend/arch/eval/transforms.py", + "backend/arch/eval/fusion.py", + "backend/inference/framework_bindings/__init__.py", + "backend/arch/layout/weight_endpoints.py", + "backend/arch/layout/layout.py", + "backend/arch/layout/workload.py", + "backend/arch/layout/physical.py", + "backend/arch/layout/comm_volume.py", + "backend/inference/comm_cost.py", + "backend/arch/eval/cache.py", + "backend/arch/eval/formats.py", + "backend/arch/dtypes.py", + "backend/arch/validate/_axioms.py", + "backend/arch/validate/_orchestrator.py", + "backend/arch/validate/_type_contracts.py", + "backend/inference/sol_closure.py", + "backend/inference/op_calibration.py", + "backend/inference/calibration_overlay.py", + "backend/measure/lookup.py" + ], + "identity": "references/huggingarch-source-identity.json", + "readset": "references/huggingarch-model-sol.md", + "note": "Cited paths only; the identity file records every retrieved file, its digests and its inspection scope, including files read but not cited. performance-ceiling-analysis keeps its own earlier pin for the checkpoint anchor." + } + ], + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis/references/huggingarch-model-sol.md", + "sha256": "79d5f350964a578fea199c1d77b0c767bb73e85e0fefbb4cebb3f8e0e6264504" + }, + { + "type": "git", + "url": "https://github.com/shenh10/HuggingArch", + "commit": "e69d20a028e5b17524aa48b53bddf8b9aad5d15b", + "revision_precision": "full", + "license": "MIT", + "observed_at": "2026-11-10", + "paths": [ + "docs/inference_cost_model.md", + "docs/evaluation_model.md", + "docs/symbolic_evaluation.md", + "docs/design.md", + "docs/parallelism.md", + "docs/kv_cache_storage.md", + "docs/attention_families.md", + "docs/moe_expert_axis.md", + "docs/quantization.md", + "docs/validation.md", + "docs/measured_calibration.md", + "docs/known_limitations.md", + "README.md", + "backend/inference/row_roofline.py", + "backend/inference/phases.py", + "backend/inference/phase_formulas.py", + "backend/arch/eval/binding.py", + "backend/arch/eval/transforms.py", + "backend/arch/eval/fusion.py", + "backend/inference/framework_bindings/__init__.py", + "backend/arch/layout/weight_endpoints.py", + "backend/arch/layout/layout.py", + "backend/arch/layout/workload.py", + "backend/arch/layout/physical.py", + "backend/arch/layout/comm_volume.py", + "backend/inference/comm_cost.py", + "backend/arch/eval/cache.py", + "backend/arch/eval/formats.py", + "backend/arch/dtypes.py", + "backend/arch/validate/_axioms.py", + "backend/arch/validate/_orchestrator.py", + "backend/arch/validate/_type_contracts.py", + "backend/inference/sol_closure.py", + "backend/inference/op_calibration.py", + "backend/inference/calibration_overlay.py", + "backend/measure/lookup.py" + ], + "identity": "references/huggingarch-source-identity.json", + "readset": "references/huggingarch-model-sol.md", + "note": "Cited paths only; the identity file records every retrieved file, its digests and its inspection scope, including files read but not cited. performance-ceiling-analysis keeps its own earlier pin for the checkpoint anchor." + } + ], + "id": "model-sol-analysis.huggingarch-model-sol", + "kind": "knowledge", + "entrypoint": "huggingarch-model-sol.md", + "atom": { + "when": {}, + "license": "Apache-2.0", + "permissions": { + "read": true, + "retain": true, + "redistribute": true + }, + "layer": "L3", + "source_span": { + "source_index": 0, + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis/references/huggingarch-model-sol.md", + "byte_range": [ + 0, + 19954 + ], + "sha256": "79d5f350964a578fea199c1d77b0c767bb73e85e0fefbb4cebb3f8e0e6264504" + } + } + }, + "content": { + "huggingarch-model-sol.md": { + "path": "playbooks/model-sol-analysis/references/huggingarch-model-sol.md" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/model-sol-analysis.huggingarch-source-identity.json b/src/inferrsi/knowledge/atoms/model-sol-analysis.huggingarch-source-identity.json new file mode 100644 index 000000000..faabeab4b --- /dev/null +++ b/src/inferrsi/knowledge/atoms/model-sol-analysis.huggingarch-source-identity.json @@ -0,0 +1,174 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Model-level prefill and decode speed-of-light analysis for decoder-only (optionally multimodal) inference under a declared parallel layout; extends performance-ceiling-analysis L1 from one operation to a whole model without replacing its evidence rules", + "hardware": "any; per-dtype peaks, memory bandwidth and link bandwidths must be supplied with sources", + "prerequisites": "Model config and forward source at a pinned revision, the checkpoint's tensor headers where a checkpoint exists, the serving framework release that will run, and the layout and workload; reading the skill does not authorize execution", + "input_contract": "Model config, forward source and checkpoint headers; serving framework and release with source anchors for every fusion; per-world parallel degrees, ranks per node and node count; batch, input, output, prefix and verify tokens, and the measured expert load skew when expert placement makes per-rank work depend on routing; per-dtype compute peaks at the sustained clock, memory and link bandwidths with sources; any launch floor or link latency labelled as an assumption", + "produced_artifact": "A per-phase table with per-op counts and binding resource, per-resource totals, the conditional bound and its binding resources, the serial per-op estimate, headline TTFT, TPOT and throughput figures each labelled bound or estimate, every anchor and gate result, assumptions and unknowns; analytical only, not a measured result", + "failure_modes": [ + "The serial per-op sum is reported as a bound, or used to reject a faster measurement", + "Counts come from the unfused graph, overstating launches and activation round-trips, or from fusions the framework does not run, understating bytes", + "A degree that does not divide a weight is silently replaced by a divisor that does", + "Expert load skew is left at its default, making routed time and exchange optimistic", + "A windowed layer is priced as global, or a dense layer as windowed, because the cache growth law was not checked", + "Prefill attention is counted as a full square rather than causal pairs", + "An unmeasured launch floor or link latency, or a spec-sheet peak below the sustained clock, enters the bound", + "A measured envelope replaces the analytical figure instead of sitting beside it" + ], + "refusal_point": "Stops when an anchor gate fails or cannot be judged, when a required peak, used fabric rate or required expert-parallel load skew is missing, or when weights plus one request's KV do not fit a rank. Unanchored fusion permits only a labelled unfused estimate when its counts are available." + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "The serial estimate assumes full compute/memory overlap within an op, no overlap between ops and no pipeline bubble. The source uses one link latency for every fabric.", + "Counts are only as good as the anchors and the framework binding behind them; behaviour that lives only in weights or custom runtime code is out of reach.", + "Decoder-only models, optionally multimodal; encoder-decoder models are out of scope.", + "Checkout-only local skill; no automatic execution or promotion.", + "Only declared references are required; other cross-skill links are navigation.", + "Historical revisions require a matching checkout or a retained store." + ], + "empirical_validation": "not_run", + "title": "HuggingArch source identity and inspection scope", + "attribution": [ + { + "type": "git", + "url": "https://github.com/shenh10/HuggingArch", + "commit": "e69d20a028e5b17524aa48b53bddf8b9aad5d15b", + "revision_precision": "full", + "license": "MIT", + "observed_at": "2026-11-10", + "paths": [ + "docs/inference_cost_model.md", + "docs/evaluation_model.md", + "docs/symbolic_evaluation.md", + "docs/design.md", + "docs/parallelism.md", + "docs/kv_cache_storage.md", + "docs/attention_families.md", + "docs/moe_expert_axis.md", + "docs/quantization.md", + "docs/validation.md", + "docs/measured_calibration.md", + "docs/known_limitations.md", + "README.md", + "backend/inference/row_roofline.py", + "backend/inference/phases.py", + "backend/inference/phase_formulas.py", + "backend/arch/eval/binding.py", + "backend/arch/eval/transforms.py", + "backend/arch/eval/fusion.py", + "backend/inference/framework_bindings/__init__.py", + "backend/arch/layout/weight_endpoints.py", + "backend/arch/layout/layout.py", + "backend/arch/layout/workload.py", + "backend/arch/layout/physical.py", + "backend/arch/layout/comm_volume.py", + "backend/inference/comm_cost.py", + "backend/arch/eval/cache.py", + "backend/arch/eval/formats.py", + "backend/arch/dtypes.py", + "backend/arch/validate/_axioms.py", + "backend/arch/validate/_orchestrator.py", + "backend/arch/validate/_type_contracts.py", + "backend/inference/sol_closure.py", + "backend/inference/op_calibration.py", + "backend/inference/calibration_overlay.py", + "backend/measure/lookup.py" + ], + "identity": "references/huggingarch-source-identity.json", + "readset": "references/huggingarch-model-sol.md", + "note": "Cited paths only; the identity file records every retrieved file, its digests and its inspection scope, including files read but not cited. performance-ceiling-analysis keeps its own earlier pin for the checkpoint anchor." + } + ], + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis/references/huggingarch-source-identity.json", + "sha256": "40ef6bd6d0d11e48aea4f2b30fcad11d226c32e869ea7e97fe8431b55c8dc65f" + }, + { + "type": "git", + "url": "https://github.com/shenh10/HuggingArch", + "commit": "e69d20a028e5b17524aa48b53bddf8b9aad5d15b", + "revision_precision": "full", + "license": "MIT", + "observed_at": "2026-11-10", + "paths": [ + "docs/inference_cost_model.md", + "docs/evaluation_model.md", + "docs/symbolic_evaluation.md", + "docs/design.md", + "docs/parallelism.md", + "docs/kv_cache_storage.md", + "docs/attention_families.md", + "docs/moe_expert_axis.md", + "docs/quantization.md", + "docs/validation.md", + "docs/measured_calibration.md", + "docs/known_limitations.md", + "README.md", + "backend/inference/row_roofline.py", + "backend/inference/phases.py", + "backend/inference/phase_formulas.py", + "backend/arch/eval/binding.py", + "backend/arch/eval/transforms.py", + "backend/arch/eval/fusion.py", + "backend/inference/framework_bindings/__init__.py", + "backend/arch/layout/weight_endpoints.py", + "backend/arch/layout/layout.py", + "backend/arch/layout/workload.py", + "backend/arch/layout/physical.py", + "backend/arch/layout/comm_volume.py", + "backend/inference/comm_cost.py", + "backend/arch/eval/cache.py", + "backend/arch/eval/formats.py", + "backend/arch/dtypes.py", + "backend/arch/validate/_axioms.py", + "backend/arch/validate/_orchestrator.py", + "backend/arch/validate/_type_contracts.py", + "backend/inference/sol_closure.py", + "backend/inference/op_calibration.py", + "backend/inference/calibration_overlay.py", + "backend/measure/lookup.py" + ], + "identity": "references/huggingarch-source-identity.json", + "readset": "references/huggingarch-model-sol.md", + "note": "Cited paths only; the identity file records every retrieved file, its digests and its inspection scope, including files read but not cited. performance-ceiling-analysis keeps its own earlier pin for the checkpoint anchor." + } + ], + "id": "model-sol-analysis.huggingarch-source-identity", + "kind": "knowledge", + "entrypoint": "huggingarch-source-identity.json", + "atom": { + "when": {}, + "license": "Apache-2.0", + "permissions": { + "read": true, + "retain": true, + "redistribute": true + }, + "layer": "L3", + "source_span": { + "source_index": 0, + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis/references/huggingarch-source-identity.json", + "byte_range": [ + 0, + 18566 + ], + "sha256": "40ef6bd6d0d11e48aea4f2b30fcad11d226c32e869ea7e97fe8431b55c8dc65f" + } + } + }, + "content": { + "huggingarch-source-identity.json": { + "path": "playbooks/model-sol-analysis/references/huggingarch-source-identity.json" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/model-sol-analysis.model-sol-contract.json b/src/inferrsi/knowledge/atoms/model-sol-analysis.model-sol-contract.json new file mode 100644 index 000000000..db27642c5 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/model-sol-analysis.model-sol-contract.json @@ -0,0 +1,75 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Model-level prefill and decode speed-of-light analysis for decoder-only (optionally multimodal) inference under a declared parallel layout; extends performance-ceiling-analysis L1 from one operation to a whole model without replacing its evidence rules", + "hardware": "any; per-dtype peaks, memory bandwidth and link bandwidths must be supplied with sources", + "prerequisites": "Model config and forward source at a pinned revision, the checkpoint's tensor headers where a checkpoint exists, the serving framework release that will run, and the layout and workload; reading the skill does not authorize execution", + "input_contract": "Model config, forward source and checkpoint headers; serving framework and release with source anchors for every fusion; per-world parallel degrees, ranks per node and node count; batch, input, output, prefix and verify tokens, and the measured expert load skew when expert placement makes per-rank work depend on routing; per-dtype compute peaks at the sustained clock, memory and link bandwidths with sources; any launch floor or link latency labelled as an assumption", + "produced_artifact": "A per-phase table with per-op counts and binding resource, per-resource totals, the conditional bound and its binding resources, the serial per-op estimate, headline TTFT, TPOT and throughput figures each labelled bound or estimate, every anchor and gate result, assumptions and unknowns; analytical only, not a measured result", + "failure_modes": [ + "The serial per-op sum is reported as a bound, or used to reject a faster measurement", + "Counts come from the unfused graph, overstating launches and activation round-trips, or from fusions the framework does not run, understating bytes", + "A degree that does not divide a weight is silently replaced by a divisor that does", + "Expert load skew is left at its default, making routed time and exchange optimistic", + "A windowed layer is priced as global, or a dense layer as windowed, because the cache growth law was not checked", + "Prefill attention is counted as a full square rather than causal pairs", + "An unmeasured launch floor or link latency, or a spec-sheet peak below the sustained clock, enters the bound", + "A measured envelope replaces the analytical figure instead of sitting beside it" + ], + "refusal_point": "Stops when an anchor gate fails or cannot be judged, when a required peak, used fabric rate or required expert-parallel load skew is missing, or when weights plus one request's KV do not fit a rank. Unanchored fusion permits only a labelled unfused estimate when its counts are available." + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "The serial estimate assumes full compute/memory overlap within an op, no overlap between ops and no pipeline bubble. The source uses one link latency for every fabric.", + "Counts are only as good as the anchors and the framework binding behind them; behaviour that lives only in weights or custom runtime code is out of reach.", + "Decoder-only models, optionally multimodal; encoder-decoder models are out of scope.", + "Checkout-only local skill; no automatic execution or promotion.", + "Only declared references are required; other cross-skill links are navigation.", + "Historical revisions require a matching checkout or a retained store." + ], + "empirical_validation": "not_run", + "title": "`model_sol.py` contract", + "attribution": [], + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis/references/model-sol-contract.md", + "sha256": "2a5babea1f744f124d3f234c741dae2fb6e5b48b7fd04285e6b3a476c065b34d" + } + ], + "id": "model-sol-analysis.model-sol-contract", + "kind": "knowledge", + "entrypoint": "model-sol-contract.md", + "atom": { + "when": {}, + "license": "Apache-2.0", + "permissions": { + "read": true, + "retain": true, + "redistribute": true + }, + "layer": "L3", + "source_span": { + "source_index": 0, + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis/references/model-sol-contract.md", + "byte_range": [ + 0, + 9719 + ], + "sha256": "2a5babea1f744f124d3f234c741dae2fb6e5b48b7fd04285e6b3a476c065b34d" + } + } + }, + "content": { + "model-sol-contract.md": { + "path": "playbooks/model-sol-analysis/references/model-sol-contract.md" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/model-sol-analysis.model-sol-example.json b/src/inferrsi/knowledge/atoms/model-sol-analysis.model-sol-example.json new file mode 100644 index 000000000..73c3293d2 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/model-sol-analysis.model-sol-example.json @@ -0,0 +1,75 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Model-level prefill and decode speed-of-light analysis for decoder-only (optionally multimodal) inference under a declared parallel layout; extends performance-ceiling-analysis L1 from one operation to a whole model without replacing its evidence rules", + "hardware": "any; per-dtype peaks, memory bandwidth and link bandwidths must be supplied with sources", + "prerequisites": "Model config and forward source at a pinned revision, the checkpoint's tensor headers where a checkpoint exists, the serving framework release that will run, and the layout and workload; reading the skill does not authorize execution", + "input_contract": "Model config, forward source and checkpoint headers; serving framework and release with source anchors for every fusion; per-world parallel degrees, ranks per node and node count; batch, input, output, prefix and verify tokens, and the measured expert load skew when expert placement makes per-rank work depend on routing; per-dtype compute peaks at the sustained clock, memory and link bandwidths with sources; any launch floor or link latency labelled as an assumption", + "produced_artifact": "A per-phase table with per-op counts and binding resource, per-resource totals, the conditional bound and its binding resources, the serial per-op estimate, headline TTFT, TPOT and throughput figures each labelled bound or estimate, every anchor and gate result, assumptions and unknowns; analytical only, not a measured result", + "failure_modes": [ + "The serial per-op sum is reported as a bound, or used to reject a faster measurement", + "Counts come from the unfused graph, overstating launches and activation round-trips, or from fusions the framework does not run, understating bytes", + "A degree that does not divide a weight is silently replaced by a divisor that does", + "Expert load skew is left at its default, making routed time and exchange optimistic", + "A windowed layer is priced as global, or a dense layer as windowed, because the cache growth law was not checked", + "Prefill attention is counted as a full square rather than causal pairs", + "An unmeasured launch floor or link latency, or a spec-sheet peak below the sustained clock, enters the bound", + "A measured envelope replaces the analytical figure instead of sitting beside it" + ], + "refusal_point": "Stops when an anchor gate fails or cannot be judged, when a required peak, used fabric rate or required expert-parallel load skew is missing, or when weights plus one request's KV do not fit a rank. Unanchored fusion permits only a labelled unfused estimate when its counts are available." + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "The serial estimate assumes full compute/memory overlap within an op, no overlap between ops and no pipeline bubble. The source uses one link latency for every fabric.", + "Counts are only as good as the anchors and the framework binding behind them; behaviour that lives only in weights or custom runtime code is out of reach.", + "Decoder-only models, optionally multimodal; encoder-decoder models are out of scope.", + "Checkout-only local skill; no automatic execution or promotion.", + "Only declared references are required; other cross-skill links are navigation.", + "Historical revisions require a matching checkout or a retained store." + ], + "empirical_validation": "not_run", + "title": "Synthetic model-level speed-of-light example inputs", + "attribution": [], + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis/references/model-sol-example.json", + "sha256": "557ac952af65c907e5c08f55c3b15f5fd24317308b0b4ed317d4eb9217a02ac8" + } + ], + "id": "model-sol-analysis.model-sol-example", + "kind": "knowledge", + "entrypoint": "model-sol-example.json", + "atom": { + "when": {}, + "license": "Apache-2.0", + "permissions": { + "read": true, + "retain": true, + "redistribute": true + }, + "layer": "L3", + "source_span": { + "source_index": 0, + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis/references/model-sol-example.json", + "byte_range": [ + 0, + 3552 + ], + "sha256": "557ac952af65c907e5c08f55c3b15f5fd24317308b0b4ed317d4eb9217a02ac8" + } + } + }, + "content": { + "model-sol-example.json": { + "path": "playbooks/model-sol-analysis/references/model-sol-example.json" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/model-sol-analysis.model-sol.json b/src/inferrsi/knowledge/atoms/model-sol-analysis.model-sol.json new file mode 100644 index 000000000..6427ed35b --- /dev/null +++ b/src/inferrsi/knowledge/atoms/model-sol-analysis.model-sol.json @@ -0,0 +1,75 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Model-level prefill and decode speed-of-light analysis for decoder-only (optionally multimodal) inference under a declared parallel layout; extends performance-ceiling-analysis L1 from one operation to a whole model without replacing its evidence rules", + "hardware": "any; per-dtype peaks, memory bandwidth and link bandwidths must be supplied with sources", + "prerequisites": "Model config and forward source at a pinned revision, the checkpoint's tensor headers where a checkpoint exists, the serving framework release that will run, and the layout and workload; reading the skill does not authorize execution", + "input_contract": "Model config, forward source and checkpoint headers; serving framework and release with source anchors for every fusion; per-world parallel degrees, ranks per node and node count; batch, input, output, prefix and verify tokens, and the measured expert load skew when expert placement makes per-rank work depend on routing; per-dtype compute peaks at the sustained clock, memory and link bandwidths with sources; any launch floor or link latency labelled as an assumption", + "produced_artifact": "A per-phase table with per-op counts and binding resource, per-resource totals, the conditional bound and its binding resources, the serial per-op estimate, headline TTFT, TPOT and throughput figures each labelled bound or estimate, every anchor and gate result, assumptions and unknowns; analytical only, not a measured result", + "failure_modes": [ + "The serial per-op sum is reported as a bound, or used to reject a faster measurement", + "Counts come from the unfused graph, overstating launches and activation round-trips, or from fusions the framework does not run, understating bytes", + "A degree that does not divide a weight is silently replaced by a divisor that does", + "Expert load skew is left at its default, making routed time and exchange optimistic", + "A windowed layer is priced as global, or a dense layer as windowed, because the cache growth law was not checked", + "Prefill attention is counted as a full square rather than causal pairs", + "An unmeasured launch floor or link latency, or a spec-sheet peak below the sustained clock, enters the bound", + "A measured envelope replaces the analytical figure instead of sitting beside it" + ], + "refusal_point": "Stops when an anchor gate fails or cannot be judged, when a required peak, used fabric rate or required expert-parallel load skew is missing, or when weights plus one request's KV do not fit a rank. Unanchored fusion permits only a labelled unfused estimate when its counts are available." + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "The serial estimate assumes full compute/memory overlap within an op, no overlap between ops and no pipeline bubble. The source uses one link latency for every fabric.", + "Counts are only as good as the anchors and the framework binding behind them; behaviour that lives only in weights or custom runtime code is out of reach.", + "Decoder-only models, optionally multimodal; encoder-decoder models are out of scope.", + "Checkout-only local skill; no automatic execution or promotion.", + "Only declared references are required; other cross-skill links are navigation.", + "Historical revisions require a matching checkout or a retained store." + ], + "empirical_validation": "not_run", + "title": "Pure model-level speed-of-light arithmetic over supplied counts.\n\nNo I/O, network access, device execution or acceptance. Every function takes\nJSON data, returns JSON data and reports missing evidence as unknowns instead of\nguessing. See references/model-sol-contract.md for inputs, outputs and limits.", + "attribution": [], + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis/scripts/model_sol.py", + "sha256": "e3810ff5afafeded34a59ee3fb64093f5e39448e76bde8afa68c5f8238eba63e" + } + ], + "id": "model-sol-analysis.model-sol", + "kind": "knowledge", + "entrypoint": "model_sol.py", + "atom": { + "when": {}, + "license": "Apache-2.0", + "permissions": { + "read": true, + "retain": true, + "redistribute": true + }, + "layer": "L3", + "source_span": { + "source_index": 0, + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis/scripts/model_sol.py", + "byte_range": [ + 0, + 25400 + ], + "sha256": "e3810ff5afafeded34a59ee3fb64093f5e39448e76bde8afa68c5f8238eba63e" + } + } + }, + "content": { + "model_sol.py": { + "path": "playbooks/model-sol-analysis/scripts/model_sol.py" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/model-sol-analysis.original.json b/src/inferrsi/knowledge/atoms/model-sol-analysis.original.json new file mode 100644 index 000000000..799be0311 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/model-sol-analysis.original.json @@ -0,0 +1,203 @@ +{ + "authority": "checkout", + "metadata": { + "id": "model-sol-analysis.original", + "kind": "knowledge", + "entrypoint": "guide.md", + "title": "Walk a whole model to per-phase (prefill, decode) speed-of-light figures under a declared parallel layout - anchored counts, the fused graph the framework runs, per-rank geometry, explicit communication and KV growth laws - and report a resource-total bound apart from a serial per-op estimate.", + "origin": [ + "external" + ], + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis/SKILL.md", + "sha256": "b7a2dc5cc051427b12e195652c20f7ee337326a6954a44f811f8b06d21b63e8a" + }, + { + "type": "git", + "url": "https://github.com/shenh10/HuggingArch", + "commit": "e69d20a028e5b17524aa48b53bddf8b9aad5d15b", + "revision_precision": "full", + "license": "MIT", + "observed_at": "2026-11-10", + "paths": [ + "docs/inference_cost_model.md", + "docs/evaluation_model.md", + "docs/symbolic_evaluation.md", + "docs/design.md", + "docs/parallelism.md", + "docs/kv_cache_storage.md", + "docs/attention_families.md", + "docs/moe_expert_axis.md", + "docs/quantization.md", + "docs/validation.md", + "docs/measured_calibration.md", + "docs/known_limitations.md", + "README.md", + "backend/inference/row_roofline.py", + "backend/inference/phases.py", + "backend/inference/phase_formulas.py", + "backend/arch/eval/binding.py", + "backend/arch/eval/transforms.py", + "backend/arch/eval/fusion.py", + "backend/inference/framework_bindings/__init__.py", + "backend/arch/layout/weight_endpoints.py", + "backend/arch/layout/layout.py", + "backend/arch/layout/workload.py", + "backend/arch/layout/physical.py", + "backend/arch/layout/comm_volume.py", + "backend/inference/comm_cost.py", + "backend/arch/eval/cache.py", + "backend/arch/eval/formats.py", + "backend/arch/dtypes.py", + "backend/arch/validate/_axioms.py", + "backend/arch/validate/_orchestrator.py", + "backend/arch/validate/_type_contracts.py", + "backend/inference/sol_closure.py", + "backend/inference/op_calibration.py", + "backend/inference/calibration_overlay.py", + "backend/measure/lookup.py" + ], + "identity": "references/huggingarch-source-identity.json", + "readset": "references/huggingarch-model-sol.md", + "note": "Cited paths only; the identity file records every retrieved file, its digests and its inspection scope, including files read but not cited. performance-ceiling-analysis keeps its own earlier pin for the checkpoint anchor." + } + ], + "applicability": { + "scope": "Model-level prefill and decode speed-of-light analysis for decoder-only (optionally multimodal) inference under a declared parallel layout; extends performance-ceiling-analysis L1 from one operation to a whole model without replacing its evidence rules", + "hardware": "any; per-dtype peaks, memory bandwidth and link bandwidths must be supplied with sources", + "prerequisites": "Model config and forward source at a pinned revision, the checkpoint's tensor headers where a checkpoint exists, the serving framework release that will run, and the layout and workload; reading the skill does not authorize execution", + "input_contract": "Model config, forward source and checkpoint headers; serving framework and release with source anchors for every fusion; per-world parallel degrees, ranks per node and node count; batch, input, output, prefix and verify tokens, and the measured expert load skew when expert placement makes per-rank work depend on routing; per-dtype compute peaks at the sustained clock, memory and link bandwidths with sources; any launch floor or link latency labelled as an assumption", + "produced_artifact": "A per-phase table with per-op counts and binding resource, per-resource totals, the conditional bound and its binding resources, the serial per-op estimate, headline TTFT, TPOT and throughput figures each labelled bound or estimate, every anchor and gate result, assumptions and unknowns; analytical only, not a measured result", + "failure_modes": [ + "The serial per-op sum is reported as a bound, or used to reject a faster measurement", + "Counts come from the unfused graph, overstating launches and activation round-trips, or from fusions the framework does not run, understating bytes", + "A degree that does not divide a weight is silently replaced by a divisor that does", + "Expert load skew is left at its default, making routed time and exchange optimistic", + "A windowed layer is priced as global, or a dense layer as windowed, because the cache growth law was not checked", + "Prefill attention is counted as a full square rather than causal pairs", + "An unmeasured launch floor or link latency, or a spec-sheet peak below the sustained clock, enters the bound", + "A measured envelope replaces the analytical figure instead of sitting beside it" + ], + "refusal_point": "Stops when an anchor gate fails or cannot be judged, when a required peak, used fabric rate or required expert-parallel load skew is missing, or when weights plus one request's KV do not fit a rank. Unanchored fusion permits only a labelled unfused estimate when its counts are available." + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "The serial estimate assumes full compute/memory overlap within an op, no overlap between ops and no pipeline bubble. The source uses one link latency for every fabric.", + "Counts are only as good as the anchors and the framework binding behind them; behaviour that lives only in weights or custom runtime code is out of reach.", + "Decoder-only models, optionally multimodal; encoder-decoder models are out of scope.", + "Checkout-only local skill; no automatic execution or promotion.", + "Only declared references are required; other cross-skill links are navigation.", + "Historical revisions require a matching checkout or a retained store." + ], + "attribution": [ + { + "type": "git", + "url": "https://github.com/shenh10/HuggingArch", + "commit": "e69d20a028e5b17524aa48b53bddf8b9aad5d15b", + "revision_precision": "full", + "license": "MIT", + "observed_at": "2026-11-10", + "paths": [ + "docs/inference_cost_model.md", + "docs/evaluation_model.md", + "docs/symbolic_evaluation.md", + "docs/design.md", + "docs/parallelism.md", + "docs/kv_cache_storage.md", + "docs/attention_families.md", + "docs/moe_expert_axis.md", + "docs/quantization.md", + "docs/validation.md", + "docs/measured_calibration.md", + "docs/known_limitations.md", + "README.md", + "backend/inference/row_roofline.py", + "backend/inference/phases.py", + "backend/inference/phase_formulas.py", + "backend/arch/eval/binding.py", + "backend/arch/eval/transforms.py", + "backend/arch/eval/fusion.py", + "backend/inference/framework_bindings/__init__.py", + "backend/arch/layout/weight_endpoints.py", + "backend/arch/layout/layout.py", + "backend/arch/layout/workload.py", + "backend/arch/layout/physical.py", + "backend/arch/layout/comm_volume.py", + "backend/inference/comm_cost.py", + "backend/arch/eval/cache.py", + "backend/arch/eval/formats.py", + "backend/arch/dtypes.py", + "backend/arch/validate/_axioms.py", + "backend/arch/validate/_orchestrator.py", + "backend/arch/validate/_type_contracts.py", + "backend/inference/sol_closure.py", + "backend/inference/op_calibration.py", + "backend/inference/calibration_overlay.py", + "backend/measure/lookup.py" + ], + "identity": "references/huggingarch-source-identity.json", + "readset": "references/huggingarch-model-sol.md", + "note": "Cited paths only; the identity file records every retrieved file, its digests and its inspection scope, including files read but not cited. performance-ceiling-analysis keeps its own earlier pin for the checkpoint anchor." + } + ], + "empirical_validation": "not_run", + "atom": { + "when": {}, + "license": "Apache-2.0", + "permissions": { + "read": true, + "retain": true, + "redistribute": true + }, + "layer": "L3", + "source_span": { + "source_index": 0, + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis/SKILL.md", + "byte_range": [ + 0, + 23157 + ], + "sha256": "b7a2dc5cc051427b12e195652c20f7ee337326a6954a44f811f8b06d21b63e8a" + } + } + }, + "content": { + "guide.md": { + "path": "playbooks/model-sol-analysis.md" + } + }, + "parts": { + "navigation": { + "skill_section": "navigation", + "layer": "L0", + "byte_range": [ + 0, + 337 + ], + "sha256": "e0c3d21ffaa6b20ac683b0daf0417d522fbea7dccbc402ca54bd15cd96fe5726" + }, + "decision": { + "skill_section": "decision", + "layer": "L1", + "byte_range": [ + 0, + 7995 + ], + "sha256": "4d84ede8c7cbbb215950c1519c6b55e7138bff2d77cd675077e3df6248e7e5c3" + }, + "procedure": { + "skill_section": "procedure", + "layer": "L2", + "byte_range": [ + 7995, + 23157 + ], + "sha256": "0ccf1f1d3068f93b19c19ca49414901da34070e5ab10b10f776da5706475318d" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/model-sol-analysis.qwen38-checkpoint.json b/src/inferrsi/knowledge/atoms/model-sol-analysis.qwen38-checkpoint.json new file mode 100644 index 000000000..5e2b928bf --- /dev/null +++ b/src/inferrsi/knowledge/atoms/model-sol-analysis.qwen38-checkpoint.json @@ -0,0 +1,75 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Model-level prefill and decode speed-of-light analysis for decoder-only (optionally multimodal) inference under a declared parallel layout; extends performance-ceiling-analysis L1 from one operation to a whole model without replacing its evidence rules", + "hardware": "any; per-dtype peaks, memory bandwidth and link bandwidths must be supplied with sources", + "prerequisites": "Model config and forward source at a pinned revision, the checkpoint's tensor headers where a checkpoint exists, the serving framework release that will run, and the layout and workload; reading the skill does not authorize execution", + "input_contract": "Model config, forward source and checkpoint headers; serving framework and release with source anchors for every fusion; per-world parallel degrees, ranks per node and node count; batch, input, output, prefix and verify tokens, and the measured expert load skew when expert placement makes per-rank work depend on routing; per-dtype compute peaks at the sustained clock, memory and link bandwidths with sources; any launch floor or link latency labelled as an assumption", + "produced_artifact": "A per-phase table with per-op counts and binding resource, per-resource totals, the conditional bound and its binding resources, the serial per-op estimate, headline TTFT, TPOT and throughput figures each labelled bound or estimate, every anchor and gate result, assumptions and unknowns; analytical only, not a measured result", + "failure_modes": [ + "The serial per-op sum is reported as a bound, or used to reject a faster measurement", + "Counts come from the unfused graph, overstating launches and activation round-trips, or from fusions the framework does not run, understating bytes", + "A degree that does not divide a weight is silently replaced by a divisor that does", + "Expert load skew is left at its default, making routed time and exchange optimistic", + "A windowed layer is priced as global, or a dense layer as windowed, because the cache growth law was not checked", + "Prefill attention is counted as a full square rather than causal pairs", + "An unmeasured launch floor or link latency, or a spec-sheet peak below the sustained clock, enters the bound", + "A measured envelope replaces the analytical figure instead of sitting beside it" + ], + "refusal_point": "Stops when an anchor gate fails or cannot be judged, when a required peak, used fabric rate or required expert-parallel load skew is missing, or when weights plus one request's KV do not fit a rank. Unanchored fusion permits only a labelled unfused estimate when its counts are available." + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "The serial estimate assumes full compute/memory overlap within an op, no overlap between ops and no pipeline bubble. The source uses one link latency for every fabric.", + "Counts are only as good as the anchors and the framework binding behind them; behaviour that lives only in weights or custom runtime code is out of reach.", + "Decoder-only models, optionally multimodal; encoder-decoder models are out of scope.", + "Checkout-only local skill; no automatic execution or promotion.", + "Only declared references are required; other cross-skill links are navigation.", + "Historical revisions require a matching checkout or a retained store." + ], + "empirical_validation": "not_run", + "title": "Read and verify public metadata for the pinned Qwen checkpoint on explicit request.", + "attribution": [], + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis/scripts/qwen38_checkpoint.py", + "sha256": "bc022056cad77941987a4f79647c0890ada808f7f0129522d137f51bcc16b1b7" + } + ], + "id": "model-sol-analysis.qwen38-checkpoint", + "kind": "knowledge", + "entrypoint": "qwen38_checkpoint.py", + "atom": { + "when": {}, + "license": "Apache-2.0", + "permissions": { + "read": true, + "retain": true, + "redistribute": true + }, + "layer": "L3", + "source_span": { + "source_index": 0, + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis/scripts/qwen38_checkpoint.py", + "byte_range": [ + 0, + 4234 + ], + "sha256": "bc022056cad77941987a4f79647c0890ada808f7f0129522d137f51bcc16b1b7" + } + } + }, + "content": { + "qwen38_checkpoint.py": { + "path": "playbooks/model-sol-analysis/scripts/qwen38_checkpoint.py" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/model-sol-analysis.qwen38-h200-tp4-calculator.json b/src/inferrsi/knowledge/atoms/model-sol-analysis.qwen38-h200-tp4-calculator.json new file mode 100644 index 000000000..7bfa46a6f --- /dev/null +++ b/src/inferrsi/knowledge/atoms/model-sol-analysis.qwen38-h200-tp4-calculator.json @@ -0,0 +1,75 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Model-level prefill and decode speed-of-light analysis for decoder-only (optionally multimodal) inference under a declared parallel layout; extends performance-ceiling-analysis L1 from one operation to a whole model without replacing its evidence rules", + "hardware": "any; per-dtype peaks, memory bandwidth and link bandwidths must be supplied with sources", + "prerequisites": "Model config and forward source at a pinned revision, the checkpoint's tensor headers where a checkpoint exists, the serving framework release that will run, and the layout and workload; reading the skill does not authorize execution", + "input_contract": "Model config, forward source and checkpoint headers; serving framework and release with source anchors for every fusion; per-world parallel degrees, ranks per node and node count; batch, input, output, prefix and verify tokens, and the measured expert load skew when expert placement makes per-rank work depend on routing; per-dtype compute peaks at the sustained clock, memory and link bandwidths with sources; any launch floor or link latency labelled as an assumption", + "produced_artifact": "A per-phase table with per-op counts and binding resource, per-resource totals, the conditional bound and its binding resources, the serial per-op estimate, headline TTFT, TPOT and throughput figures each labelled bound or estimate, every anchor and gate result, assumptions and unknowns; analytical only, not a measured result", + "failure_modes": [ + "The serial per-op sum is reported as a bound, or used to reject a faster measurement", + "Counts come from the unfused graph, overstating launches and activation round-trips, or from fusions the framework does not run, understating bytes", + "A degree that does not divide a weight is silently replaced by a divisor that does", + "Expert load skew is left at its default, making routed time and exchange optimistic", + "A windowed layer is priced as global, or a dense layer as windowed, because the cache growth law was not checked", + "Prefill attention is counted as a full square rather than causal pairs", + "An unmeasured launch floor or link latency, or a spec-sheet peak below the sustained clock, enters the bound", + "A measured envelope replaces the analytical figure instead of sitting beside it" + ], + "refusal_point": "Stops when an anchor gate fails or cannot be judged, when a required peak, used fabric rate or required expert-parallel load skew is missing, or when weights plus one request's KV do not fit a rank. Unanchored fusion permits only a labelled unfused estimate when its counts are available." + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "The serial estimate assumes full compute/memory overlap within an op, no overlap between ops and no pipeline bubble. The source uses one link latency for every fabric.", + "Counts are only as good as the anchors and the framework binding behind them; behaviour that lives only in weights or custom runtime code is out of reach.", + "Decoder-only models, optionally multimodal; encoder-decoder models are out of scope.", + "Checkout-only local skill; no automatic execution or promotion.", + "Only declared references are required; other cross-skill links are navigation.", + "Historical revisions require a matching checkout or a retained store." + ], + "empirical_validation": "not_run", + "title": "Replay the fixed Qwen3.8-Flash-Next BF16 / H200 SXM TP4 paper analysis.", + "attribution": [], + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis/scripts/qwen38_h200_tp4.py", + "sha256": "0265ee13d9ca354745af261b35682b674b8c3f68538a3bf8ceead34b70724f84" + } + ], + "id": "model-sol-analysis.qwen38-h200-tp4-calculator", + "kind": "knowledge", + "entrypoint": "qwen38_h200_tp4.py", + "atom": { + "when": {}, + "license": "Apache-2.0", + "permissions": { + "read": true, + "retain": true, + "redistribute": true + }, + "layer": "L3", + "source_span": { + "source_index": 0, + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis/scripts/qwen38_h200_tp4.py", + "byte_range": [ + 0, + 15468 + ], + "sha256": "0265ee13d9ca354745af261b35682b674b8c3f68538a3bf8ceead34b70724f84" + } + } + }, + "content": { + "qwen38_h200_tp4.py": { + "path": "playbooks/model-sol-analysis/scripts/qwen38_h200_tp4.py" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/model-sol-analysis.qwen38-h200-tp4-inputs.json b/src/inferrsi/knowledge/atoms/model-sol-analysis.qwen38-h200-tp4-inputs.json new file mode 100644 index 000000000..baf0cb5a0 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/model-sol-analysis.qwen38-h200-tp4-inputs.json @@ -0,0 +1,75 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Model-level prefill and decode speed-of-light analysis for decoder-only (optionally multimodal) inference under a declared parallel layout; extends performance-ceiling-analysis L1 from one operation to a whole model without replacing its evidence rules", + "hardware": "any; per-dtype peaks, memory bandwidth and link bandwidths must be supplied with sources", + "prerequisites": "Model config and forward source at a pinned revision, the checkpoint's tensor headers where a checkpoint exists, the serving framework release that will run, and the layout and workload; reading the skill does not authorize execution", + "input_contract": "Model config, forward source and checkpoint headers; serving framework and release with source anchors for every fusion; per-world parallel degrees, ranks per node and node count; batch, input, output, prefix and verify tokens, and the measured expert load skew when expert placement makes per-rank work depend on routing; per-dtype compute peaks at the sustained clock, memory and link bandwidths with sources; any launch floor or link latency labelled as an assumption", + "produced_artifact": "A per-phase table with per-op counts and binding resource, per-resource totals, the conditional bound and its binding resources, the serial per-op estimate, headline TTFT, TPOT and throughput figures each labelled bound or estimate, every anchor and gate result, assumptions and unknowns; analytical only, not a measured result", + "failure_modes": [ + "The serial per-op sum is reported as a bound, or used to reject a faster measurement", + "Counts come from the unfused graph, overstating launches and activation round-trips, or from fusions the framework does not run, understating bytes", + "A degree that does not divide a weight is silently replaced by a divisor that does", + "Expert load skew is left at its default, making routed time and exchange optimistic", + "A windowed layer is priced as global, or a dense layer as windowed, because the cache growth law was not checked", + "Prefill attention is counted as a full square rather than causal pairs", + "An unmeasured launch floor or link latency, or a spec-sheet peak below the sustained clock, enters the bound", + "A measured envelope replaces the analytical figure instead of sitting beside it" + ], + "refusal_point": "Stops when an anchor gate fails or cannot be judged, when a required peak, used fabric rate or required expert-parallel load skew is missing, or when weights plus one request's KV do not fit a rank. Unanchored fusion permits only a labelled unfused estimate when its counts are available." + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "The serial estimate assumes full compute/memory overlap within an op, no overlap between ops and no pipeline bubble. The source uses one link latency for every fabric.", + "Counts are only as good as the anchors and the framework binding behind them; behaviour that lives only in weights or custom runtime code is out of reach.", + "Decoder-only models, optionally multimodal; encoder-decoder models are out of scope.", + "Checkout-only local skill; no automatic execution or promotion.", + "Only declared references are required; other cross-skill links are navigation.", + "Historical revisions require a matching checkout or a retained store." + ], + "empirical_validation": "not_run", + "title": "Pinned Qwen model and H200 TP4 scenario inputs", + "attribution": [], + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis/references/qwen38-h200-tp4.json", + "sha256": "e7a8648c2a9b2dde4dee3f360dd256508fe15ee9867d4a7be3b9f4e889259a6c" + } + ], + "id": "model-sol-analysis.qwen38-h200-tp4-inputs", + "kind": "knowledge", + "entrypoint": "qwen38-h200-tp4.json", + "atom": { + "when": {}, + "license": "Apache-2.0", + "permissions": { + "read": true, + "retain": true, + "redistribute": true + }, + "layer": "L3", + "source_span": { + "source_index": 0, + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis/references/qwen38-h200-tp4.json", + "byte_range": [ + 0, + 2964 + ], + "sha256": "e7a8648c2a9b2dde4dee3f360dd256508fe15ee9867d4a7be3b9f4e889259a6c" + } + } + }, + "content": { + "qwen38-h200-tp4.json": { + "path": "playbooks/model-sol-analysis/references/qwen38-h200-tp4.json" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/model-sol-analysis.qwen38-h200-tp4.json b/src/inferrsi/knowledge/atoms/model-sol-analysis.qwen38-h200-tp4.json new file mode 100644 index 000000000..2888b7141 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/model-sol-analysis.qwen38-h200-tp4.json @@ -0,0 +1,75 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Model-level prefill and decode speed-of-light analysis for decoder-only (optionally multimodal) inference under a declared parallel layout; extends performance-ceiling-analysis L1 from one operation to a whole model without replacing its evidence rules", + "hardware": "any; per-dtype peaks, memory bandwidth and link bandwidths must be supplied with sources", + "prerequisites": "Model config and forward source at a pinned revision, the checkpoint's tensor headers where a checkpoint exists, the serving framework release that will run, and the layout and workload; reading the skill does not authorize execution", + "input_contract": "Model config, forward source and checkpoint headers; serving framework and release with source anchors for every fusion; per-world parallel degrees, ranks per node and node count; batch, input, output, prefix and verify tokens, and the measured expert load skew when expert placement makes per-rank work depend on routing; per-dtype compute peaks at the sustained clock, memory and link bandwidths with sources; any launch floor or link latency labelled as an assumption", + "produced_artifact": "A per-phase table with per-op counts and binding resource, per-resource totals, the conditional bound and its binding resources, the serial per-op estimate, headline TTFT, TPOT and throughput figures each labelled bound or estimate, every anchor and gate result, assumptions and unknowns; analytical only, not a measured result", + "failure_modes": [ + "The serial per-op sum is reported as a bound, or used to reject a faster measurement", + "Counts come from the unfused graph, overstating launches and activation round-trips, or from fusions the framework does not run, understating bytes", + "A degree that does not divide a weight is silently replaced by a divisor that does", + "Expert load skew is left at its default, making routed time and exchange optimistic", + "A windowed layer is priced as global, or a dense layer as windowed, because the cache growth law was not checked", + "Prefill attention is counted as a full square rather than causal pairs", + "An unmeasured launch floor or link latency, or a spec-sheet peak below the sustained clock, enters the bound", + "A measured envelope replaces the analytical figure instead of sitting beside it" + ], + "refusal_point": "Stops when an anchor gate fails or cannot be judged, when a required peak, used fabric rate or required expert-parallel load skew is missing, or when weights plus one request's KV do not fit a rank. Unanchored fusion permits only a labelled unfused estimate when its counts are available." + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "The serial estimate assumes full compute/memory overlap within an op, no overlap between ops and no pipeline bubble. The source uses one link latency for every fabric.", + "Counts are only as good as the anchors and the framework binding behind them; behaviour that lives only in weights or custom runtime code is out of reach.", + "Decoder-only models, optionally multimodal; encoder-decoder models are out of scope.", + "Checkout-only local skill; no automatic execution or promotion.", + "Only declared references are required; other cross-skill links are navigation.", + "Historical revisions require a matching checkout or a retained store." + ], + "empirical_validation": "not_run", + "title": "Qwen3.8-Flash-Next on four H200 SXM GPUs", + "attribution": [], + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis/references/qwen38-h200-tp4.md", + "sha256": "5b310fc546522f71dc882eff4f44df490955735474bc3d165a36e89556059749" + } + ], + "id": "model-sol-analysis.qwen38-h200-tp4", + "kind": "knowledge", + "entrypoint": "qwen38-h200-tp4.md", + "atom": { + "when": {}, + "license": "Apache-2.0", + "permissions": { + "read": true, + "retain": true, + "redistribute": true + }, + "layer": "L3", + "source_span": { + "source_index": 0, + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis/references/qwen38-h200-tp4.md", + "byte_range": [ + 0, + 7855 + ], + "sha256": "5b310fc546522f71dc882eff4f44df490955735474bc3d165a36e89556059749" + } + } + }, + "content": { + "qwen38-h200-tp4.md": { + "path": "playbooks/model-sol-analysis/references/qwen38-h200-tp4.md" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis.md b/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis.md new file mode 100644 index 000000000..18fc95487 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis.md @@ -0,0 +1,417 @@ +--- +name: model-sol-analysis +description: Walk a whole model to per-phase (prefill, decode) speed-of-light figures under a declared parallel layout - anchored counts, the fused graph the framework runs, per-rank geometry, explicit communication and KV growth laws - and report a resource-total bound apart from a serial per-op estimate. +metadata: + inferrsi: | + { + "schema_version": 1, + "profile": "local-skill-v1", + "kind": "skill", + "status": "candidate", + "origin": [ + "external" + ], + "empirical_validation": "not_run", + "tags": [ + "performance", + "roofline", + "speed-of-light", + "parallelism", + "kv-cache", + "inference" + ], + "sources": [ + { + "type": "git", + "url": "https://github.com/shenh10/HuggingArch", + "commit": "e69d20a028e5b17524aa48b53bddf8b9aad5d15b", + "revision_precision": "full", + "license": "MIT", + "observed_at": "2026-11-10", + "paths": [ + "docs/inference_cost_model.md", + "docs/evaluation_model.md", + "docs/symbolic_evaluation.md", + "docs/design.md", + "docs/parallelism.md", + "docs/kv_cache_storage.md", + "docs/attention_families.md", + "docs/moe_expert_axis.md", + "docs/quantization.md", + "docs/validation.md", + "docs/measured_calibration.md", + "docs/known_limitations.md", + "README.md", + "backend/inference/row_roofline.py", + "backend/inference/phases.py", + "backend/inference/phase_formulas.py", + "backend/arch/eval/binding.py", + "backend/arch/eval/transforms.py", + "backend/arch/eval/fusion.py", + "backend/inference/framework_bindings/__init__.py", + "backend/arch/layout/weight_endpoints.py", + "backend/arch/layout/layout.py", + "backend/arch/layout/workload.py", + "backend/arch/layout/physical.py", + "backend/arch/layout/comm_volume.py", + "backend/inference/comm_cost.py", + "backend/arch/eval/cache.py", + "backend/arch/eval/formats.py", + "backend/arch/dtypes.py", + "backend/arch/validate/_axioms.py", + "backend/arch/validate/_orchestrator.py", + "backend/arch/validate/_type_contracts.py", + "backend/inference/sol_closure.py", + "backend/inference/op_calibration.py", + "backend/inference/calibration_overlay.py", + "backend/measure/lookup.py" + ], + "identity": "references/huggingarch-source-identity.json", + "readset": "references/huggingarch-model-sol.md", + "note": "Cited paths only; the identity file records every retrieved file, its digests and its inspection scope, including files read but not cited. performance-ceiling-analysis keeps its own earlier pin for the checkpoint anchor." + } + ], + "applicability": { + "scope": "Model-level prefill and decode speed-of-light analysis for decoder-only (optionally multimodal) inference under a declared parallel layout; extends performance-ceiling-analysis L1 from one operation to a whole model without replacing its evidence rules", + "hardware": "any; per-dtype peaks, memory bandwidth and link bandwidths must be supplied with sources", + "prerequisites": "Model config and forward source at a pinned revision, the checkpoint's tensor headers where a checkpoint exists, the serving framework release that will run, and the layout and workload; reading the skill does not authorize execution", + "input_contract": "Model config, forward source and checkpoint headers; serving framework and release with source anchors for every fusion; per-world parallel degrees, ranks per node and node count; batch, input, output, prefix and verify tokens, and the measured expert load skew when expert placement makes per-rank work depend on routing; per-dtype compute peaks at the sustained clock, memory and link bandwidths with sources; any launch floor or link latency labelled as an assumption", + "produced_artifact": "A per-phase table with per-op counts and binding resource, per-resource totals, the conditional bound and its binding resources, the serial per-op estimate, headline TTFT, TPOT and throughput figures each labelled bound or estimate, every anchor and gate result, assumptions and unknowns; analytical only, not a measured result", + "failure_modes": [ + "The serial per-op sum is reported as a bound, or used to reject a faster measurement", + "Counts come from the unfused graph, overstating launches and activation round-trips, or from fusions the framework does not run, understating bytes", + "A degree that does not divide a weight is silently replaced by a divisor that does", + "Expert load skew is left at its default, making routed time and exchange optimistic", + "A windowed layer is priced as global, or a dense layer as windowed, because the cache growth law was not checked", + "Prefill attention is counted as a full square rather than causal pairs", + "An unmeasured launch floor or link latency, or a spec-sheet peak below the sustained clock, enters the bound", + "A measured envelope replaces the analytical figure instead of sitting beside it" + ], + "refusal_point": "Stops when an anchor gate fails or cannot be judged, when a required peak, used fabric rate or required expert-parallel load skew is missing, or when weights plus one request's KV do not fit a rank. Unanchored fusion permits only a labelled unfused estimate when its counts are available." + }, + "recommendations": [ + "Anchor weights, shapes and KV growth before pricing any count, and treat an unjudged gate as a failure.", + "Price the post-fusion graph the serving framework runs at its pinned release, with a source anchor for every fusion.", + "Report the resource-total bound and the serial per-op estimate in separate columns; only the bound may reject a result.", + "Keep unmeasured launch floors and link latencies out of the bound, as labelled assumptions in the estimate.", + "Keep measured kernel times beside the analytical figure, joined by physical identity rather than model or framework name." + ], + "verification": { + "locally_verified": false, + "evidence_level": "source_grounded", + "note": "Derived from a reviewed external implementation at a pinned commit (references/huggingarch-model-sol.md, identity in references/huggingarch-source-identity.json); claims read from executable code and claims stated only in the project's prose, docstrings included, are marked separately there. The bundled pure helper composes supplied counts only and is covered by synthetic tests; no accelerator, model or source-project run was used, and no predicted figure has been compared with a measurement." + }, + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "The serial estimate assumes full compute/memory overlap within an op, no overlap between ops and no pipeline bubble. The source uses one link latency for every fabric.", + "Counts are only as good as the anchors and the framework binding behind them; behaviour that lives only in weights or custom runtime code is out of reach.", + "Decoder-only models, optionally multimodal; encoder-decoder models are out of scope." + ], + "provenance_readsets": [ + "references/huggingarch-model-sol.md", + "references/huggingarch-source-identity.json", + "references/model-sol-contract.md", + "references/model-sol-example.json", + "references/qwen38-h200-tp4.md", + "references/qwen38-h200-tp4.json" + ], + "consumption_mode": "packaged" + } +--- + +# Model-level speed-of-light analysis + +Status: candidate; `empirical_validation: not_run`. Reading this skill does not +authorize execution; follow the current task's scope. + +## When to use this skill + +Use it to answer model-level ceiling questions before building or tuning +anything: + +- What is the prefill and decode ceiling of model M under layout L on card H? +- Is a requested TTFT or TPOT physically plausible at this batch and context? +- Which resource binds decode at context length s, and does it move with s? +- How do two layouts compare analytically? + +This skill extends [performance-ceiling-analysis](../performance-ceiling-analysis/SKILL.md). +That owner's L1 helper prices one device, one operation class and one traffic +tier, and its contract states that it does not walk a model, sum devices or +compose stages. This skill does the model walk and keeps that owner's evidence +rules. + +Do not use it for: + +- benchmarking built candidates: use `rsi-evidence` and the AB/BA harness; +- queueing, admission or percentile SLO prediction: use + [calibrate-serving-simulation](../calibrate-serving-simulation/SKILL.md); +- one operation's roofline: use `performance-ceiling-analysis`; +- weight loading mechanics: use + [weight-loading-optimization](../../optimization/weight-loading-optimization/SKILL.md). + +## Inputs + +Gather these before any arithmetic. Mark a missing item unknown; do not borrow a +default from a paper or another card. + +- **Model:** config and forward source at a pinned revision. Also the + checkpoint's tensor headers, or an explicit statement that none exists. +- **Framework:** the serving framework and the release that will actually run. + Its fusions and dispatch choices determine which graph is priced. +- **Layout:** per-world degrees (tensor, context, expert, pipeline, data), plus + ranks per node and node count. +- **Workload:** batch; input, output and prefix tokens; speculative verify + tokens. For expert parallelism, supply measured load skew `ρ` to price the + busiest rank. For pure TP with identically routed expert shards, price the + same selected tokens on every rank and state the distinct-expert assumption. +- **Hardware:** per-dtype dense compute peak, memory bandwidth, and intra- and + inter-node link bandwidth, each with its source and the clock it assumes. Use + the clock the device actually runs that work at: a spec sheet computed at a + lower clock understates the peak, and a measured row will then beat the + "bound". Record a launch floor or link latency only as a labelled assumption + unless it was measured. + +## Procedure + +### 1. Anchor the counts before pricing them + +A floor computed from wrong counts is wrong in a way no roofline step detects. +Pass every gate below, or stop and report which gate failed. A gate that could +not be judged counts as a failure. + +1. **Weights.** Run the two gates in + [checkpoint anchoring](../performance-ceiling-analysis/references/huggingarch-checkpoint-anchor.md): + the bidirectional per-tensor join, then the per-rank weight ledger. + `join_checkpoint` in the helper does the join and its byte checksum. A clean + byte total alone is not a pass. +2. **Shapes.** Every op's input shapes must match what it declares, and every + split or merged dimension must multiply back. A byte total that happens to + match does not excuse a graph whose tensors do not compose. +3. **KV type.** Every attention component names its cache family. Every decode + attention path either stores per-token entries or carries a recurrent state. +4. **KV growth.** For each cached tensor, state its storage law. Check it by + letting the context grow without bound: a per-token tensor must grow, a + windowed one must cap, and a constant state must not depend on the context. A + window in the model config must show up as a capped tensor. `kv_cache_bytes` + in the helper applies the laws. + + Use `global` for full-context MHA, GQA, MQA and MLA when they retain one + entry per position. Use the stored KV head widths for MHA/GQA/MQA and the + stored latent plus any retained positional-key bytes for MLA. Use `window` + for a proven fixed sliding window, `compressed` for a proven + `ceil(context / ratio)` stored-position law, `complete_groups` for a full + row only after each group closes (account for the tail separately), and `constant` for proven + fixed-size recurrent state. Split hybrid layers by state component. Other + layouts and cache growth laws require separate evidence. + +### 2. Bind each phase before walking the graph + +- **Prefill:** `s_query = input − prefix`, `s_kv = input`. +- **Decode:** `s_query` = verified tokens per step `k` (1 without + speculation). `s_kv` = the cache length in question plus `k − 1`. If you use + the average over the generation (`input + output/2`) as the cache length, say + so: the time at the mean length is not the mean time when an op switches its + binding resource along the way. +- **Attention work:** count causal pairs, + `s_pairs = s_query·(s_kv − s_query) + s_query(s_query+1)/2`, not `s²`. +- **Serving form:** use each component's actual form for the phase, such as + absorbed MLA at decode. + +### 3. Price the graph the framework runs + +- Apply the serving framework's fusions at its pinned release. Every fusion + needs a source anchor (`path:line` at that release) and evidence it applies to + the declared device and layout. When patterns overlap, resolve them by a + fixed, stated order. +- Derive traffic from the fused graph's boundaries. A fused kernel's traffic is + not the sum of its members' traffic. +- Know both failure directions. An unfused walk overstates launches and + activation round-trips. Fusion the framework does not actually run + understates bytes. +- Use the minimum evidenced demand for each resource across the admissible + variants of the declared layout. If an unresolved fusion could reduce that + demand, mark the affected bound `INSUFFICIENT_EVIDENCE`. An unfused graph + with known counts can still provide a labelled serial estimate. +- Model a dispatch condition only when it changes bytes or the main kernel path + in common deployments. Otherwise bill the default path and state that + assumption. + +### 4. Evaluate per rank, from per-rank shapes + +- Derive each rank's work from its own shapes, not from a divisor table. Data + parallelism divides no work: the step time is per replica group. +- Declare, per stored axis, which parallel world splits each weight. For a + degree that does not divide the part count, use the declared policy: refuse, + let a group of ranks co-own each shard (`gcd(parts, degree)` ways), or pad to + whole parts. Never substitute a divisor that divides. Price a padded rank at + its padded width. +- **MoE:** expert parallelism distributes whole experts. The busiest rank + receives `(ρ + (k−1)(E−ρ)/(E−1)) / k` times the mean routed rows, for `k` local + experts out of `E`. This assumes one hot expert. Without a measured `ρ`, the + routed time is optimistic: report it as unknown, not as `ρ = 1`. +- **Context parallelism:** state which scheme cuts query rows, which cuts keys, + and whether it divides KV at all. +- **Precision:** take bytes from the stored format (packing and scale siblings + included). Take compute from the MMA width the framework launches. These are + two different widths. + +### 5. Make communication explicit + +- Insert a collective wherever the sharding state changes: + - partial to full: all-reduce; + - sharded to replicated: all-gather; + - MoE shuffle: all-to-all; + - pipeline cut: send/receive. +- **Bytes per rank and hops** depend on the algorithm the framework picks for + the payload. Name it: + + | Algorithm | Hops | Bytes per rank (tensor `T`, `N` ranks) | + |---|---|---| + | Library default (ring bytes, log-depth hops) | `ceil(log2 N)`, doubled for all-reduce | `(N−1)/N·T`, doubled for all-reduce | + | One-shot all-reduce | 1 | `(N−1)·T` | + | Two-shot all-reduce | 2 | `2(N−1)/N·T` | + | In-switch reduction (NVLink SHARP) | 2 | `(N−1)/N·T` | + | Point-to-point | 1 | `T` | + + For the bound, use the fewest bytes among the algorithms the framework and + fabric admit, since any of them could run. +- **Time:** bytes over the bandwidth of the link the collective crosses, plus + hops × link latency. A node-spanning all-reduce can run hierarchically: + intra-node reduce-scatter, inter-node all-reduce on the shard, intra-node + all-gather. This needs more than one rank per node and a world that divides + evenly by it. State which schedule you assume. +- A transfer needs an evidenced topology and finite positive bandwidth for + each fabric that carries bytes. An unavailable rate on such a fabric yields + `INSUFFICIENT_EVIDENCE`. Omit the transfer + only when the layout establishes no transfer, for example a one-rank world. +- The latency term and any launch floor go into the serial estimate only, + never into the bound. Label them as assumptions unless they were measured. + +### 6. Compose the phase + +Use `phase_floors` in the helper, or apply the same arithmetic by hand: + +- **Conditional bound.** For each resource, total per-rank irreducible demand + over its peak rate; take the maximum across resources. This is a lower bound + only when the counts cannot be reduced by any permitted variant, such as a + collective algorithm moving fewer bytes, and every rate is a peak at the clock + the device actually runs that work at. Only a qualified peak-based bound may + reject a result for that layout. +- **Serial estimate.** + `Σ_op max(t_compute, t_memory, Σ_phases t_link + hops × latency, launch floor)`, + with the counts the framework actually runs. The maximum assumes full + compute/memory overlap within each op, and the sum assumes no overlap between + ops. The phases of one collective run one after another, so their link times add. A + stack that overlaps kernels or hides communication under compute can finish + below it, so it can only flag a faster result. It can never reject one. +- Record the counts the selected graph actually runs in `demand`. For a phase + bound, explicitly supply `bound_demand` for every positive demand and cite + why that amount is unavoidable for the layout. A missing proof leaves the + affected resource total and phase bound unknown. The scheduled counts still + support a serial estimate. Use one op per collective, with each link phase + assigned to the link it crosses. +- **Pipeline parallelism:** one microbatch's latency is the stages plus the + inter-stage hops, with no bubble modelled. Say so. +- **Capacity first:** if weights plus one request's KV do not fit a rank, + publish no time for that layout. + +### 7. Report headline figures with their labels + +- **TTFT:** the prefill step. +- **TPOT:** the decode step, divided by `1 + α·K` under speculation with + acceptance `α` and `K` drafts. The decode step must then include the draft's + forward passes. +- **Decode throughput:** effective tokens per step over the decode step. Under + speculation this count is fractional. + +Each figure carries its label (bound or estimate), its phase binding, its +layout and its unknowns. + +### 8. Calibrate beside the model, never over it + +- Join measured kernel times by physical identity: op signature, shapes, dtypes, + device and phase. Do not join by model or framework name. +- Keep the analytical and measured columns side by side. +- Rescale a row measured under different peaks by the ratio for the resource it + saturated. With no known peak, do not rescale. +- Apply the rules in [the two-threshold rule](../performance-ceiling-analysis/references/huggingarch-checkpoint-anchor.md#which-bound-may-reject-a-measurement-the-two-threshold-rule): + - A row claiming more work per second than its own recorded peak contradicts + itself. Correct its numerator or peak, then check it again. + - A row faster than a separately computed roofline is flagged, and both sides + are re-derived. +- If the collectives were not measured, a phase containing one has no complete + measured total. + +## Output + +Produce a per-phase table with: + +- per-op rows: counts, per-resource time and binding resource; +- per-resource totals; +- the conditional bound with its binding resource or resources; +- the serial estimate; +- headline figures; +- every anchor and gate result; +- assumptions and unknowns. + +Keep the bound and the estimate in separate columns. Never print an unlabelled +"SOL". + +## Failure and stop conditions + +- An anchor gate fails or cannot be judged: stop and name the gate. +- A fusion lacks a source anchor: report an unfused serial estimate if its + counts are known. Withhold the bound if the unresolved fusion could reduce + its demand. +- A per-dtype peak, a used link bandwidth or a required expert-parallel skew `ρ` is missing: + the result is `INSUFFICIENT_EVIDENCE`, not a default. +- The serial estimate is called a bound, or used to reject a measurement: + correct the label before reporting. +- Capacity fails for the layout: publish no time. +- A measured envelope is treated as a bound: it is evidence about one stack, not + a physical limit. + +## Known gaps + +The source method does not model: + +- inter-kernel overlap, multi-stream execution or the pipeline bubble; +- per-fabric link latencies; +- generic compiler fusion it cannot anchor; +- behaviour that lives only in weights or custom runtime code. + +It covers decoder-only models, optionally multimodal. Details and markers are in +the [source reading](references/huggingarch-model-sol.md). + +## Helper + +[`scripts/model_sol.py`](scripts/model_sol.py) is pure: JSON in, JSON out, and +no I/O, network or device access. Its inputs, outputs and limits are in the +[helper contract](references/model-sol-contract.md), with a synthetic +[example](references/model-sol-example.json). + +- `join_checkpoint(header, inventory)`: the bidirectional join, per-name + element and byte comparison, and the byte checksum. +- `kv_cache_bytes(layers, context_tokens)`: stored KV per sequence by growth law, + with boundedness as the context grows. +- `phase_floors(phase, hardware)`: the conditional bound, binding resources, + serial estimate and per-op rows for one phase step. + +Each function reports missing evidence as unknowns and returns +`INSUFFICIENT_EVIDENCE` rather than guessing. Malformed data raises +`ValueError`. + +For rates taken from a hardware datasheet, use `source.kind = "datasheet"`. +The reference time prices the specified workload at those nominal rates. +The qualified bound stays unavailable until the actual clock basis is known. +The [Qwen3.8-Flash-Next H200 TP4 worked example](references/qwen38-h200-tp4.md) +includes an offline replay and an optional public checkpoint-header audit. + +## Resource contract + +[`references/huggingarch-model-sol.md`](references/huggingarch-model-sol.md) +records the source method with per-claim markers, and +[`references/huggingarch-source-identity.json`](references/huggingarch-source-identity.json) +records the pinned commit, per-file digests and inspection scope. The checkpoint +anchor and the two-threshold rule stay with `performance-ceiling-analysis`; this +owner links to them. Candidate guidance; no local measurement. diff --git a/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/references/huggingarch-model-sol.md b/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/references/huggingarch-model-sol.md new file mode 100644 index 000000000..93713a89b --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/references/huggingarch-model-sol.md @@ -0,0 +1,327 @@ +# HuggingArch: model-level speed-of-light method, source reading + +Status: candidate; `empirical_validation: not_run`. This document records what one +external project does to turn a model, a layout and a card into per-phase +speed-of-light times, read at one pinned commit and recorded in +[`huggingarch-source-identity.json`](huggingarch-source-identity.json). The +procedure in [`SKILL.md`](../SKILL.md) is derived from it. Claims carry one of +two markers: + +- `[code]` — verified in executable code (statements, constants, signatures) of + a file inspected at that commit; +- `[doc]` — stated only in the project's own prose: its documentation, or a + docstring or comment in an inspected source file. Where the behaviour lives in + a file that was not inspected, the claim is `[doc]` even if a docstring in an + inspected file describes it. + +A parenthesised locator names the file, section or symbol behind the marker. +Documentation paths are under `docs/`, code paths under `backend/`. Where this +document interprets rather than reports, the text says so. + +Use the earlier HuggingArch pin for the checkpoint join and per-rank weight +ledger, and this document's pin for graph composition and calibration. Of the +12 files in the anchor's readset, nine match byte for byte across the pins, +including the join and weight-ledger implementations. The changed files are +`docs/measured_calibration.md`, `docs/parallelism.md` and +`backend/inference/op_calibration.py`. The code change replaces the memoization +decorator on four identity helpers. [Checkpoint anchor](../../performance-ceiling-analysis/references/huggingarch-checkpoint-anchor.md) · [Upstream comparison](https://github.com/shenh10/HuggingArch/compare/facbbbc96856e558b9084a94a5070b2e2c86cf0b...e69d20a028e5b17524aa48b53bddf8b9aad5d15b) + +## 1. What the source calls SOL + +- Each fused leaf row takes the maximum of four alternative times: compute + (FLOPs over the compute peak), memory (weight read, metadata and activation + bytes over bandwidth), communication (bytes over link bandwidth plus a link + latency) and a launch floor `[code]` (`inference/row_roofline.py`, + `build_row_exprs`). That the compute peak is the one for the row's + activation dtype is stated in the module docstring `[doc]`. +- A phase step is the serial sum of those rows `[code]` (`inference/phases.py`, + `t_sol = step.total(...)`; `inference/phase_formulas.py`, `STEP_SOL_LAW` + "Σ_leaf max(t_compute, t_memory, t_comm, t_launch)"). +- The source states the assumption behind the sum: "Rows are serial: the step is + the sum of its rows, and no compute hides a collective or another kernel's + launch" `[doc]` (`inference_cost_model.md`, "The roofline: four bounds per op"). +- It rejects the model-level form `max(Σ flops / peak, Σ bytes / bw)` as "the + tempting shortcut" that "*under-counts* the true time", and states that the + per-op sum lies between the largest component sum and the sum of all four + `[doc]` (same file, "Why SOL is a per-op sum, not a model-level max"). +- It calls the result "an upper bound — the *speed of light*, not a promised + latency" and conditions that on the peak being a real bound: "the card's dense + peak at the clock it actually runs tensor-core work at, not the clock a spec + sheet is computed at" `[doc]` (same file, "Calibration: from peak to + achievable"). The project describes its latency as "a planning envelope, not a + benchmark" `[doc]` (`README.md`, Scope). + +The source also states the other side of that trade. Next to the serial sum, +a code comment says the whole-step `max(F/Fp, B/Bp)` "assumes perfect overlap +across every kernel in the model, so it is a bound and not an estimate" `[doc]` +(`inference/phases.py`, `estimate_phase` comment). It publishes the per-op sum +as its SOL. The skill reports both: the resource-total maximum as the bound, +and the per-op sum, which a stack that overlaps kernels or hides a collective +under compute can beat, as a serial estimate. + +## 2. Binding a phase before the walk + +- Prefill binds `s_query = input − prefix` and `s_kv = input`. Decode binds + `s_query` to the verified tokens per step `k`, and `s_kv` to a cache length + plus `k − 1`. The cache length is the explicit one when given, otherwise the + average over the generation, `input + output/2`; the `k − 1` applies to both + `[code]` (`arch/eval/transforms.py`, `Phase.resolve`). +- Attention work is counted in exact causal pairs: + `s_past = s_kv − s_query` and `s_pairs = s_query·s_past + s_query(s_query+1)/2` + `[code]` (`arch/eval/binding.py`, `STEP_LAWS`). +- Each component's serving form for the phase, such as absorbed MLA at decode, + is swapped in before the walk, because the absorbed form has a cost of its own + `[doc]` (`inference_cost_model.md`, "Two phases: prefill and decode"; + `Phase.substitute` docstring). +- A phase without per-op rows raises instead of falling back, and a deployment + without capacity publishes no time `[code]` (`inference/phases.py`, + `estimate_phase`). +- Headline figures: TTFT is the prefill step; TPOT is the decode step divided by + `1 + α·K` under speculation; decode throughput is effective tokens per step + over the decode step `[doc]` (`inference_cost_model.md`, "From per-step time + to the headline numbers"). +- Under pipeline parallelism a step is one microbatch's latency: the stages in + sequence plus the inter-stage handoff, with the fill/drain bubble not modelled + `[doc]` (`inference/phases.py`, `estimate_phase` comments and note string). The + summing itself happens in a part of the calibration overlay that was not + inspected. + +## 3. Which graph is priced + +- The per-op sum is taken over the post-fusion leaves, and traffic is + re-derived from the rewritten graph's boundaries rather than summed over the + fused members `[doc]` (`inference_cost_model.md`, "Fusion: collapsing memory + round-trips"; `evaluation_model.md`, Layers). The traffic derivation itself is + in a file not inspected. +- Fusions come from a binding for the serving framework, not from a generic + registry. Larger patterns are applied first, and overlapping matches resolve + "first wins" `[code]` (`inference/framework_bindings/__init__.py`, load sort and + `_pattern_specificity`; `arch/eval/fusion.py`, `rewrite`). +- Every implementation entry needs a source anchor in the framework's code, of + the form `path[:line[-line]]`, and every binding records the release it was + read at as `{repo, tag, commit}` `[code]` (`_append_op_implementation`, + `SourceAnchor.parse`, `_audited_at`). +- The two failure directions are named. An unfused walk "OVERSTATES launches and + activation round-trips" `[doc]` (`inference_cost_model.md`, "What the silence + costs"). Registry fusion the framework does not run was "hiding intermediate + HBM materialization" `[doc]` (`arch/eval/fusion.py`, `Framework` docstring). +- A dispatch condition is modelled only when it changes bytes or the main kernel + path and triggers under common deployments; otherwise the default path is + billed and the assumption stated `[doc]` (`inference_cost_model.md`, "How + precisely to model a dispatch condition"). Where a framework does redundant + work, the graph models the better form `[doc]` (same file, "Activation + epilogues follow their consumer"). +- Generic compiler fusion that cannot be anchored to source stays unmodelled; + the source reports its measured share of bytes as small in its own corpus and + states when to reopen the question `[doc]` (same file, "Inductor's generic + fusion: measured, then left unmodelled"). + +## 4. Per-rank geometry + +- Per-rank work follows from per-rank shapes, not from a per-op divisor table, + and data parallelism "never divides work": the step time is per replica group + `[doc]` (`inference_cost_model.md`, "Placement: per-rank shapes, not + divisors"; `parallelism.md`, per-rank cost). +- Each stored weight declares, per stored axis, which parallel world splits it. + A degree that does not divide the axis's part count follows the declared + policy: `exact` refuses, `replica_cells` splits `gcd(parts, degree)` ways and + lets ranks co-own each shard, and `pad` pads each shard to whole parts `[code]` + (`arch/layout/weight_endpoints.py`, `_placement_layout`). A padded extent is + rounded up to the shard quantum `[code]` (`arch/layout/layout.py`, + `Block.padded_global_extent`), and the pricing reads that padded width `[doc]` + (`Block.valid_counts_per_shard` docstring, "the uneven≈pad assumption"). +- Context parallelism changes whose work a rank holds. The pair share a rank + computes is the ratio of local to global causal pairs `[code]` + (`arch/layout/physical.py`, `pairs_share`); which scheme cuts query rows and + which cuts keys is `[doc]` (its docstring, `parallelism.md`). +- MoE expert parallelism distributes whole experts, and the expert count must + be a multiple of the route-group size `[code]` (`arch/layout/workload.py`, + `_check_route_group`). + The busiest rank carries `(ρ + (k−1)(E−ρ)/(E−1)) / k` times the mean routed + rows, for `k` local experts out of `E` and a measured expert load skew `ρ` + `[code]` (`busiest_rank_load_factor`), under a single-hot-expert assumption + `[doc]` (its docstring). Leaving `ρ` at its default makes routed time and + exchange optimistic by roughly the busiest rank's excess `[doc]` + (`known_limitations.md` §1.1). +- Storage and compute precision are separate. Weight bytes are parameters + divided by the packing factor times the storage width, plus scale siblings + `[code]` (`arch/eval/formats.py`, `TensorFormat.weight_bytes_for`, + `bytes_for`). The served width of a plain float wider than 16 bits is taken as + BF16 `[code]` (`arch/dtypes.py`, `served_dtype`). A compute pin narrower than + its weight is refused `[doc]` (`quantization.md`, deployment precision). +- An MLA latent has no head axis, so tensor parallelism replicates it and + raising the TP degree does not shrink its KV `[doc]` (`parallelism.md`, + cases; `attention_families.md`, MLA). + +## 5. Communication + +- Collectives are grafted where the sharding state changes between producer + and consumer: a partial result needs an all-reduce, a sharded-to-replicated + edge an all-gather, the MoE shuffle an all-to-all, and a pipeline cut a + send/receive `[doc]` (`parallelism.md`, "Communication is injected, and + first-class"). The materializer was not inspected. +- Per-rank bytes are the tensor's bytes times a ring factor: `(N−1)/N`, doubled + for all-reduce, and 1 for point-to-point. Latency hops are `ceil(log2 N)`, + doubled for all-reduce, and 1 for point-to-point `[code]` + (`arch/layout/comm_volume.py`, `ring_factor`, `latency_hops`). +- Each phase of a collective costs its bytes over the fabric bandwidth plus the + link latency times its hops `[code]` (`inference/comm_cost.py`, + `price_collective`). Bandwidths come from the card's intra- and inter-node + peak columns `[code]` (`Fabric.of`). +- A node-spanning collective is priced hierarchically only when its op is + scheduled that way, more than one member sits on each node and the world + divides evenly by that count; everything else runs one inter-node ring + `[code]` (`collective_phases`). +- The ring factor is not universal. The framework's all-reduce algorithm is + chosen by payload from its binding `[code]` (`comm_cost.py`, + `collective_ladder`), and each algorithm has its own hops and bytes per rank + `[code]` (`comm_volume.py`, `ALGORITHMS`): + + | Algorithm | Hops | Bytes per rank | + |---|---|---| + | one-shot | 1 | `(N−1)·T` | + | two-shot | 2 | `2(N−1)/N·T` | + | NVLink SHARP | 2 | `(N−1)/N·T` | + | library default | `latency_hops` | ring factor | +- The link latency and the launch floor are fixed defaults that the source + itself calls estimates until measured `[doc]` (`inference/defaults.py` + comments; `inference_cost_model.md`). One link latency serves every fabric, + "a deliberate simplification" `[doc]` (same file). Collectives are not + measured `[doc]` (`known_limitations.md` §4.8). + +## 6. KV accounting + +- The unit is the cached node, each sized by its own storage law and dtype; + "There is no single 'KV bytes per token'" for a layer with several cached + tensors `[doc]` (`kv_cache_storage.md`, "The unit of accounting"). +- A cached tensor's bytes are its per-position bytes, data plus dynamic scales, + times its positions at the cache length, divided by the ranks that share those + positions `[code]` (`arch/eval/cache.py`, `CachedTensor.bytes_at`, + `position_bytes`). A tensor without a law stores the full length `[code]` + (`positions_at`). Storage and read laws are separate fields `[code]`. +- Three storage laws: per-token (grows without bound), windowed + (`Min(s_kv, s_window)`) and constant state. A compressor stores + `ceil(s_kv / ratio)` `[doc]` (`kv_cache_storage.md`, "Three storage laws", + "Where the number comes from"). Per-family layouts for dense, MLA, + sliding-window, DSA, compressed-attention and linear or state-space layers are + `[doc]` (`attention_families.md`). +- Boundedness is judged by substituting `s_kv → ∞` into each stored length: a + per-token tensor must grow, a windowed one must cap and a constant state must + have no free `s_kv` `[code]` (`arch/validate/_axioms.py`, `_storage_is_bounded`, + `_kv_growth`). A windowed family needs every growing tensor capped and at least + one growing `[code]` (`_window_contract`). A positive configured window with no + capped tensor fails unless the config disables windowing or the spec declares + an exemption `[code]` (`_check_config_windowing`). +- The window gate reads stored lengths, not FLOPs, because a windowed and a + global component emit identical attention FLOPs `[doc]` + (`arch/validate/_type_contracts.py` docstring; `validation.md` §5.3). +- Sparse reads bill each selected row per query: exact for distinct requests, + an upper bound under a shared prefix `[doc]` (`cache.py`, `gathered_bytes` + docstring). + +## 7. Gates before a number is published + +- A spec is valid only with no gating errors `[code]` + (`arch/validate/_orchestrator.py`, `_evaluate_spec`). Shape and dimension-map + mismatches, the storage-byte checksum (zero tolerance), packing, the weight + ledger, KV type contracts, KV growth claims and the window contracts all gate + `[code]` (`_gating_errors`). +- Uncertainty is not a pass. A claim that cannot be judged is reported as a + gating finding, a crash in a gating check fails the gate, and an analysis + replay skipped because earlier gates failed is reported `not_run`, never + `passed` `[code]` (`_axioms.py` unjudged findings; `_guarded`; + `_downstream`). +- The replay checks that per-row bytes add up to the row's access and that the + rows add up to the phase's FLOPs, access and writes, as exact integers `[code]` + (`inference/sol_closure.py`). It does not check that per-op times add up to the + phase time. +- The verification classes: per-op axioms (A), conservation (B), perturbation + invariants (C), type contracts (D) and dual-path cross-checks (E). Class A + "cannot verify itself", and "Rules marked *not implemented* provide no coverage + and must not be counted" `[doc]` (`validation.md` §8–14). +- To anchor a per-op axiom: read the framework or model source, compute one + layer by hand, diff the engine per axis, and fix the abstraction rather than + adding a per-model case `[doc]` (`validation.md` §9.2). + +## 8. Measured envelope, beside the roofline + +- A measured row is keyed by op signature, projected shape, dtype environment, + device and phase, not by framework, model or deployment `[code]` + (`inference/op_calibration.py`, `PhysicalKey`). +- `envelope` mode takes the fastest row at a key after peak-drift scaling; + `latest` takes the framework's exact declared kernel at its newest measured + release, and reports ambiguous or missing instead of substituting `[code]` + (`physical_time_for`, `latest_time_for`, `select_time`). +- A row measured under different peaks is rescaled by the ratio of the bound it + saturated; without a known compute peak the ratio is 1 `[code]` + (`_peak_drift_scaled_latency_us`, `_compute_drift`). +- A row is flagged as an anomaly when its latency falls below a fixed fraction + of the roofline computed at the row's own test-time peaks and the caller's + numerators, and the measured value is never clamped `[code]` + (`ANOMALY_THRESHOLD`, `_roofline_at_test_us`, `_build_measured_timing`). +- The calibration overlay keeps the roofline as the op time `[code]` + (`inference/calibration_overlay.py`, `CalibrationOverlay.apply`); measured + times are published beside it, "never overwriting it" `[doc]` (`inference_cost_model.md`, + calibration). +- Envelope selection does not filter on the numeric cross-check, so a row never + cross-checked can win `[code]` (`physical_time_for`). +- No configured service, a working service and a failing service are three + distinct outcomes; a failure is not an empty answer `[code]` + (`measure/lookup.py`). +- A measured total is all-or-nothing, and because collectives are not + measured, a deployment's measured total "cannot be complete whenever it + contains a collective" `[doc]` (`known_limitations.md` §2.3, §4.8). + +## 9. Stated limits + +All `[doc]` unless marked: + +- No inter-kernel overlap and no pipeline bubble (sections 1 and 2 above). +- One weight placement per spec can under-bill a framework's weight read and + over-bill one all-gather (`known_limitations.md` §1.3). +- Disabled providers can leave the envelope slower than the fastest kernel a + framework runs (§4.9). +- Behaviour "that lives only in weights or custom runtime code is out of reach" + (`README.md`, Scope). +- Scope is decoder-only, optionally multimodal; encoder-decoder and + mixture-of-depth models are out (`design.md` §1.4). +- Shape checks "prove the tensors compose, not that the graph computes what + `forward()` computes" (`design.md` §2.3). + +## 10. Where this skill departs from the source + +- **Labels.** The source publishes the serial per-op sum as its SOL; it is + reported here as the serial estimate. The resource-total maximum, which the + source's own comment calls a bound, is reported as the conditional bound + (section 1). +- **Unmeasured terms.** The link latency, which adds to a collective's byte + time, and the launch floor enter the estimate only, as stated assumptions, + never the bound. +- **Peaks.** A bound needs the peak at the clock the device actually runs that + work at, as the source requires; a spec sheet computed at a lower clock is + not one. A measurement above the peak means the peak definition is wrong. +- **Collective bytes in the bound.** The bound takes the fewest bytes among the + algorithms the framework and fabric admit, since any of them could run. +- **Decode at an average length.** Evaluating decode at the average cache + length gives the time at the mean length, not the mean time. These differ + when an op changes its binding resource during the generation (this + document's inference). +- **Attention work.** Causal pairs count about half of `seq²` in prefill. The + `seq²` formula in `performance-ceiling-analysis` is given for DiT, whose + attention is bidirectional, where it is right. Applied to causal LLM prefill + it would overstate attention work by about 2× (this document's inference); + that skill is not changed here. +- **Tool vocabulary.** The source's spec format, field names, default + constants, framework line citations and model-specific figures are not carried + over. + +## 11. What this reference does not establish + +- No local execution of any kind: no accelerator, no model and no run of the + source project. +- No comparison of a predicted serving figure with a measured one exists in + the inspected scope. +- The source's measured corpus and its figures are not reproduced or cited as + facts. +- Files not inspected are listed in the identity record; behaviour that lives + in them is `[doc]` above. diff --git a/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/references/huggingarch-source-identity.json b/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/references/huggingarch-source-identity.json new file mode 100644 index 000000000..d5757cf4e --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/references/huggingarch-source-identity.json @@ -0,0 +1,358 @@ +{ + "schema_version": 1, + "subject": "HuggingArch model-level speed-of-light method: phase binding, fused-graph pricing, per-rank geometry, communication, KV accounting, publication gates and measured envelope", + "consumed_by": "huggingarch-model-sol.md", + "required_resources": [ + "huggingarch-source-identity.json", + "huggingarch-model-sol.md" + ], + "sources": [ + { + "type": "git", + "repository": "https://github.com/shenh10/HuggingArch", + "commit": "e69d20a028e5b17524aa48b53bddf8b9aad5d15b", + "revision_precision": "full", + "commit_date": "2026-11-10T04:13:16Z", + "license": "MIT", + "observed_at": "2026-11-10", + "method": "GitHub API tree listing at the pinned commit for blob identity and size; raw file retrieval at the same commit, hashed locally; every git blob and size matched the tree listing. A complete file hash does not imply complete semantic inspection; per-file scope is stated below. Code was read, never executed.", + "repository_history": { + "default_branch_head_at_observation": "e69d20a028e5b17524aa48b53bddf8b9aad5d15b", + "commits_on_default_branch": 41, + "root_commit": "facbbbc96856e558b9084a94a5070b2e2c86cf0b", + "note": "The root commit supplies the checkpoint join and per-rank weight ledger used by performance-ceiling-analysis. The later commit supplies this playbook's model-walk and calibration claims.", + "anchor_readset_comparison": { + "checked_at": "2026-11-23", + "files_compared": 12, + "different_blobs": [ + "backend/inference/op_calibration.py", + "docs/measured_calibration.md", + "docs/parallelism.md" + ] + } + }, + "files": [ + { + "path": "docs/inference_cost_model.md", + "git_blob": "ebaed29491d49efbfa15c61a4cd6a3bd61f8d726", + "bytes": 45984, + "sha256": "1bdf615083e620ea22899fed41baa698fbb89cedf55db5b5e8d6fbcac9568372", + "inspection": "Read in full. Cited for the per-op sum and its no-overlap statement, the rejected model-level maximum, fusion and dispatch-condition rules, placement, headline figures and calibration." + }, + { + "path": "docs/evaluation_model.md", + "git_blob": "304eb9c8cd8ff7c27587bbe7042246f373d5f5e7", + "bytes": 13653, + "sha256": "a62578fbf17302e0bf6a85a7692d881ea6cd1ee19beed59202a80be1d330b53a", + "inspection": "Read in full. Cited for re-deriving traffic from the rewritten graph." + }, + { + "path": "docs/symbolic_evaluation.md", + "git_blob": "8d5a1736aa9569e087610b1ee5b4035df3d7da2a", + "bytes": 10391, + "sha256": "cc0fe9eb50c9824f444354ca18be2d5cd36a662413dceb16f4e6f097d6c41e84", + "inspection": "Read in full. Workload counts as symbols; not cited directly." + }, + { + "path": "docs/design.md", + "git_blob": "769d8245df93ec6fa324c1dd120e3043d17079da", + "bytes": 69617, + "sha256": "e6bc05cf505eef17d2d8130b621adf918c3dd941be9286798155f99a56990111", + "inspection": "Read in full except sections 6, 7.1, 7.3 and 8, which were skimmed (spec generation pipeline, UI pages, naming contract). Cited for scope (1.4) and the limit of shape checks (2.3)." + }, + { + "path": "docs/parallelism.md", + "git_blob": "f53b8d6982b231e407dc550cc7d4f24f0062efbd", + "bytes": 24272, + "sha256": "e0e2e2f6e9e7166be64c565adf035e92b575fc38e830d2132fc9f90b91bf7758", + "inspection": "Read in full; the terminology table was skimmed. Cited for per-rank cost, sharding states, injected communication and the MLA case." + }, + { + "path": "docs/kv_cache_storage.md", + "git_blob": "79f410488e5f8a01eaef2e05d60a8d5b16803d5c", + "bytes": 17413, + "sha256": "efa62049ab4705fcdea33092533e99010062c2cf3cb6daf29f57d512995de368", + "inspection": "Read in full. Cited for the per-node unit of accounting and the storage laws." + }, + { + "path": "docs/attention_families.md", + "git_blob": "49483e5a0ffe72d42315d9f95a94c7b144c190df", + "bytes": 10122, + "sha256": "092cb4acd70381f73ec7cb9c93b69ca81d5ffa4a629ae5a8150f64c07dd2a190", + "inspection": "Read in full. Cited for per-family KV layouts and the MLA replication case." + }, + { + "path": "docs/moe_expert_axis.md", + "git_blob": "4ec71306f07d309ee5670cb38d4d032b54322cb7", + "bytes": 10291, + "sha256": "f24b07f5aa26dbbc15745389b5b47eda469ca41cd8ce2cfa629c0e8aa83e2018", + "inspection": "Read in full. Background for the expert axis; claims cited from code instead." + }, + { + "path": "docs/quantization.md", + "git_blob": "26237b2933c25297ef17ead845fcef5ca39f78d6", + "bytes": 21028, + "sha256": "3a920b9ad281605a9d9fc3be5fd1dedf3ced5d03cbf648c9a508ddcc61e3a434", + "inspection": "Read in full. Cited for the refusal of a compute pin narrower than its weight." + }, + { + "path": "docs/validation.md", + "git_blob": "27ad32471db8c39937e04196a46fd3826a68def3", + "bytes": 37659, + "sha256": "917131e52bca569c9742efeba77606e2f102678acd9dccba06c593a833c9b800", + "inspection": "Read in full. Cited for the window gate rationale (5.3), the verification classes (8-14) and the axiom anchoring procedure (9.2)." + }, + { + "path": "docs/measured_calibration.md", + "git_blob": "711cf37d353a49ac79e9952af8eed377ac959e79", + "bytes": 65150, + "sha256": "111936275fe1bfe524a17f9c4fbe75adf35d3204ebf0ea97620739c79adda65b", + "inspection": "Sections 1-3, 4.1-4.4, 6.3 and 7 read in full; 4.5-6.2 and 8 skimmed (storage, service and deployment operations). Background for the measured envelope; claims cited from code instead." + }, + { + "path": "docs/known_limitations.md", + "git_blob": "4480f090cf338c4868832e6e25c34583e9085558", + "bytes": 29268, + "sha256": "0317f9edf17755bb58006130ed9fbfbabf4375d68d79fa744f811c7e9159172d", + "inspection": "Read in full, every section body. Cited for 1.1, 1.3, 2.3, 4.8 and 4.9." + }, + { + "path": "README.md", + "git_blob": "21872c5f74237ecac17ad05d196932e657326205", + "bytes": 5552, + "sha256": "e9430d93c8edc9fd37a2160957137345a889eacb8489515074d9899cc50ebf1f", + "inspection": "Read in full. Cited for the scope statements." + }, + { + "path": "docs/README.md", + "git_blob": "c37d2a930d2e01d2b6d72e92d5900083fadd9c74", + "bytes": 6149, + "sha256": "9518dba944e780d5ce3c352a537bbf7450baae6d152fabc273f7628625f641f5", + "inspection": "Read in full. Not cited." + }, + { + "path": "CLAUDE.md", + "git_blob": "ef25df9db5cf0402eb7d183e51f2a97479be5ddd", + "bytes": 36158, + "sha256": "84c509416ccdaa0a56af89da49aea46249029e895e136b0a8967791e850faf60", + "inspection": "Sections 1-4 read as data only; this is the upstream project's instruction file for its own agents. Not cited." + }, + { + "path": "docs/auto_sweep.md", + "git_blob": "3a27378220f0c936ded1edf3d57950432869e46a", + "bytes": 39192, + "sha256": "c7f10baec6f9aafb9d2d43167e39fe3d2522f9510fbe101ddbc712c2d310257a", + "inspection": "Retrieved and hashed; not inspected. Not cited." + }, + { + "path": "docs/custom_models.md", + "git_blob": "72a6372787d95f559ed45da473a1d40234e9debb", + "bytes": 8358, + "sha256": "676c9588697ec81b501bd7d2d04a48d3a77a5ef5ebcd98c5719214a7884fcc9f", + "inspection": "Retrieved and hashed; not inspected. Not cited." + }, + { + "path": "docs/deployment.md", + "git_blob": "11a804e501fcb8dbcf8836a3200184c9db49e3ed", + "bytes": 12953, + "sha256": "22c11e7e30e6cfe532db9bafdf5a7e3f5787d80f7f9a646cf1b503f4821b90ab", + "inspection": "Retrieved and hashed; not inspected. Not cited." + }, + { + "path": "backend/inference/row_roofline.py", + "git_blob": "bf2fc28dbf36bbc3fa88cfb3f714fb275ff68a20", + "bytes": 76456, + "sha256": "8bfd62044ab48ef6485a07d0481cbee9e0e3b145109cc3308f379c8b7154a3f4", + "inspection": "Module docstring L1-60, build_row_exprs L508-581, RowTimes.bound L196-200, BOUNDS L205, FloorForm L1217-1272, StepSum.total L1501-1510." + }, + { + "path": "backend/inference/phases.py", + "git_blob": "0a606298b8ee2fe0317407046931e7739b7396b9", + "bytes": 117002, + "sha256": "86a048c2db0b2e19af8848a0af8c099289c92c7cf60981bfcc5e37398c9f55b0", + "inspection": "Module docstring L1-26, phase-binding helper L220-285, estimate_phase L680-720 and L800-920 (serial sum, capacity branch, pipeline branch)." + }, + { + "path": "backend/inference/phase_formulas.py", + "git_blob": "f0a035c65ab25cc5582d05bcacd241ccdadb3b59", + "bytes": 57663, + "sha256": "3ab3a014af13ed27b33bbd8c66ed2fc4bd00bb7d04cd2b7aa1139b99c81827f7", + "inspection": "STEP_SOL_LAW (L964) only." + }, + { + "path": "backend/inference/defaults.py", + "git_blob": "a0499fe13d5cf018c7e1ae05861d43853da7ea9e", + "bytes": 2943, + "sha256": "302e9b412dc5832c4852db5d3f30ecaf67fe03ea4ba412c3468999371a0672e1", + "inspection": "L48-63: the launch floor and link latency defaults and their comments." + }, + { + "path": "backend/arch/eval/binding.py", + "git_blob": "bf4e40ecabda1875dc47864779ac80845383252b", + "bytes": 17961, + "sha256": "e8b89421e9753f70a075469f326b305af38e82d34b77bb673dd8811021d16767", + "inspection": "STEP_LAWS (L284-287) only." + }, + { + "path": "backend/arch/eval/transforms.py", + "git_blob": "3ca1ece24a69ce27950e74ec8237e361106302fb", + "bytes": 113479, + "sha256": "22ef87a5522026ac86f377d6f392966b389d9e44f049a218fdeddcf7939f8307", + "inspection": "Phase class and docstrings L340-432 (including substitute), Phase.resolve L434-486." + }, + { + "path": "backend/arch/eval/fusion.py", + "git_blob": "fccbc9e03f7a88cdcf39616c49f93368ec3e6f49", + "bytes": 107459, + "sha256": "0d7b005791b343f60e71aa921bd9f01352664e84baf63e4577857b1389ebee46", + "inspection": "rewrite L1224-1300, Framework L1464-1509, rebase_shapes docstring L2047-2066." + }, + { + "path": "backend/inference/framework_bindings/__init__.py", + "git_blob": "76ee283d0f50fb37e897927502574e2cea363387", + "bytes": 109043, + "sha256": "c89edac5f79bebd5a669fde6ee412fac34635cddf35167789d627895e109a127", + "inspection": "Module docstring L1-40, _pattern_specificity L108-140, SourceAnchor.parse L953-981, _audited_at L1700-1708, load sort L2076-2088, _append_op_implementation L2109-2136." + }, + { + "path": "backend/arch/layout/weight_endpoints.py", + "git_blob": "1c8a9bb176ca0ac6d61e27d1f0c60aa472e66b9f", + "bytes": 33260, + "sha256": "6c4bc967a53939b6278a151c33b28fe57718b8cbe2f7a7be195071a4a8a2c15d", + "inspection": "PlacementContext._placement_layout L564-707 and imports L18-32." + }, + { + "path": "backend/arch/layout/layout.py", + "git_blob": "ef3f17a140bd9009cd207a95375dc0c6c6e99cdd", + "bytes": 37430, + "sha256": "046a9b5a914fd8f5140dc8416b3ec088652cd04cca235391756cbe6a3a983ffe", + "inspection": "_exact_div and _divided L93-110, Block L182-270, block and sharded L539-560, local extents L621-634." + }, + { + "path": "backend/arch/layout/workload.py", + "git_blob": "1511a784d8873ecf8019d488f518085a72d8848f", + "bytes": 7972, + "sha256": "6c10bda338277a2ce659e28fdd2c555b8e740a72876d7793abb2a49d5e8fe958", + "inspection": "Read in full." + }, + { + "path": "backend/arch/layout/physical.py", + "git_blob": "8115295d17fbeccd62e3556db0316be28caf7ae5", + "bytes": 44863, + "sha256": "92de2d362331e9a1c981c25e761db34a5a8894628f67c0041c6c8446bf3b4261", + "inspection": "local_dims L417-450, pairs_share L752-786." + }, + { + "path": "backend/arch/layout/comm_volume.py", + "git_blob": "3b740bff597511343c87fc0242dbf1d1ad065412", + "bytes": 7439, + "sha256": "58d70e04249a3b9dea0c0742247450662bb2a15b625b5d66455f4d5a45b470c9", + "inspection": "Read in full." + }, + { + "path": "backend/inference/comm_cost.py", + "git_blob": "ad775f1d0e2eddd7ec7e66010484db0149e406e1", + "bytes": 20878, + "sha256": "647937f0e927385220eb342631ba0c970ef520867bacaa61b72d298a07b79d33", + "inspection": "Module docstring L1-34, Fabric L89-119, CollectiveRung L137-198, collective_ladder through collective_phases L201-478." + }, + { + "path": "backend/arch/eval/cache.py", + "git_blob": "23edad37781b65f50fddb2a636b863016a4ae116", + "bytes": 106145, + "sha256": "7b384cf8a9b47ebcc1ad7826f5d9c1adbcb264eca83730b8e0080fd2bb658a60", + "inspection": "positions_at L97-112, CacheGeometry L115-140, CachedTensor L143-339, Cache L342-405, derive through bind_format L410-502, _declared_formats through _sequence_shard L753-811, _per_position_elements and _law_for L1898-1961." + }, + { + "path": "backend/arch/eval/precision.py", + "git_blob": "90562db0b03f3913e29632ac9bf21f9176bc5cd4", + "bytes": 36774, + "sha256": "fda944ce91ba58109da49ef6bfa93c31260d72cbcf88237b88ebe6fd713aa258", + "inspection": "__init__ excerpt L55-76, cache_format and shipped_cache_format L556-576." + }, + { + "path": "backend/arch/dtypes.py", + "git_blob": "bc9e5b60c9466685cfc4f856d9c3a4e006593003", + "bytes": 22958, + "sha256": "b7a87bca6768c11280e7aa4d7cbc04306f58b27119af206c36ab3de6131802e7", + "inspection": "served_dtype L310-400." + }, + { + "path": "backend/arch/eval/formats.py", + "git_blob": "040073501f6cb3e7c02406d78fd7855a3564b18c", + "bytes": 65349, + "sha256": "55b0ea1038a9dfede3f9838164f5dd015e18c8a2c21f58c2865dc3df15d5f72e", + "inspection": "TensorFormat byte methods L293-331, FormatPolicy.for_node L889-952, _from_scheme head L954-1000." + }, + { + "path": "backend/arch/quant_schemes/__init__.py", + "git_blob": "e509411a1b197c4fbb481a61ea3db50eec80ad93", + "bytes": 41493, + "sha256": "cbaffb911b39842459e029fcb79030bbe847562b760eaa403b911e9362735840", + "inspection": "Searched only: _ALLOWED_PACKING_FACTORS (L46) and its check (L335-347). Not cited." + }, + { + "path": "backend/inference/op_calibration.py", + "git_blob": "7541b32972959443873694a619f07d5428546d47", + "bytes": 52795, + "sha256": "32576110c9724ad09d8afa7b2c19e24471b7c18e02870b859b0e638d6f8a3ff5", + "inspection": "Module docstring L1-31, ANOMALY_THRESHOLD L59, PhysicalKey L159-197, _Row and measured_utilization L307-392, _index_row and _resolve_physical_duplicate L474-625, L745-1180 (drift scaling, test-time roofline, measured timing, latest_time_for, physical_time_for, select_time)." + }, + { + "path": "backend/arch/validate/_orchestrator.py", + "git_blob": "f90e694a1f21499dfca90f4d08fb3838c548df03", + "bytes": 44081, + "sha256": "7ac96a0d4554b68948d7bd2b79e2277c053ef395d78161dcd7ffb7adfc8a080e", + "inspection": "L1-60, _guarded L217-232, _Checks L240-458, _gating_errors L506-608, validate L734-782, _downstream L785-800, _evaluate_spec L803-873." + }, + { + "path": "backend/arch/validate/_axioms.py", + "git_blob": "ad21ff3de8419c2c53a3bb98ebc77555361c6795", + "bytes": 25016, + "sha256": "be953f0c0f0fdc1da518d2fdd203c8f329ac18ff0ac6f2092f05a505f3575976", + "inspection": "Read in full." + }, + { + "path": "backend/arch/validate/_type_contracts.py", + "git_blob": "ecea3a7b3220ec93b11edc330daa589c4c5e4914", + "bytes": 5839, + "sha256": "cb02a1a17d4b47391834a747570ccc9449f96015df13fd6dbbe941bf76312e83", + "inspection": "Read in full." + }, + { + "path": "backend/measure/lookup.py", + "git_blob": "24136e0456497f2240d685b104acc74747627592", + "bytes": 14058, + "sha256": "59d57156b9c465ef912e6f92049a51164314a1a01c26f1dd118272045698c925", + "inspection": "L96-310: request, scope resolution and lookup outcomes." + }, + { + "path": "backend/inference/sol_closure.py", + "git_blob": "af38540c1d5b967cb1b33e22971bcf847cc14d2f", + "bytes": 4436, + "sha256": "1fdce0abf73697edc16601aab02e0c131bc62268da0c5f2545e8cdce30cb9047", + "inspection": "Read in full." + }, + { + "path": "backend/inference/calibration_overlay.py", + "git_blob": "4368103f2c2c18534da4b17be5237bf1251d5ad0", + "bytes": 54891, + "sha256": "cb5d4689e3d600edb34fe10e70b202a0c2f62b59b0b07e70db1596f67dfc9852", + "inspection": "CalibrationOverlay.apply L150-306 only." + } + ], + "not_inspected": [ + "backend/ beyond the files above, including the collective materializer, sharding propagation, parallel configuration, pipeline stages, traffic derivation, capacity, step evaluation and the invariant battery", + "kernel_bench/, tests/, web/, supabase/, tools/, scripts/", + "docs/auto_sweep.md, docs/custom_models.md, docs/deployment.md (hashed only)" + ] + } + ], + "verification": { + "locally_verified": false, + "empirical_validation": "not_run", + "native_execution": "not_run", + "evidence_level": "source_grounded", + "note": "The consuming document separates claims read from executable code ([code]) from claims stated only in the project's prose, docstrings included ([doc]). No accelerator was used, the source project was not run, and its measured corpus is neither reproduced nor cited as fact." + } +} diff --git a/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/references/model-sol-contract.md b/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/references/model-sol-contract.md new file mode 100644 index 000000000..9ecccf3b7 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/references/model-sol-contract.md @@ -0,0 +1,173 @@ +# `model_sol.py` contract + +The helper is pure arithmetic over supplied JSON. It reads no files, fetches +nothing, runs no device and grants no acceptance. Each function copies its +inputs, returns JSON-serializable data and leaves its inputs unchanged. + +Every result carries `analysis_status`: `COMPUTED`, or `INSUFFICIENT_EVIDENCE` +when evidence is missing or incompatible. Missing evidence is listed in +`unknowns`, and no unit is converted implicitly. The only default is an op's +`repeat` and a stored tensor's `copies`, both 1 when absent. Malformed data, such +as non-JSON values, counts below their minimum, non-finite numbers or non-text +keys, raises `ValueError`. Derived arithmetic outside the finite numeric range +also raises `ValueError`. Neither status is a campaign verdict. + +A link bandwidth is an evidence input. A positive transfer with a missing or +unusable bandwidth yields `INSUFFICIENT_EVIDENCE`. The helper accepts a Python +NaN or infinity specifically in a link's numeric `value` and records it as +JSON null in the returned hardware snapshot. Other inputs retain the finite +JSON requirement. + +A `source` object is `{kind, locator}`. The allowed kinds depend on the field: + +| Field | Allowed `kind` | +|---|---| +| checkpoint header | `measured` (read from the file) or `synthetic` | +| inventory, op demand, KV layer group | `derived`, `measured` or `synthetic` | +| hardware rate | `peak`, `synthetic` or `datasheet`. All rates in one call must share one kind. | +| link latency, launch floor | `measured`, `assumed` or `synthetic` | + +A `peak` rate also needs `clock_basis`: the clock the device actually runs that +work at, and where that comes from. A spec sheet computed at a lower clock than +the part sustains understates the peak, and a bound built on it can reject a +real result. + +## `join_checkpoint(header, inventory)` + +Inputs: + +- `header.tensors`: a map from verbatim header names to `{dtype, shape}`, + merged across shards. `__metadata__` is ignored. `dtype` uses safetensors codes + (`BF16`, `F8_E4M3`, `I32`, …); a packed format is priced at its container's + width. +- `inventory.tensors`: a list of `{name, dtype, shape, copies, buffer}`. + - A name segment `X` matches any all-digit segment, and the number of + segments must agree. + - Rows sharing a name are summed. + - `copies` counts stored tensors sharing that name; the default is 1. + - `buffer: true` marks a tensor computed at load, which may be absent from the + file. + +Both inputs require an explicit `shape`. An empty shape `[]` declares a +scalar. An absent or null shape leaves the affected counts unavailable. + +Outputs: + +- `unclaimed_header_tensors`: header tensors that no stored name selects. +- `multiply_claimed_header_tensors`: header tensors selected by more than one + distinct stored name. +- `absent_stored_names`: non-buffer stored names that select nothing. +- `matched`: per stored name, the header and inventory physical elements and + bytes, and their differences. +- `mismatched_names`: names whose element count or byte count differs. +- `byte_checksum`: header bytes against inventory bytes. Buffers count only when + the header stores them. An unknown size leaves the affected total and + equality flag null. +- `join_clean`: true only when the status is `COMPUTED`, both residuals are + empty, all matches agree and each header tensor is selected exactly once. + +The join is the gate; the byte checksum is only a checksum. Equal totals with a +non-clean join are expected when two submodules swap widths. + +## `kv_cache_bytes(layers, context_tokens)` + +Each layer group is `{name, layers, law, source, …}`. An empty or absent list +of groups, or a missing required field for a group's law, is an unknown. + +| `law` | Stored positions | Extra fields | Bounded as context grows | +|---|---|---|---| +| `global` | `s` | `bytes_per_position` | no | +| `window` | `min(window, s)` | `bytes_per_position`, `window` | yes | +| `compressed` | `ceil(s / ratio)` | `bytes_per_position`, `ratio` | no | +| `complete_groups` | `floor(s / ratio)` | `bytes_per_position`, `ratio`. Account for any open-group buffer separately. | no | +| `constant` | fixed state | `state_bytes` | yes | + +Outputs: per-group positions and bytes, `total_bytes` per sequence, and +`bounded_as_context_grows`, which is true only if every group is bounded. +Results are per sequence. Batch, paging granularity and per-rank head splits are +the caller's to apply, through `bytes_per_position` or a later multiplication. + +## `phase_floors(phase, hardware)` + +Inputs: + +- `phase`: `{phase, model_id, layout, hardware_id, tokens_per_step, assumptions, + ops}`, where `phase` is `prefill` or `decode`. `tokens_per_step` is a positive + number and may be fractional, for example effective tokens per step under + speculation. +- Each op: `{name, repeat, demand, bound_demand, link_latency_s, + launch_floor_s, source}`. + - `demand` maps a rate name to the per-rank amount the op actually moves or + computes, in FLOP for a compute rate and in bytes for a memory or link rate. + The helper cannot check that unit; the amount's source must state it. + - `bound_demand` declares counts known to be irreducible across the permitted + variants of this layout. Cite that evidence in the op's source, for example + the minimum traffic across all admissible collective algorithms. Each key + must occur in `demand`, with a value between zero and its scheduled amount. + Supply an explicit zero when it is the evidenced minimum for positive work. + An absent, empty or null map, an omitted key and a null value all leave + irreducibility unknown for the corresponding positive demand. A scheduled + count of zero already establishes a lower count of zero. + - Link amounts within one op add up: model one op per collective, with each + of its phases as a demand on the link that phase crosses. + - `link_latency_s` is `{value, source}` in seconds. It is the whole latency of + one instance of the op, already hops × per-hop latency summed over its + phases, and it adds once to the op's summed link time. With no link demand, + the latency alone is the op's link time. + - `launch_floor_s` is `{value, source}` in seconds, one more alternative time + for the op, not added to anything. + - An op may carry only a latency or a launch floor. +- `hardware`: `{hardware_id, assumptions, rates}`. Each rate is + `{resource, unit, value, source, clock_basis}`, where `resource` is `compute` + (`FLOP/s`), `memory` (`byte/s`) or `link` (`byte/s`). Units must match + exactly. Provide a valid rate for every fabric used by the declared + layout and schedule. A missing, non-finite or nonpositive link bandwidth + leaves timing and throughput unavailable for a positive transfer. A + single-rank schedule with zero bytes on that link needs no bandwidth + observation. The scheduled byte count is retained in both cases. + +Outputs: + +- `evidence_basis`: `peak`, `synthetic` or `datasheet` when all rates share that kind, else + null. +- `phase` and `tokens_per_step`: echoed from the input. +- `resource_totals` gives the sum of the evidenced lower counts × `repeat` + for each rate. A rate's total is null if any op using it lacks that evidence. +- `actual_resource_totals`: per rate, the sum of `demand × repeat`. +- `conditional_bound_s`: `max over rates (total / rate)`, with + `binding_resources` naming the rates that reach it. Latencies and launch + floors never enter it. It is a lower bound only if every demand is + irreducible for the permitted variants of the declared layout and every rate + is a peak at the clock the device actually runs that work at. Only a bound + meeting those conditions may reject a result. +- If only irreducibility evidence is missing with `peak` or `synthetic` rates, + the status is `INSUFFICIENT_EVIDENCE`. The phase bound, its binding resources + and its throughput are null. The helper still reports the serial estimate, + its throughput and per-op rows from the evidenced schedule. For example, + 400 scheduled bytes at 100 B/s give a 4 s serial estimate. Explicit evidence + for 100 irreducible bytes adds a 1 s bound for that single-resource example. +- `datasheet_resource_time_s` and `datasheet_binding_resources` carry the + resource-total calculation using `actual_resource_totals` at the vendor + specifications. This calculation needs only the schedule. In that mode + `conditional_bound_s`, `binding_resources` + and `tokens_per_s_at_bound` are null. The serial estimate uses the same + nominal rates. These reference times cannot reject an observation. +- `serial_estimate_s`: + `Σ_op repeat × max(compute and memory times, summed link time + latency, launch floor)`, + from `demand`. + It assumes full compute/memory overlap within an op and no overlap between + ops. It may flag a faster result. With the same counts and rate domains it + is never below the resource-total bound. +- `per_op`: each op's time and binding term: rate names (all of an op's link + rates when the link term binds), `link_latency` or `launch_floor`. +- `tokens_per_s_at_bound` and `tokens_per_s_at_serial_estimate`: + `tokens_per_step` over each positive time, or null when the time is zero or + unavailable. +- `assumptions`, `unknowns`, a copy of the `inputs`, and `limits`. + +The helper composes supplied per-rank counts only. Deriving the counts — fusion, +sharding, ring factors, hops, MoE load factors and KV growth — is the procedure's +job and is recorded with the counts' sources. It does not model queueing, +launches beyond supplied floors, synchronization or load imbalance beyond the +supplied counts. No achievable utilization, speedup, quality, goal acceptance or +end-to-end claim follows from its output. diff --git a/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/references/model-sol-example.json b/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/references/model-sol-example.json new file mode 100644 index 000000000..3c87421e0 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/references/model-sol-example.json @@ -0,0 +1,65 @@ +{ + "_comment": "Synthetic fixture for the helper's arithmetic and evidence boundaries. Not a model, device or measurement.", + "header": { + "source": {"kind": "synthetic", "locator": "hand-written fixture"}, + "tensors": { + "__metadata__": {"format": "pt"}, + "model.embed_tokens.weight": {"dtype": "BF16", "shape": [8, 4]}, + "model.layers.0.self_attn.qkv_proj.weight": {"dtype": "BF16", "shape": [12, 4]}, + "model.layers.1.self_attn.qkv_proj.weight": {"dtype": "BF16", "shape": [12, 4]}, + "model.layers.0.mlp.down_proj.weight": {"dtype": "F8_E4M3", "shape": [4, 16]}, + "model.layers.1.mlp.down_proj.weight": {"dtype": "F8_E4M3", "shape": [4, 16]}, + "model.layers.0.mlp.down_proj.weight_scale": {"dtype": "F32", "shape": [4]}, + "model.layers.1.mlp.down_proj.weight_scale": {"dtype": "F32", "shape": [4]}, + "lm_head.weight": {"dtype": "BF16", "shape": [8, 4]} + } + }, + "inventory": { + "source": {"kind": "synthetic", "locator": "hand-written fixture"}, + "tensors": [ + {"name": "model.embed_tokens.weight", "dtype": "BF16", "shape": [8, 4]}, + {"name": "model.layers.X.self_attn.qkv_proj.weight", "dtype": "BF16", "shape": [12, 4], "copies": 2}, + {"name": "model.layers.X.mlp.down_proj.weight", "dtype": "F8_E4M3", "shape": [4, 16], "copies": 2}, + {"name": "model.layers.X.mlp.down_proj.weight_scale", "dtype": "F32", "shape": [4], "copies": 2}, + {"name": "lm_head.weight", "dtype": "BF16", "shape": [8, 4]}, + {"name": "model.rotary_emb.inv_freq", "dtype": "F32", "shape": [2], "buffer": true} + ] + }, + "kv_layers": [ + {"name": "global attention", "layers": 1, "law": "global", "bytes_per_position": 16, + "source": {"kind": "synthetic", "locator": "hand-written fixture"}}, + {"name": "sliding-window attention", "layers": 1, "law": "window", "window": 4, "bytes_per_position": 16, + "source": {"kind": "synthetic", "locator": "hand-written fixture"}} + ], + "hardware": { + "hardware_id": "synthetic-device", + "assumptions": ["Synthetic rates chosen for hand calculation"], + "rates": { + "compute.bf16": {"resource": "compute", "unit": "FLOP/s", "value": 100, + "source": {"kind": "synthetic", "locator": "hand-written fixture"}}, + "memory.hbm": {"resource": "memory", "unit": "byte/s", "value": 10, + "source": {"kind": "synthetic", "locator": "hand-written fixture"}}, + "link.tp": {"resource": "link", "unit": "byte/s", "value": 5, + "source": {"kind": "synthetic", "locator": "hand-written fixture"}} + } + }, + "decode": { + "phase": "decode", + "model_id": "synthetic-model", + "layout": "tp2", + "hardware_id": "synthetic-device", + "tokens_per_step": 1, + "assumptions": ["Per rank, batch 1. This synthetic fixture fixes the irreducible demands explicitly."], + "ops": [ + {"name": "attention block", "repeat": 2, "demand": {"compute.bf16": 40, "memory.hbm": 10}, + "bound_demand": {"compute.bf16": 40, "memory.hbm": 10}, + "source": {"kind": "synthetic", "locator": "hand-written fixture"}}, + {"name": "mlp block", "repeat": 2, "demand": {"compute.bf16": 20, "memory.hbm": 20}, + "bound_demand": {"compute.bf16": 20, "memory.hbm": 20}, + "source": {"kind": "synthetic", "locator": "hand-written fixture"}}, + {"name": "tensor-parallel all-reduce", "repeat": 2, "demand": {"link.tp": 5}, + "bound_demand": {"link.tp": 5}, + "source": {"kind": "synthetic", "locator": "hand-written fixture"}} + ] + } +} diff --git a/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/references/qwen38-h200-tp4.json b/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/references/qwen38-h200-tp4.json new file mode 100644 index 000000000..cd5938da2 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/references/qwen38-h200-tp4.json @@ -0,0 +1,89 @@ +{ + "model": "Qwen/Qwen3.8-Flash-Next", + "revision": "812d96e10a0dd82b69d749e68693698cf6c36daa", + "config_sha256": "889658f2508e8c61d409b02e70e0d78d8d4452ec65aaafbe129805d213d2e74b", + "text_config": { + "dtype": "bfloat16", + "mamba_ssm_dtype": "float32", + "num_hidden_layers": 48, + "full_attention_interval": 4, + "hidden_size": 2560, + "vocab_size": 248320, + "num_attention_heads": 24, + "num_key_value_heads": 2, + "head_dim": 256, + "linear_num_key_heads": 16, + "linear_key_head_dim": 128, + "linear_num_value_heads": 48, + "linear_value_head_dim": 128, + "linear_conv_kernel_dim": 4, + "num_experts": 512, + "num_experts_per_tok": 10, + "moe_intermediate_size": 640, + "shared_expert_intermediate_size": 640, + "hc_count": 4, + "hc_lowrank": 320, + "ple_layer_ids": [ + 2 + ], + "ple_embed_dim": 2560, + "ple_conv_kernel_size": 4, + "ngram_size": 3, + "heads_per_ngram": 8, + "ngram_vocab_size_base": 20000000, + "make_ngram_vocab_size_divisible_by": 128, + "split_ngram_parts": 128, + "indexer_n_heads": 4, + "indexer_kv_heads": 1, + "indexer_head_dim": 128, + "indexer_budget": 2048, + "indexer_compress_ratio": 4, + "max_position_embeddings": 262144 + }, + "checkpoint": { + "index_sha256": "99e815241ef03325536b0aaa4441deea45174c17fae31e10f0bb456410c590de", + "shards": 131, + "tensors": 1658, + "stored_bytes": 359999963128, + "text_tensors": 1294, + "text_schema_sha256": "b76bcb1c01778e512502bc409751e1274bed149020ea29c6699442c37b955435", + "all_schema_sha256": "1598eab3de975cb002c7ae275abde805acbf77b9b7d061c601dba9ddb1a072fc" + }, + "engine": "https://github.com/vllm-project/vllm/tree/5df63a7203cdb9328d824a27b682e77c7b9928be", + "nominal_hbm_bytes_per_gpu": 141000000000, + "hardware": { + "hardware_id": "H200-SXM", + "assumptions": [ + "Published SKU rates per GPU. Actual clocks, topology and effective bandwidth are unmeasured. Ring traffic counts outgoing bytes." + ], + "rates": { + "compute.bf16": { + "resource": "compute", + "unit": "FLOP/s", + "value": 989500000000000.0, + "source": { + "kind": "datasheet", + "locator": "https://www.nvidia.com/en-us/data-center/h200/ (SXM BF16 1,979 TFLOP/s with 2:4 sparsity, divided by two for dense arithmetic)" + } + }, + "memory.hbm": { + "resource": "memory", + "unit": "byte/s", + "value": 4800000000000.0, + "source": { + "kind": "datasheet", + "locator": "https://www.nvidia.com/en-us/data-center/h200/ (SXM HBM3e bandwidth)" + } + }, + "link.nvlink_tx": { + "resource": "link", + "unit": "byte/s", + "value": 450000000000.0, + "source": { + "kind": "datasheet", + "locator": "https://www.nvidia.com/en-us/data-center/technologies/hopper-architecture/ (900 GB/s bidirectional per GPU, symmetric links)" + } + } + } + } +} diff --git a/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/references/qwen38-h200-tp4.md b/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/references/qwen38-h200-tp4.md new file mode 100644 index 000000000..f19a4edc7 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/references/qwen38-h200-tp4.md @@ -0,0 +1,73 @@ +# Qwen3.8-Flash-Next on four H200 SXM GPUs + +This worked example prices one text request at published H200 SXM rates. It +checks the stored tensors used by the text decoder and follows the NVIDIA +implementation in vLLM 0.32.0. The report keeps the whole-model qualified bound +and measured latency unavailable. [Model config](https://huggingface.co/Qwen/Qwen3.8-Flash-Next/blob/812d96e10a0dd82b69d749e68693698cf6c36daa/config.json) · [vLLM decoder](https://github.com/vllm-project/vllm/blob/5df63a7203cdb9328d824a27b682e77c7b9928be/vllm/models/qwen4_exp/nvidia/model.py#L178-L361) + +## Reproduce + +From the repository root, run the standard-library driver. The second command +also verifies the pinned config and index and reads the headers of all 131 +safetensors shards with HTTP byte-range requests. The offline replay uses the +recorded digest of the observed names, shapes and dtypes. [Inputs and source digests](qwen38-h200-tp4.json) + +```bash +skill=src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis +python3 "$skill/scripts/qwen38_h200_tp4.py" --prompt-tokens 8192 --output-tokens 256 +python3 "$skill/scripts/qwen38_h200_tp4.py" --prompt-tokens 8192 --output-tokens 256 --verify-hub-headers +``` + +## Workload and layout + +- One 8,192-token prompt, one prefill chunk, 256 output tokens, batch one, no prefix reuse, language-model-only mode and MTP disabled. Prefill emits the first token. The 255 following forwards have visible lengths 8,193 through 8,447, including the token being processed. +- One four-GPU node, TP4 and embedding TP4, with PP, context, data and expert parallel degrees of one. HC and MoE sequence parallelism are disabled. Each TP rank processes shards of the same ten selected experts per token. For prefill the driver evaluates both extrema for the number of distinct experts touched per layer. Routing skew and padding still affect kernel efficiency. [MoE layout](https://github.com/vllm-project/vllm/blob/5df63a7203cdb9328d824a27b682e77c7b9928be/vllm/model_executor/models/qwen3_next.py#L125-L259) +- Weights, activations, main KV, index KV and convolution state use BF16. The GDN temporal matrix uses FP32. The n-gram embedding is GPU-resident and vocabulary-sharded. The four residual streams have replicated projection weights on this path. [N-gram placement](https://github.com/vllm-project/vllm/blob/5df63a7203cdb9328d824a27b682e77c7b9928be/vllm/models/qwen4_exp/nvidia/ngram_embedding.py#L178-L240) · [Residual projections](https://github.com/vllm-project/vllm/blob/5df63a7203cdb9328d824a27b682e77c7b9928be/vllm/models/qwen4_exp/nvidia/hyperconnection.py#L90-L134) +- Per GPU, use about 989.5 TFLOP/s dense BF16 (half the advertised 1,979 with structured sparsity), 4.8 TB/s HBM and 450 GB/s outgoing NVLink (half the advertised bidirectional bandwidth). The capacity screen uses the nominal 141 GB in decimal units. These device specifications supply ideal rates. Actual clocks and effective rates require target evidence. [H200 SXM specifications and sparsity footnote](https://www.nvidia.com/en-us/data-center/h200/) · [Hopper NVLink direction convention](https://www.nvidia.com/en-us/data-center/technologies/hopper-architecture/) + +## Counts + +The 1,658 checkpoint entries contain 359,999,963,128 stored bytes. The driver +derives names, dtypes and shapes for the 1,294 text tensors, including the +output projection and 128 n-gram shards. The optional audit compares them +against the published headers in both directions. The other 364 entries belong +to vision and MTP. The header audit verifies metadata only. [Checkpoint index](https://huggingface.co/Qwen/Qwen3.8-Flash-Next/blob/812d96e10a0dd82b69d749e68693698cf6c36daa/model.safetensors.index.json) · [Language-model-only loading](https://github.com/vllm-project/vllm/blob/5df63a7203cdb9328d824a27b682e77c7b9928be/vllm/models/qwen4_exp/nvidia/model.py#L987-L1013) + +The resident ledger divides stored axes according to their placement, including +partial KV-head replication and n-gram vocabulary ownership. `rank_logical_weight_bytes` +counts checkpoint-format logical payload before kernel repacking, internal +padding and dtype conversion. Real fit also depends on the KV pool, scratch +buffers, CUDA graphs and allocator reserves. [Tensor ledger](../scripts/qwen38_h200_tp4.py) + +For the 12 QSA layers, one main KV head resides on each TP rank. The index stores +one compressed key per completed four-token group and a separate four-row raw +key ring. Language-model-only mode strips MRoPE. The 36 GDN layers retain fixed +temporal and convolution states. The PLE convolution retains its dilated +history. The cache report gives logical state payload for one live sequence. +[QSA head placement](https://github.com/vllm-project/vllm/blob/5df63a7203cdb9328d824a27b682e77c7b9928be/vllm/models/qwen4_exp/nvidia/qsa.py#L389-L429) · [Indexer caches](https://github.com/vllm-project/vllm/blob/5df63a7203cdb9328d824a27b682e77c7b9928be/vllm/models/qwen4_exp/common/qsa_cache.py#L815-L877) · [Text-only RoPE and GDN dtype configuration](https://github.com/vllm-project/vllm/blob/5df63a7203cdb9328d824a27b682e77c7b9928be/vllm/model_executor/models/config.py#L851-L949) · [GDN state shapes](https://github.com/vllm-project/vllm/blob/5df63a7203cdb9328d824a27b682e77c7b9928be/vllm/model_executor/layers/mamba/mamba_utils.py#L280-L302) · [PLE state](https://github.com/vllm-project/vllm/blob/5df63a7203cdb9328d824a27b682e77c7b9928be/vllm/models/qwen4_exp/nvidia/ple_layer.py#L91-L96) + +## Interpret the phase output + +| Resource | Counted demand per rank | +| --- | --- | +| Compute | Two FLOPs per useful dense multiply-add across the text projections, ten routed experts and one shared expert per token, and one logits row per forward. QSA QK/AV covers the selected rows and the causal tail. The index score counts dots against complete four-token groups. Arithmetic is priced in dense BF16 equivalents. | +| HBM | One stream of each distinct matrix per forward. Prefill counts two scenarios with 10 or 512 distinct routed experts per layer at the given length. Each QSA query writes its new main KV row. Decode streams selected main KV rows and reads compressed index keys once. GDN writes the final recurrent matrix after prefill and reads and writes it once per decode step. | +| NVLink transmit | 96 decoder hidden-state reductions per forward in the assumed ring schedule. Each of the four ranks sends 1.5 times the BF16 payload per reduction. The model allows zero startup time. | + +The QSA token selection counts complete blocks up to the 2,048-token budget +plus the open group's tail. The retained main KV grows with the full context. +[Sparse index expansion](https://github.com/vllm-project/vllm/blob/5df63a7203cdb9328d824a27b682e77c7b9928be/vllm/models/qwen4_exp/nvidia/ops/qsa_indexer.py#L232-L276) · [Index projection and precision](https://github.com/vllm-project/vllm/blob/5df63a7203cdb9328d824a27b682e77c7b9928be/vllm/models/qwen4_exp/nvidia/indexer_qsa.py#L115-L164) + +`resource_max_s` is the largest of the three resource times for the counted +work. `serial_group_s` sums the largest resource time of each modeled family. +Families aggregate layers and can contain several kernels. The mean decode +rate divides the 255 emitted tokens by the summed decode reference times. +`request_resource_s` adds the prefill reference for each routing scenario. + +The timing omits GDN recurrence arithmetic, QSA top-k selection and +intermediate traffic, repeated prefill KV reads, embedding/PLE lookup traffic +and reductions, logits gathering, activation and normalization traffic, +allocator behavior, launch overhead and scheduling. The grouped time also +depends on fusion, cache reuse and overlap. A complete fused graph and +device evidence are needed to turn these scenario calculations into a +qualified bound or a calibrated latency or throughput estimate. diff --git a/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/scripts/model_sol.py b/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/scripts/model_sol.py new file mode 100644 index 000000000..104052a73 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/scripts/model_sol.py @@ -0,0 +1,588 @@ +"""Pure model-level speed-of-light arithmetic over supplied counts. + +No I/O, network access, device execution or acceptance. Every function takes +JSON data, returns JSON data and reports missing evidence as unknowns instead of +guessing. See references/model-sol-contract.md for inputs, outputs and limits. +""" + +import math + +# Byte widths of safetensors header dtypes. Packed sub-byte formats are stored in +# one of these containers, so the header's own dtype gives the physical width. +DTYPE_BYTES = { + "F64": 8, "I64": 8, "U64": 8, + "F32": 4, "I32": 4, "U32": 4, + "F16": 2, "BF16": 2, "I16": 2, "U16": 2, + "F8_E4M3": 1, "F8_E5M2": 1, "F8_E8M0": 1, "I8": 1, "U8": 1, "BOOL": 1, +} +PHASES = ("prefill", "decode") +KV_LAWS = ("global", "window", "compressed", "complete_groups", "constant") +RATE_UNITS = {"compute": "FLOP/s", "memory": "byte/s", "link": "byte/s"} +SOURCE_KINDS = ("derived", "measured", "synthetic") +RATE_KINDS = ("peak", "synthetic", "datasheet") +FLOOR_KINDS = ("measured", "assumed", "synthetic") + + +def _json_object(value): + return type(value) is dict and all(type(key) is str for key in value) + + +def _copy_json(value): + """Accept only JSON data, without invoking caller-defined hooks.""" + if value is None or type(value) in (str, int, bool): + return value + if type(value) is float and math.isfinite(value): + return value + if type(value) is list: + return [_copy_json(item) for item in value] + if _json_object(value): + return {key: _copy_json(item) for key, item in value.items()} + raise ValueError("Inputs must contain only finite JSON data") + + +def _mapping(value, path): + if value is None: + return {} + if type(value) is not dict: + raise ValueError(f"{path} must be an object or null") + return value + + +def _list(value, path): + if value is None: + return [] + if type(value) is not list: + raise ValueError(f"{path} must be a list or null") + return value + + +def _text(mapping, key, path, unknowns): + value = mapping.get(key) + if value is None or value == "": + unknowns.append(f"{path}.{key}: missing") + return None + if type(value) is not str or not value.strip(): + raise ValueError(f"{path}.{key} must be nonempty text or null") + return value + + +def _count(value, path, minimum=0): + if type(value) is not int or value < minimum: + raise ValueError(f"{path} must be an integer >= {minimum}") + return value + + +def _required_count(mapping, key, path, unknowns): + if mapping.get(key) is None: + unknowns.append(f"{path}.{key}: missing") + return None + return _count(mapping.get(key), f"{path}.{key}", 1) + + +def _positive(value, path): + if value is None: + return None + if type(value) not in (int, float): + raise ValueError(f"{path} must be a finite positive number or null") + try: + result = float(value) + except OverflowError as error: + raise ValueError(f"{path} exceeds the numeric range") from error + if not math.isfinite(result) or result <= 0: + raise ValueError(f"{path} must be a finite positive number or null") + return result + + +def _nonnegative(value, path): + if type(value) not in (int, float): + raise ValueError(f"{path} must be a finite number >= 0") + try: + result = float(value) + except OverflowError as error: + raise ValueError(f"{path} exceeds the numeric range") from error + if not math.isfinite(result) or result < 0: + raise ValueError(f"{path} must be a finite number >= 0") + return result + + +def _finite(value, label): + if not math.isfinite(value): + raise ValueError(f"Derived {label} is outside the finite numeric range") + return value + + +def _scaled(value, count, label): + try: + return _finite(value * count, label) + except OverflowError as error: + raise ValueError(f"Derived {label} is outside the finite numeric range") from error + + +def _source(value, path, unknowns, kinds): + source = _mapping(value, path) + kind = _text(source, "kind", path, unknowns) + _text(source, "locator", path, unknowns) + if kind is not None and kind not in kinds: + unknowns.append(f"{path}.kind: requires one of {'/'.join(kinds)}") + return kind + + +def _assumptions(mapping, path, unknowns): + values = mapping.get("assumptions") + if values is None or values == []: + unknowns.append(f"{path}.assumptions: missing") + return [] + if type(values) is not list or any( + type(item) is not str or not item.strip() for item in values + ): + raise ValueError(f"{path}.assumptions must be a list of nonempty strings") + return list(values) + + +def _tensor_counts(tensor, path, unknowns, copies=1): + shape = tensor.get("shape") + dtype = tensor.get("dtype") + if dtype is not None and type(dtype) is not str: + raise ValueError(f"{path}.dtype must be a string or null") + width = DTYPE_BYTES.get(dtype) + if width is None: + unknowns.append(f"{path}.dtype: no known byte width; bytes cannot be formed") + if shape is None: + unknowns.append(f"{path}.shape: missing") + return None, None + total = 1 + for index, size in enumerate(_list(shape, f"{path}.shape")): + total *= _count(size, f"{path}.shape[{index}]") + elements = total * copies + return elements, elements * width if width is not None else None + + +def _sum_known(values): + total = 0 + for value in values: + if value is None: + return None + total += value + return total + + +def _selects(pattern, name): + """A stored name selects a header name segment by segment; `X` matches any index.""" + wanted, actual = pattern.split("."), name.split(".") + if len(wanted) != len(actual): + return False + return all(w == a or (w == "X" and a.isdigit()) for w, a in zip(wanted, actual)) + + +def join_checkpoint(header, inventory): + """Join an analytical stored-tensor inventory to a checkpoint header in both directions. + + `header.tensors` maps verbatim header names to {dtype, shape}, merged across + shards. `inventory.tensors` lists stored tensors as {name, dtype, shape, copies, + buffer}; a name may write `X` at an indexed position. Rows sharing a name are + summed. Returns missing and multiply claimed names, per-name comparisons + and the byte checksum. The join is the gate; the byte total is its checksum. + """ + header = _mapping(_copy_json(header), "header") + inventory = _mapping(_copy_json(inventory), "inventory") + unknowns = [] + _source(header.get("source"), "header.source", unknowns, ("measured", "synthetic")) + _source(inventory.get("source"), "inventory.source", unknowns, SOURCE_KINDS) + + tensors = {} + for name, entry in _mapping(header.get("tensors"), "header.tensors").items(): + if name == "__metadata__": + continue + path = f"header.tensors.{name}" + tensors[name] = _tensor_counts(_mapping(entry, path), path, unknowns) + if not tensors: + unknowns.append("header.tensors: empty; an empty header passes every join") + + stored = {} + for index, row in enumerate(_list(inventory.get("tensors"), "inventory.tensors")): + path = f"inventory.tensors[{index}]" + row = _mapping(row, path) + name = _text(row, "name", path, unknowns) + if name is None: + continue + copies = _count(row.get("copies", 1), f"{path}.copies", 1) + elements, size = _tensor_counts(row, path, unknowns, copies) + entry = stored.setdefault(name, {"elements": [], "bytes": [], "buffer": True}) + entry["elements"].append(elements) + entry["bytes"].append(size) + entry["buffer"] = entry["buffer"] and row.get("buffer") is True + + claimed, matched, absent = set(), [], [] + multiply_claimed = set() + for name in sorted(stored): + entry = stored[name] + selection = [key for key in tensors if _selects(name, key)] + if not selection: + if not entry["buffer"]: + absent.append(name) + continue + multiply_claimed.update(claimed.intersection(selection)) + claimed.update(selection) + entry["matched"] = True + header_elements = _sum_known(tensors[key][0] for key in selection) + header_bytes = _sum_known(tensors[key][1] for key in selection) + inventory_elements = _sum_known(entry["elements"]) + inventory_bytes = _sum_known(entry["bytes"]) + matched.append({ + "name": name, + "header_tensors": len(selection), + "header_elements": header_elements, + "inventory_elements": inventory_elements, + "element_diff": header_elements - inventory_elements + if header_elements is not None and inventory_elements is not None else None, + "header_bytes": header_bytes, + "inventory_bytes": inventory_bytes, + "byte_diff": header_bytes - inventory_bytes + if header_bytes is not None and inventory_bytes is not None else None, + }) + unclaimed = sorted(name for name in tensors if name not in claimed) + mismatched = [row["name"] for row in matched if row["element_diff"] or row["byte_diff"]] + header_total = _sum_known(size for _, size in tensors.values()) + # A buffer computed at load may be absent from the file; count it only when stored there. + inventory_total = _sum_known( + size for entry in stored.values() if not entry["buffer"] or entry.get("matched") + for size in entry["bytes"] + ) + clean = not (unknowns or unclaimed or absent or mismatched or multiply_claimed) + return { + "analysis_status": "INSUFFICIENT_EVIDENCE" if unknowns else "COMPUTED", + "join_clean": clean, + "unclaimed_header_tensors": unclaimed, + "multiply_claimed_header_tensors": sorted(multiply_claimed), + "absent_stored_names": absent, + "mismatched_names": mismatched, + "matched": matched, + "byte_checksum": { + "header_bytes": header_total, + "inventory_bytes": inventory_total, + "equal": header_total == inventory_total + if header_total is not None and inventory_total is not None else None, + }, + "unknowns": unknowns, + "limits": [ + "The join anchors stored weights only; it says nothing about KV growth, " + "cache boundedness or per-rank placement.", + "Equal byte totals do not imply a correct join: two swapped submodules " + "with the same total pass the checksum.", + "No layout is read; a clean join certifies nothing about per-rank bytes.", + ], + } + + +def kv_cache_bytes(layers, context_tokens): + """Stored KV bytes per sequence at `context_tokens`, by each layer group's growth law. + + Each group is {name, layers, bytes_per_position, law, window|ratio|state_bytes}: + `global` stores every position, `window` stores min(window, s), `compressed` + stores ceil(s / ratio), `complete_groups` stores floor(s / ratio) + and `constant` stores a fixed recurrent state. The + result also reports which groups stay bounded as the context grows. + """ + layers = _list(_copy_json(layers), "layers") + context = _count(context_tokens, "context_tokens") + unknowns, groups = [], [] + if not layers: + unknowns.append("layers: empty") + for index, group in enumerate(layers): + path = f"layers[{index}]" + group = _mapping(group, path) + name = _text(group, "name", path, unknowns) + count = _required_count(group, "layers", path, unknowns) + law = group.get("law") + if law not in KV_LAWS: + unknowns.append(f"{path}.law: requires one of {'/'.join(KV_LAWS)}") + continue + _source(group.get("source"), f"{path}.source", unknowns, SOURCE_KINDS) + if law == "constant": + if group.get("state_bytes") is None: + unknowns.append(f"{path}.state_bytes: missing") + continue + per_layer = _nonnegative(group.get("state_bytes"), f"{path}.state_bytes") + positions, bounded = None, True + else: + width = _positive(group.get("bytes_per_position"), f"{path}.bytes_per_position") + if width is None: + unknowns.append(f"{path}.bytes_per_position: missing") + continue + if law == "global": + positions, bounded = context, False + elif law == "window": + window = _required_count(group, "window", path, unknowns) + if window is None: + continue + positions, bounded = min(window, context), True + else: + ratio = _required_count(group, "ratio", path, unknowns) + if ratio is None: + continue + positions = context // ratio if law == "complete_groups" else -(-context // ratio) + bounded = False + per_layer = _scaled(width, positions, "KV bytes") + if count is None: + continue + groups.append({ + "name": name, + "law": law, + "layers": count, + "positions": positions, + "bytes": _scaled(per_layer, count, "KV bytes"), + "bounded_as_context_grows": bounded, + }) + total = _finite(sum(group["bytes"] for group in groups), "KV bytes") if not unknowns else None + return { + "analysis_status": "INSUFFICIENT_EVIDENCE" if unknowns else "COMPUTED", + "context_tokens": context, + "groups": groups, + "total_bytes": total, + "bounded_as_context_grows": all(group["bounded_as_context_grows"] for group in groups) + if groups and not unknowns else None, + "unknowns": unknowns, + "limits": [ + "Per sequence and per supplied bytes_per_position; batch, paging granularity " + "and per-rank head splits are the caller's to apply.", + "A layer declared global whose real attention is windowed overstates KV; " + "one declared windowed but wired dense understates it. Check the wiring.", + ], + } + + +def _floor(op, key, path, unknowns): + if op.get(key) is None: + return None + floor = _mapping(op.get(key), f"{path}.{key}") + value = _nonnegative(floor.get("value"), f"{path}.{key}.value") + _source(floor.get("source"), f"{path}.{key}.source", unknowns, FLOOR_KINDS) + return value + + +def _copy_hardware(value): + """Record non-finite link readings as JSON null in the returned snapshot.""" + if _json_object(value) and _json_object(value.get("rates")): + rates = value["rates"].copy() + for name, fact in rates.items(): + if not _json_object(fact): + continue + resource, sample = fact.get("resource"), fact.get("value") + if (type(resource) is str and resource == "link" + and type(sample) is float and not math.isfinite(sample)): + rates[name] = {**fact, "value": None} + value = {**value, "rates": rates} + return _mapping(_copy_json(value), "hardware") + + +def _rates(hardware, unknowns): + rates, kinds = {}, set() + for name, fact in _mapping(hardware.get("rates"), "hardware.rates").items(): + path = f"hardware.rates.{name}" + fact = _mapping(fact, path) + resource = fact.get("resource") + if type(resource) is not str or resource not in RATE_UNITS: + unknowns.append(f"{path}.resource: requires one of {'/'.join(RATE_UNITS)}") + continue + if fact.get("unit") != RATE_UNITS[resource]: + unknowns.append(f"{path}.unit: requires {RATE_UNITS[resource]}; no implicit conversion") + kind = _source(fact.get("source"), f"{path}.source", unknowns, RATE_KINDS) + kinds.add(kind) + if kind == "peak": + _text(fact, "clock_basis", path, unknowns) + try: + value = _positive(fact.get("value"), f"{path}.value") + except ValueError: + if resource != "link": + raise + value = None + # Link bandwidth is required only for a positive transfer. + if value is None and resource != "link": + unknowns.append(f"{path}.value: {fact.get('missing_reason') or 'missing'}") + rates[name] = (resource, value) + if not rates: + unknowns.append("hardware.rates: empty") + basis = kinds.pop() if len(kinds) == 1 else None + basis = basis if basis in RATE_KINDS else None + if basis not in RATE_KINDS: + unknowns.append("hardware.rates: requires all peak or all synthetic or all datasheet " + "sources; observed envelopes require separate calibration") + return rates, basis + + +def _bound_counts(declaration, demand, path, require_evidence, unknowns): + """Return each resource's declared lower count, retaining gaps as null.""" + declared = _mapping(declaration, path) + counts = {key: 0.0 if scheduled == 0 else None for key, scheduled in demand.items()} + for key, value in declared.items(): + amount = _nonnegative(value, f"{path}.{key}") if value is not None else None + if key not in demand: + unknowns.append(f"{path}.{key}: not in demand") + elif amount is not None: + if amount > demand[key]: + unknowns.append(f"{path}.{key}: exceeds demand") + counts[key] = None + else: + counts[key] = amount + if require_evidence: + for key, scheduled in demand.items(): + if scheduled > 0 and declared.get(key) is None: + unknowns.append(f"{path}.{key}: missing irreducible demand") + return counts + + +def _seconds(amount, rate): + # Zero bytes require no bandwidth. Positive transfers have passed the evidence check. + return 0.0 if amount == 0 else _finite(amount / rate, "resource time") + + +def _resource_time(totals, rates): + times = {name: _seconds(amount, rates[name][1]) for name, amount in totals.items()} + maximum = max(times.values()) + return maximum, sorted(name for name, value in times.items() if value == maximum) + + +def phase_floors(phase, hardware): + """Per-rank floors for one phase step from supplied per-op demands and peak rates. + + `phase.ops` lists {name, repeat, demand, bound_demand, link_latency_s, + launch_floor_s, source}. `demand` maps a rate in `hardware.rates` to the + amount the op actually moves or computes, in the unit that rate's resource + consumes. A phase bound requires explicit `bound_demand` evidence for + each positive amount. Scheduled work alone supplies the estimate. + Within an op, the maximum assumes full + compute/memory overlap. Sequential link phases add up with the link latency; + a launch floor is one more alternative time. These floors enter only the serial + estimate, never the bound. Returns the resource-total bound and the serial + per-op estimate separately. Datasheet rates populate a specification + reference time and leave the hardware-qualified bound unavailable. + """ + phase = _mapping(_copy_json(phase), "phase") + hardware = _copy_hardware(hardware) + unknowns = [] + kind = phase.get("phase") + if kind not in PHASES: + unknowns.append(f"phase.phase: requires one of {'/'.join(PHASES)}") + for key in ("model_id", "layout", "hardware_id"): + _text(phase, key, "phase", unknowns) + if _text(hardware, "hardware_id", "hardware", unknowns) != phase.get("hardware_id"): + unknowns.append("hardware.hardware_id: differs from phase") + tokens = _positive(phase.get("tokens_per_step"), "phase.tokens_per_step") + if tokens is None: + unknowns.append("phase.tokens_per_step: missing") + rates, basis = _rates(hardware, unknowns) + assumptions = _assumptions(phase, "phase", unknowns) + assumptions += _assumptions(hardware, "hardware", unknowns) + + bound_unknowns = [] + totals = {name: 0.0 for name in rates} + actual = {name: 0.0 for name in rates} + ops = [] + for index, op in enumerate(_list(phase.get("ops"), "phase.ops")): + path = f"phase.ops[{index}]" + op = _mapping(op, path) + name = _text(op, "name", path, unknowns) + repeat = _count(op.get("repeat", 1), f"{path}.repeat", 1) + _source(op.get("source"), f"{path}.source", unknowns, SOURCE_KINDS) + demand = _mapping(op.get("demand"), f"{path}.demand") + latency = _floor(op, "link_latency_s", path, unknowns) + launch = _floor(op, "launch_floor_s", path, unknowns) + if not demand and latency is None and launch is None: + unknowns.append(f"{path}.demand: empty") + amounts = {} + for rate_name, amount in demand.items(): + amount = _nonnegative(amount, f"{path}.demand.{rate_name}") + if rate_name not in rates: + unknowns.append(f"{path}.demand.{rate_name}: no matching hardware rate") + continue + amounts[rate_name] = amount + actual[rate_name] = _finite( + actual[rate_name] + _scaled(amount, repeat, "actual resource demand"), + "actual resource total", + ) + lower = _bound_counts(op.get("bound_demand"), amounts, f"{path}.bound_demand", + basis in ("peak", "synthetic"), bound_unknowns) + for rate_name, amount in lower.items(): + if amount is None: + totals[rate_name] = None + elif totals[rate_name] is not None: + totals[rate_name] = _finite( + totals[rate_name] + _scaled(amount, repeat, "bound resource demand"), + "bound resource total", + ) + ops.append({"name": name, "repeat": repeat, "amounts": amounts, + "latency": latency, "launch": launch}) + if not ops: + unknowns.append("phase.ops: empty") + for key, (resource, value) in rates.items(): + if resource == "link" and value is None and actual[key] > 0: + reason = hardware["rates"][key].get("missing_reason") or "missing or invalid bandwidth" + unknowns.append(f"hardware.rates.{key}.value: {reason}") + + bound = binding = estimate = None + datasheet_time = datasheet_binding = None + per_op = [] + if not unknowns: + if basis == "datasheet": + datasheet_time, datasheet_binding = _resource_time(actual, rates) + elif not bound_unknowns: + bound, binding = _resource_time(totals, rates) + estimate = 0.0 + for op in ops: + terms, links = {}, [] + link_time = 0.0 + for key, value in op["amounts"].items(): + if rates[key][0] == "link": + if value > 0: + links.append(key) + link_time += _seconds(value, rates[key][1]) + else: + terms[(key,)] = _seconds(value, rates[key][1]) + if links or op["latency"] is not None: + label = tuple(sorted(links)) or ("link_latency",) + terms[label] = link_time + (op["latency"] or 0.0) + if op["launch"] is not None: + terms[("launch_floor",)] = op["launch"] + op_time = max(terms.values()) if terms else 0.0 + estimate += _scaled(op_time, op["repeat"], "op time") + per_op.append({ + "name": op["name"], + "repeat": op["repeat"], + "time_s": op_time, + "binding": sorted(key for label, value in terms.items() if value == op_time + for key in label), + }) + estimate = _finite(estimate, "serial estimate") + unknowns.extend(bound_unknowns) + return { + "analysis_status": "INSUFFICIENT_EVIDENCE" if unknowns else "COMPUTED", + "evidence_basis": basis, + "phase": kind, + "tokens_per_step": tokens, + "resource_totals": totals, + "actual_resource_totals": actual, + "conditional_bound_s": bound, + "binding_resources": binding, + "datasheet_resource_time_s": datasheet_time, + "datasheet_binding_resources": datasheet_binding, + "serial_estimate_s": estimate, + "per_op": per_op, + "tokens_per_s_at_bound": _finite(tokens / bound, "bound throughput") if bound else None, + "tokens_per_s_at_serial_estimate": _finite(tokens / estimate, "serial throughput") + if estimate else None, + "assumptions": assumptions, + "unknowns": unknowns, + "inputs": {"phase": phase, "hardware": hardware}, + "limits": [ + "conditional_bound_s is a lower bound only if every demand is irreducible " + "for the permitted variants and every rate is a peak at the clock the device " + "actually runs that work at; it may reject a result.", + "serial_estimate_s assumes full compute/memory overlap within each op and " + "no overlap between ops. It includes any link latencies and launch floors " + "and may only " + "flag a faster result, never reject it.", + "Per rank and per supplied counts; queueing, launch, synchronization and " + "load imbalance are not modeled.", + "No achievable utilization, speedup, quality, goal acceptance or E2E claim follows.", + ], + } diff --git a/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/scripts/qwen38_checkpoint.py b/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/scripts/qwen38_checkpoint.py new file mode 100644 index 000000000..26c21c2b4 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/scripts/qwen38_checkpoint.py @@ -0,0 +1,87 @@ +"""Read and verify public metadata for the pinned Qwen checkpoint on explicit request.""" + +import hashlib +import json +import math +from concurrent.futures import ThreadPoolExecutor +from urllib.request import Request, urlopen + +from model_sol import join_checkpoint + + +def schema_digest(headers): + data = json.dumps(headers, sort_keys=True, separators=(",", ":")).encode() + return hashlib.sha256(data).hexdigest() + + +def _header_range(url, start, end): + request = Request(f"{url}?header-range={start}-{end}", + headers={"Range": f"bytes={start}-{end}"}) + with urlopen(request, timeout=30) as response: + interval = response.headers.get("Content-Range", "").partition("/")[0] + if response.status != 206 or interval != f"bytes {start}-{end}": + raise ValueError("Server did not return the requested header range") + data = response.read(end - start + 1) + if len(data) != end - start + 1: + raise ValueError("Incomplete safetensors header range") + return data + + +def _read_verified_json(url, digest): + with urlopen(url, timeout=30) as response: + data = response.read(4 * 1024**2) + if hashlib.sha256(data).hexdigest() != digest: + raise ValueError(f"Unexpected source bytes for {url}") + return json.loads(data) + + +def audit_headers(facts, expected_text): + base = f"https://huggingface.co/{facts['model']}/resolve/{facts['revision']}/" + config = _read_verified_json(base + "config.json", facts["config_sha256"])["text_config"] + for key, value in facts["text_config"].items(): + if config.get(key) != value: + raise ValueError(f"Packaged model configuration differs at {key}") + interval = config["full_attention_interval"] + expected_layers = ["full_attention" if (i + 1) % interval == 0 else "linear_attention" + for i in range(config["num_hidden_layers"])] + if config["layer_types"] != expected_layers: + raise ValueError("Layer sequence differs from the priced GDN/QSA layout") + + evidence = facts["checkpoint"] + index = _read_verified_json(base + "model.safetensors.index.json", evidence["index_sha256"]) + by_shard = {} + for name, shard in index["weight_map"].items(): + by_shard.setdefault(shard, set()).add(name) + + def read(shard): + url = base + shard + length = int.from_bytes(_header_range(url, 0, 7), "little") + if not 0 < length < 4 * 1024**2: + raise ValueError(f"Unexpected header size for {shard}") + rows = json.loads(_header_range(url, 8, 7 + length)) + rows.pop("__metadata__", None) + if rows.keys() != by_shard[shard]: + raise ValueError(f"Tensor names differ from the index for {shard}") + return {key: {"shape": row["shape"], "dtype": row["dtype"]} for key, row in rows.items()} + + with ThreadPoolExecutor(max_workers=4) as pool: + all_rows = {k: v for shard in pool.map(read, sorted(by_shard)) for k, v in shard.items()} + stored = sum(math.prod(row["shape"]) * {"BF16": 2, "I64": 8}[row["dtype"]] + for row in all_rows.values()) + if (len(by_shard) != evidence["shards"] or len(all_rows) != evidence["tensors"] + or stored != index["metadata"]["total_size"] or stored != evidence["stored_bytes"] + or schema_digest(all_rows) != evidence["all_schema_sha256"]): + raise ValueError("Checkpoint header inventory differs from the archived identity") + + text = {k: v for k, v in all_rows.items() if k.startswith("model.language_model.") + or k == "lm_head.weight"} + joined = join_checkpoint( + {"source": {"kind": "measured", "locator": base}, "tensors": text}, + {"source": {"kind": "derived", "locator": "qwen38_h200_tp4.py:text_weights"}, + "tensors": [dict(name=k, **v) for k, v in expected_text.items()]}, + ) + if not joined["join_clean"] or text != expected_text: + raise ValueError("Text checkpoint names, shapes or dtypes differ from the inventory") + return {"shards": len(by_shard), "checkpoint_tensors": len(all_rows), + "stored_bytes": stored, "text_tensors_joined": len(text), "join_clean": True, + "read_scope": "config, index and safetensors headers only"} diff --git a/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/scripts/qwen38_h200_tp4.py b/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/scripts/qwen38_h200_tp4.py new file mode 100644 index 000000000..43a52f5f0 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/model-sol-analysis/scripts/qwen38_h200_tp4.py @@ -0,0 +1,294 @@ +"""Replay the fixed Qwen3.8-Flash-Next BF16 / H200 SXM TP4 paper analysis.""" + +import argparse +import json +import math +from collections import Counter +from pathlib import Path + +from model_sol import kv_cache_bytes, phase_floors +from qwen38_checkpoint import audit_headers, schema_digest + +FACTS = Path(__file__).resolve().parents[1] / "references/qwen38-h200-tp4.json" +TP = 4 +BF16 = 2 +SOURCE = {"kind": "derived", "locator": "references/qwen38-h200-tp4.md"} + + +def ngram_shard_shape(c): + # vLLM builds one prime-sized vocabulary per n-gram head, pads the + # concatenation, then maps the checkpoint shards onto ETP vocabulary owners. + heads = (c["ngram_size"] - 1) * c["heads_per_ngram"] + candidate = c["ngram_vocab_size_base"] + rows = 0 + for _ in range(heads): + while any(candidate % d == 0 for d in range(2, math.isqrt(candidate) + 1)): + candidate += 1 + rows += candidate + candidate += 1 + pad = c["make_ngram_vocab_size_divisible_by"] + rows = (rows + pad - 1) // pad * pad + return rows // c["split_ngram_parts"], c["ple_embed_dim"] // heads + + +class WeightLedger: + """Logical checkpoint storage and TP placement before engine repacking.""" + + def __init__(self): + self.headers = {} + self.rank_bytes = Counter() + self.stored_bytes = 0 + + def add(self, name, shape, group="auxiliary", *, axis=None, ways=TP, dtype="BF16", owner=None): + if name in self.headers: + raise ValueError(f"Duplicated inventory name: {name}") + self.headers[name] = {"dtype": dtype, "shape": list(shape)} + size = math.prod(shape) * {"BF16": BF16, "I64": 8}[dtype] + self.stored_bytes += size + if axis is not None: + if shape[axis] % ways: + raise ValueError(f"Cannot split {name} on axis {axis} into {ways}") + size //= ways + if owner is None or owner == 0: + self.rank_bytes[group] += size + + +def text_weights(c): + ledger = WeightLedger() + h, streams, low = c["hidden_size"], c["hc_count"], c["hc_lowrank"] + wide = h * streams + e, m = c["num_experts"], c["moe_intermediate_size"] + shared = c["shared_expert_intermediate_size"] + d, q, kv = c["head_dim"], c["num_attention_heads"], c["num_key_value_heads"] + vk = c["linear_num_value_heads"] + v = vk * c["linear_value_head_dim"] + k = c["linear_num_key_heads"] * c["linear_key_head_dim"] + index_width = (c["indexer_n_heads"] + c["indexer_kv_heads"]) * c["indexer_head_dim"] + + def mixer(prefix, inject): + ledger.add(prefix + "hc_norm.weight", (wide,)) + ledger.add(prefix + "input_mix_weight_down.weight", (low, wide), "residual") + ledger.add(prefix + "input_mix_weight_up.weight", (wide, low), "residual") + if inject: + ledger.add(prefix + "block_inject_weight.weight", (streams, wide), "residual") + + root = "model.language_model." + ledger.add("lm_head.weight", (c["vocab_size"], h), "logits", axis=0) + ledger.add(root + "embed_tokens.weight", (c["vocab_size"], h), "embedding", axis=0) + mixer(root + "hyper_connection_mixer.", False) + for layer in range(c["num_hidden_layers"]): + prefix = f"{root}layers.{layer}." + mixer(prefix + "attn_hyper_connection.", True) + mixer(prefix + "mlp_hyper_connection.", True) + mlp = prefix + "mlp." + ledger.add(mlp + "experts.gate_up_proj", (e, 2 * m, h), "routed", axis=1) + ledger.add(mlp + "experts.down_proj", (e, h, m), "routed", axis=2) + ledger.add(mlp + "gate.weight", (e, h), "router") + ledger.add(mlp + "shared_expert_gate.weight", (1, h), "router") + for proj in ("gate_proj", "up_proj"): + ledger.add(mlp + "shared_expert." + proj + ".weight", (shared, h), "shared", axis=0) + ledger.add(mlp + "shared_expert.down_proj.weight", (h, shared), "shared", axis=1) + + if (layer + 1) % c["full_attention_interval"] == 0: + attn = prefix + "self_attn." + ledger.add(attn + "q_proj.weight", (2 * q * d, h), "qsa", axis=0) + for proj in ("k_proj", "v_proj"): + # Two distinct KV heads across four ranks, two replicas per head. + ledger.add(attn + proj + ".weight", (kv * d, h), "qsa", axis=0, ways=kv) + ledger.add(attn + "o_proj.weight", (h, q * d), "qsa", axis=1) + ledger.add(attn + "indexer.index_qk_proj.weight", (index_width, h), "qsa") + for norm in ("q_norm", "k_norm"): + ledger.add(attn + norm + ".weight", (d,)) + for norm in ("q_layernorm", "k_layernorm"): + ledger.add(attn + "indexer." + norm + ".weight", (c["indexer_head_dim"],)) + else: + attn = prefix + "linear_attn." + for proj, dim in (("a", vk), ("b", vk), ("qkv", 2 * k + v), ("z", v)): + ledger.add(attn + f"in_proj_{proj}.weight", (dim, h), "gdn", axis=0) + ledger.add(attn + "out_proj.weight", (h, v), "gdn", axis=1) + ledger.add(attn + "conv1d.weight", (2 * k + v, 1, c["linear_conv_kernel_dim"]), axis=0) + ledger.add(attn + "norm.weight", (c["linear_value_head_dim"],)) + for vector in ("A_log", "dt_bias"): + ledger.add(attn + vector, (vk,), axis=0) + + if layer + 1 in c["ple_layer_ids"]: + ple = prefix + "ple." + ledger.add(ple + "key_proj.weight", (wide, c["ple_embed_dim"]), "ple") + ledger.add(ple + "value_proj.weight", (h, c["ple_embed_dim"]), "ple") + ledger.add(ple + "conv1d.weight", (wide, 1, c["ple_conv_kernel_size"])) + for norm in ("norm_conv", "norm_key", "norm_query"): + ledger.add(ple + norm + ".weight", (wide,)) + emb = ple + "ple_embedding." + heads = (c["ngram_size"] - 1) * c["heads_per_ngram"] + ledger.add(emb + "layer_multipliers", (c["ngram_size"],), dtype="I64") + for vector in ("ngram_heads_offsets", "ngram_heads_vocab_sizes"): + ledger.add(emb + vector, (heads,), dtype="I64") + shape = ngram_shard_shape(c) + for shard in range(c["split_ngram_parts"]): + ledger.add(emb + f"ngram_embedding.shard_{shard}.weight", shape, "ngram", + owner=shard // (c["split_ngram_parts"] // TP)) + return ledger + + +def cache_payload(c, context): + layers = c["num_hidden_layers"] + qsa = layers // c["full_attention_interval"] + n_v, dv = c["linear_num_value_heads"], c["linear_value_head_dim"] + dk = c["linear_key_head_dim"] + conv = (2 * c["linear_num_key_heads"] * dk + n_v * dv) // TP + ratio, index_dim = c["indexer_compress_ratio"], c["indexer_head_dim"] + groups = [ + dict(name="QSA main K/V", layers=qsa, law="global", + bytes_per_position=2 * c["head_dim"] * BF16), # one local KV head + dict(name="QSA index", layers=qsa, law="complete_groups", ratio=ratio, + bytes_per_position=index_dim * BF16), + # vLLM strips MRoPE in language-model-only mode. The ring stores keys. + dict(name="QSA raw index ring", layers=qsa, law="constant", + state_bytes=ratio * index_dim * BF16), + dict(name="GDN recurrent matrix", layers=layers - qsa, law="constant", + state_bytes=n_v // TP * dv * dk * 4), # FP32 temporal state + dict(name="GDN convolution", layers=layers - qsa, law="constant", + state_bytes=conv * (c["linear_conv_kernel_dim"] - 1) * BF16), + dict(name="PLE convolution", layers=len(c["ple_layer_ids"]), law="constant", + state_bytes=c["hidden_size"] * c["hc_count"] * (c["ple_conv_kernel_size"] - 1) + * c["ngram_size"] * BF16), + ] + result = kv_cache_bytes([dict(group, source=SOURCE) for group in groups], context) + return {**{g["name"]: int(g["bytes"]) for g in result["groups"]}, + "total": int(result["total_bytes"])} + + +def phase_reference(facts, weights, phase, positions, distinct_experts): + """Count useful work for the supplied query positions (1-based visible lengths).""" + c, hardware = facts["text_config"], facts["hardware"] + tokens = len(positions) + ops = [] + + def op(name, flops=0, hbm=0, tx=0): + ops.append({"name": name, "source": SOURCE, + "demand": {"compute.bf16": flops, "memory.hbm": hbm, "link.nvlink_tx": tx}}) + + for name in ("gdn", "qsa", "residual", "ple", "router", "shared", "routed", "logits"): + elements = weights[name] // BF16 + active = unique = elements + if name == "routed": + per_expert = elements // c["num_experts"] + active = per_expert * c["num_experts_per_tok"] + unique = per_expert * distinct_experts + rows = 1 if name == "logits" else tokens + op(name + " matrices", 2 * active * rows, BF16 * unique) + + layers = c["num_hidden_layers"] + qsa = layers // c["full_attention_interval"] + ratio, budget = c["indexer_compress_ratio"], c["indexer_budget"] + selected = sum(min(s // ratio * ratio, budget) + s % ratio for s in positions) + kv_width = 2 * c["head_dim"] * BF16 + # QK and AV over selected token rows. Prefill historical KV rereads depend + # on tiling. Decode streams the selected local KV rows once in this scenario. + traffic = tokens * kv_width + if phase == "decode": + traffic += selected * kv_width + op("QSA core", qsa * 4 * (c["num_attention_heads"] // TP) * c["head_dim"] * selected, + qsa * traffic) + + # An ideal BF16 index score is one dot per query head and complete key + # group. Count a single pass over compressed keys for the decode query. + complete_groups = sum(s // ratio for s in positions) + index_dim = c["indexer_head_dim"] + op("QSA index scores", qsa * 2 * c["indexer_n_heads"] * index_dim * complete_groups, + qsa * complete_groups * index_dim * BF16 if phase == "decode" else 0) + + # One final FP32 state write after prefill, or one read and write at decode. + # The chunked prefill and recurrent kernel's internal traffic is unresolved. + recurrent_bytes = ((layers - qsa) * (c["linear_num_value_heads"] // TP) + * c["linear_key_head_dim"] * c["linear_value_head_dim"] * 4) + op("GDN recurrent state", hbm=recurrent_bytes * (2 if phase == "decode" else 1)) + + # Two decoder hidden-state reductions per layer; ring send volume per rank. + payload = tokens * c["hidden_size"] * BF16 + op("decoder TP reductions", tx=2 * layers * (2 * (TP - 1) * payload // TP)) + result = phase_floors({ + "phase": phase, "model_id": facts["model"], "hardware_id": hardware["hardware_id"], + "layout": "TP4/ETP4, EP1, PP1, CP1, DP1", "tokens_per_step": tokens, "ops": ops, + "assumptions": ["One sequence, unquantized weights, BF16 activations, main KV and index.", + "One HBM stream per distinct matrix per forward, ring, zero startup."], + }, hardware) + if result["analysis_status"] != "COMPUTED": + raise ValueError(result["unknowns"]) + times = {key: value / hardware["rates"][key]["value"] for key, value in + result["actual_resource_totals"].items()} + time = result["datasheet_resource_time_s"] + return {"visible_tokens": positions[-1], "distinct_experts_per_layer": distinct_experts, + "demand_per_rank": result["actual_resource_totals"], "seconds_by_resource": times, + "resource_max_s": time, "binding": result["datasheet_binding_resources"], + "tokens_per_s_at_resource_max": tokens / time, + "serial_group_s": result["serial_estimate_s"]} + + +def analyze(facts, prompt, output): + c = facts["text_config"] + if min(prompt, output) < 1 or prompt + output - 1 > c["max_position_embeddings"]: + raise ValueError("Use positive lengths within the model context") + ledger = text_weights(c) + checkpoint = facts["checkpoint"] + if (schema_digest(ledger.headers) != checkpoint["text_schema_sha256"] + or len(ledger.headers) != checkpoint["text_tensors"]): + raise ValueError("Derived text inventory differs from the pinned safetensors headers") + + top_k = c["num_experts_per_tok"] + prefill = [phase_reference(facts, ledger.rank_bytes, "prefill", range(1, prompt + 1), unique) + for unique in sorted({top_k, min(c["num_experts"], top_k * prompt)})] + # Prefill emits the first output token. Each remaining token needs one forward. + first_decode = last_decode = None + decode_sum = 0.0 + for visible in range(prompt + 1, prompt + output): + last_decode = phase_reference(facts, ledger.rank_bytes, "decode", [visible], top_k) + if first_decode is None: + first_decode = last_decode + decode_sum += last_decode["resource_max_s"] + decode_steps = output - 1 + weight_bytes = sum(ledger.rank_bytes.values()) + peak_cache = cache_payload(c, prompt + output - 1) + nominal_capacity = facts["nominal_hbm_bytes_per_gpu"] + if weight_bytes + peak_cache["total"] > nominal_capacity: + raise ValueError("The logical weight and cache payload alone exceeds nominal HBM capacity") + return { + "basis": "datasheet, selected work and explicit traffic scenario", + "whole_model": {"analysis_status": "INSUFFICIENT_EVIDENCE", + "qualified_bound_s": None, "measured_latency_s": None, + "unknowns": ["actual H200 clocks and fabric", "kernel dispatch and padding", + "HBM reuse, intermediates, activation traffic and GDN math", + "allocated memory, collective startup and scheduling"]}, + "model": facts["model"], "revision": facts["revision"], "engine": facts["engine"], + "hardware": facts["hardware"]["hardware_id"], "tp": TP, "etp": TP, "ep": 1, + "prompt_tokens": prompt, "output_tokens": output, "batch": 1, "mtp": False, + "text_tensor_count": len(ledger.headers), "text_checkpoint_bytes": ledger.stored_bytes, + "nominal_hbm_bytes_per_gpu": nominal_capacity, "allocated_fit": "unverified", + "rank_logical_weight_bytes": weight_bytes, + "rank_weight_bytes_by_family": dict(ledger.rank_bytes), + "rank_cache_payload_bytes_after_prefill": cache_payload(c, prompt), + "rank_cache_payload_bytes_last_forward": peak_cache, + "prefill": prefill, "decode_steps": decode_steps, + "first_decode": first_decode, "last_decode": last_decode, + "mean_decode_resource_ms": 1000 * decode_sum / decode_steps if decode_steps else None, + "decode_tokens_per_s_at_resource_max": decode_steps / decode_sum if decode_steps else None, + "request_resource_s": [row["resource_max_s"] + decode_sum for row in prefill], + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--prompt-tokens", type=int, default=8192) + parser.add_argument("--output-tokens", type=int, default=256) + parser.add_argument("--verify-hub-headers", action="store_true", + help="Re-read the pinned public config, index and all shard headers") + args = parser.parse_args() + facts = json.loads(FACTS.read_bytes()) + result = analyze(facts, args.prompt_tokens, args.output_tokens) + if args.verify_hub_headers: + result["source_audit"] = audit_headers(facts, text_weights(facts["text_config"]).headers) + print(json.dumps(result, indent=2, allow_nan=False)) + + +if __name__ == "__main__": + main() diff --git a/src/inferrsi/knowledge/compositions/model-sol-analysis.json b/src/inferrsi/knowledge/compositions/model-sol-analysis.json new file mode 100644 index 000000000..b156ac3ca --- /dev/null +++ b/src/inferrsi/knowledge/compositions/model-sol-analysis.json @@ -0,0 +1,275 @@ +{ + "authority": "checkout", + "metadata": { + "id": "model-sol-analysis", + "kind": "skill", + "entrypoint": "playbooks/measurement/model-sol-analysis/SKILL.md", + "title": "Walk a whole model to per-phase (prefill, decode) speed-of-light figures under a declared parallel layout - anchored counts, the fused graph the framework runs, per-rank geometry, explicit communication and KV growth laws - and report a resource-total bound apart from a serial per-op estimate.", + "origin": [ + "external" + ], + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/model-sol-analysis/SKILL.md", + "sha256": "b7a2dc5cc051427b12e195652c20f7ee337326a6954a44f811f8b06d21b63e8a" + }, + { + "type": "git", + "url": "https://github.com/shenh10/HuggingArch", + "commit": "e69d20a028e5b17524aa48b53bddf8b9aad5d15b", + "revision_precision": "full", + "license": "MIT", + "observed_at": "2026-11-10", + "paths": [ + "docs/inference_cost_model.md", + "docs/evaluation_model.md", + "docs/symbolic_evaluation.md", + "docs/design.md", + "docs/parallelism.md", + "docs/kv_cache_storage.md", + "docs/attention_families.md", + "docs/moe_expert_axis.md", + "docs/quantization.md", + "docs/validation.md", + "docs/measured_calibration.md", + "docs/known_limitations.md", + "README.md", + "backend/inference/row_roofline.py", + "backend/inference/phases.py", + "backend/inference/phase_formulas.py", + "backend/arch/eval/binding.py", + "backend/arch/eval/transforms.py", + "backend/arch/eval/fusion.py", + "backend/inference/framework_bindings/__init__.py", + "backend/arch/layout/weight_endpoints.py", + "backend/arch/layout/layout.py", + "backend/arch/layout/workload.py", + "backend/arch/layout/physical.py", + "backend/arch/layout/comm_volume.py", + "backend/inference/comm_cost.py", + "backend/arch/eval/cache.py", + "backend/arch/eval/formats.py", + "backend/arch/dtypes.py", + "backend/arch/validate/_axioms.py", + "backend/arch/validate/_orchestrator.py", + "backend/arch/validate/_type_contracts.py", + "backend/inference/sol_closure.py", + "backend/inference/op_calibration.py", + "backend/inference/calibration_overlay.py", + "backend/measure/lookup.py" + ], + "identity": "references/huggingarch-source-identity.json", + "readset": "references/huggingarch-model-sol.md", + "note": "Cited paths only; the identity file records every retrieved file, its digests and its inspection scope, including files read but not cited. performance-ceiling-analysis keeps its own earlier pin for the checkpoint anchor." + } + ], + "applicability": { + "scope": "Model-level prefill and decode speed-of-light analysis for decoder-only (optionally multimodal) inference under a declared parallel layout; extends performance-ceiling-analysis L1 from one operation to a whole model without replacing its evidence rules", + "hardware": "any; per-dtype peaks, memory bandwidth and link bandwidths must be supplied with sources", + "prerequisites": "Model config and forward source at a pinned revision, the checkpoint's tensor headers where a checkpoint exists, the serving framework release that will run, and the layout and workload; reading the skill does not authorize execution", + "input_contract": "Model config, forward source and checkpoint headers; serving framework and release with source anchors for every fusion; per-world parallel degrees, ranks per node and node count; batch, input, output, prefix and verify tokens, and the measured expert load skew when expert placement makes per-rank work depend on routing; per-dtype compute peaks at the sustained clock, memory and link bandwidths with sources; any launch floor or link latency labelled as an assumption", + "produced_artifact": "A per-phase table with per-op counts and binding resource, per-resource totals, the conditional bound and its binding resources, the serial per-op estimate, headline TTFT, TPOT and throughput figures each labelled bound or estimate, every anchor and gate result, assumptions and unknowns; analytical only, not a measured result", + "failure_modes": [ + "The serial per-op sum is reported as a bound, or used to reject a faster measurement", + "Counts come from the unfused graph, overstating launches and activation round-trips, or from fusions the framework does not run, understating bytes", + "A degree that does not divide a weight is silently replaced by a divisor that does", + "Expert load skew is left at its default, making routed time and exchange optimistic", + "A windowed layer is priced as global, or a dense layer as windowed, because the cache growth law was not checked", + "Prefill attention is counted as a full square rather than causal pairs", + "An unmeasured launch floor or link latency, or a spec-sheet peak below the sustained clock, enters the bound", + "A measured envelope replaces the analytical figure instead of sitting beside it" + ], + "refusal_point": "Stops when an anchor gate fails or cannot be judged, when a required peak, used fabric rate or required expert-parallel load skew is missing, or when weights plus one request's KV do not fit a rank. Unanchored fusion permits only a labelled unfused estimate when its counts are available." + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "The serial estimate assumes full compute/memory overlap within an op, no overlap between ops and no pipeline bubble. The source uses one link latency for every fabric.", + "Counts are only as good as the anchors and the framework binding behind them; behaviour that lives only in weights or custom runtime code is out of reach.", + "Decoder-only models, optionally multimodal; encoder-decoder models are out of scope.", + "Checkout-only local skill; no automatic execution or promotion.", + "Only declared references are required; other cross-skill links are navigation.", + "Historical revisions require a matching checkout or a retained store." + ], + "attribution": [ + { + "type": "git", + "url": "https://github.com/shenh10/HuggingArch", + "commit": "e69d20a028e5b17524aa48b53bddf8b9aad5d15b", + "revision_precision": "full", + "license": "MIT", + "observed_at": "2026-11-10", + "paths": [ + "docs/inference_cost_model.md", + "docs/evaluation_model.md", + "docs/symbolic_evaluation.md", + "docs/design.md", + "docs/parallelism.md", + "docs/kv_cache_storage.md", + "docs/attention_families.md", + "docs/moe_expert_axis.md", + "docs/quantization.md", + "docs/validation.md", + "docs/measured_calibration.md", + "docs/known_limitations.md", + "README.md", + "backend/inference/row_roofline.py", + "backend/inference/phases.py", + "backend/inference/phase_formulas.py", + "backend/arch/eval/binding.py", + "backend/arch/eval/transforms.py", + "backend/arch/eval/fusion.py", + "backend/inference/framework_bindings/__init__.py", + "backend/arch/layout/weight_endpoints.py", + "backend/arch/layout/layout.py", + "backend/arch/layout/workload.py", + "backend/arch/layout/physical.py", + "backend/arch/layout/comm_volume.py", + "backend/inference/comm_cost.py", + "backend/arch/eval/cache.py", + "backend/arch/eval/formats.py", + "backend/arch/dtypes.py", + "backend/arch/validate/_axioms.py", + "backend/arch/validate/_orchestrator.py", + "backend/arch/validate/_type_contracts.py", + "backend/inference/sol_closure.py", + "backend/inference/op_calibration.py", + "backend/inference/calibration_overlay.py", + "backend/measure/lookup.py" + ], + "identity": "references/huggingarch-source-identity.json", + "readset": "references/huggingarch-model-sol.md", + "note": "Cited paths only; the identity file records every retrieved file, its digests and its inspection scope, including files read but not cited. performance-ceiling-analysis keeps its own earlier pin for the checkpoint anchor." + } + ], + "empirical_validation": "not_run", + "required_resources": [ + "playbooks/measurement/model-sol-analysis/SKILL.md", + "playbooks/measurement/model-sol-analysis/references/huggingarch-model-sol.md", + "playbooks/measurement/model-sol-analysis/references/huggingarch-source-identity.json", + "playbooks/measurement/model-sol-analysis/references/model-sol-contract.md", + "playbooks/measurement/model-sol-analysis/references/model-sol-example.json", + "playbooks/measurement/model-sol-analysis/references/qwen38-h200-tp4.json", + "playbooks/measurement/model-sol-analysis/references/qwen38-h200-tp4.md", + "playbooks/measurement/model-sol-analysis/scripts/model_sol.py", + "playbooks/measurement/model-sol-analysis/scripts/qwen38_checkpoint.py", + "playbooks/measurement/model-sol-analysis/scripts/qwen38_h200_tp4.py" + ], + "composition": { + "when": {}, + "license": "Apache-2.0", + "permissions": { + "read": true, + "retain": true, + "redistribute": true + }, + "nodes": { + "navigation": { + "ref": "checkout:model-sol-analysis.original.navigation", + "revision": "sha256:b91edc5a41419aac7181f8b6eecac6c362ac45c0181cbccda43dc741e55ac386" + }, + "decision": { + "ref": "checkout:model-sol-analysis.original.decision", + "revision": "sha256:01aba5c2a76cba1fe2085c0b16eb73212a8c298f71d7d6059ddea4b77af7d78f" + }, + "procedure": { + "ref": "checkout:model-sol-analysis.original.procedure", + "revision": "sha256:e85af22d6e6e99dcaa3d0b215cd0b2b5534279caf38416a5c61ce309d91a98a2", + "requires": [ + "decision" + ] + }, + "original": { + "ref": "checkout:model-sol-analysis.original", + "revision": "sha256:ea23941100c5b64d594377f37c8fddb136863568a88b441acb0dab4b38e46dd2" + }, + "huggingarch-model-sol": { + "ref": "checkout:model-sol-analysis.huggingarch-model-sol", + "revision": "sha256:50aff155e09d4be3acb962dee23afa91606ef3aa21d12d00cdd3a2d5aef52733" + }, + "huggingarch-source-identity": { + "ref": "checkout:model-sol-analysis.huggingarch-source-identity", + "revision": "sha256:f8933c733108e2f52d323d2d0fd79911064b4fd4d09b6bdea52db7ed0fdc0bb3" + }, + "model-sol-contract": { + "ref": "checkout:model-sol-analysis.model-sol-contract", + "revision": "sha256:d9bda7116bd04f3cbe4e71c8303ba35e4244f30c4a0f2fcdceb2a6e61c0ffcff" + }, + "model-sol-example": { + "ref": "checkout:model-sol-analysis.model-sol-example", + "revision": "sha256:a30f7d65a85a7c3a6a8f1266b1433a0f56337266fb5b8eaa5ef61118e850f741" + }, + "qwen38-h200-tp4-inputs": { + "ref": "checkout:model-sol-analysis.qwen38-h200-tp4-inputs", + "revision": "sha256:b38cca3baa37e76d342710e029721d6ec9b5b92d8a8111662a75f5b7e2a665e5" + }, + "qwen38-h200-tp4": { + "ref": "checkout:model-sol-analysis.qwen38-h200-tp4", + "revision": "sha256:2dd4b526da5451dba496ca3bd0c159ca98844cd4ce2db7f91888a8c52df232ad" + }, + "model-sol": { + "ref": "checkout:model-sol-analysis.model-sol", + "revision": "sha256:560a10c7beadc9782f74419523761bce5dc56bcb4dc8df0e3818d7acc15b12e0" + }, + "qwen38-checkpoint": { + "ref": "checkout:model-sol-analysis.qwen38-checkpoint", + "revision": "sha256:a31b524ef06def5dd37ded62e4f7550d1407a06a899a339ce8310039666d2318" + }, + "qwen38-h200-tp4-calculator": { + "ref": "checkout:model-sol-analysis.qwen38-h200-tp4-calculator", + "revision": "sha256:d1fcf64daaf8fb2d932af82f5b124cc42077e7943b28ec3bb963c8681e5aa6be" + } + }, + "routes": { + "navigation": { + "layer": "L0", + "required": [ + "navigation" + ] + }, + "decision": { + "layer": "L1", + "required": [ + "decision" + ] + }, + "procedure": { + "layer": "L2", + "required": [ + "procedure" + ] + }, + "originals": { + "layer": "L3", + "required": [ + "original", + "huggingarch-model-sol", + "huggingarch-source-identity", + "model-sol-contract", + "model-sol-example", + "qwen38-h200-tp4-inputs", + "qwen38-h200-tp4", + "model-sol", + "qwen38-checkpoint", + "qwen38-h200-tp4-calculator" + ] + } + } + } + }, + "directory_resources": { + "playbooks/measurement/model-sol-analysis/SKILL.md": "original", + "playbooks/measurement/model-sol-analysis/references/huggingarch-model-sol.md": "huggingarch-model-sol", + "playbooks/measurement/model-sol-analysis/references/huggingarch-source-identity.json": "huggingarch-source-identity", + "playbooks/measurement/model-sol-analysis/references/model-sol-contract.md": "model-sol-contract", + "playbooks/measurement/model-sol-analysis/references/model-sol-example.json": "model-sol-example", + "playbooks/measurement/model-sol-analysis/references/qwen38-h200-tp4.json": "qwen38-h200-tp4-inputs", + "playbooks/measurement/model-sol-analysis/references/qwen38-h200-tp4.md": "qwen38-h200-tp4", + "playbooks/measurement/model-sol-analysis/scripts/model_sol.py": "model-sol", + "playbooks/measurement/model-sol-analysis/scripts/qwen38_checkpoint.py": "qwen38-checkpoint", + "playbooks/measurement/model-sol-analysis/scripts/qwen38_h200_tp4.py": "qwen38-h200-tp4-calculator" + } +} diff --git a/tests/knowledge/test_atomic_model_sol.py b/tests/knowledge/test_atomic_model_sol.py new file mode 100644 index 000000000..c3494d602 --- /dev/null +++ b/tests/knowledge/test_atomic_model_sol.py @@ -0,0 +1,176 @@ +"""Reopen the released model-level speed-of-light guide and its attachments through the Reader.""" + +import json +import shutil +import subprocess +import sys +from pathlib import PurePosixPath + +import pytest + +from inferrsi.knowledge.atomic_build import build_generation +from inferrsi.knowledge.atomic_generation import InstalledGeneration +from inferrsi.knowledge.catalog import _skill_search_source +from inferrsi.knowledge.decision_cards import DecisionSource +from tests.knowledge.test_atomic_casebooks import ( + ATOMS, + FIXTURES, + RELEASE_COMMIT, + assert_empty, + canonical, + digest, + select, +) +from tests.knowledge.test_atomic_generation import RELEASE_ROOT, make_author_root +from tests.knowledge.test_atomic_reader import allow +from tools.plugin_bundle import _io_path + +NAME = "model-sol-analysis" +REF = "checkout:" + NAME +LIBRARY = "src/inferrsi/knowledge/data/skill_library/" +RELEASE = json.loads((FIXTURES / "playbook-domain-v0.3.4.json").read_bytes())["refs"][REF] + + +@pytest.fixture(scope="module") +def installed(tmp_path_factory): + root = tmp_path_factory.mktemp("model-sol") + author = make_author_root(root) + release = _io_path(root / "release") + shutil.copytree(RELEASE_ROOT, release) + spec_file = ATOMS.parent / "compositions" / (NAME + ".json") + shutil.copyfile(spec_file, author / "compositions" / spec_file.name) + spec = json.loads(spec_file.read_bytes()) + nodes = spec["metadata"]["composition"]["nodes"] + assert spec["directory_resources"].keys() == RELEASE["required_resources"].keys() + for logical, label in spec["directory_resources"].items(): + atom = ATOMS / (nodes[label]["ref"].removeprefix("checkout:") + ".json") + shutil.copyfile(atom, author / "atoms" / atom.name) + (resource,) = json.loads(atom.read_bytes())["content"].values() + raw = (ATOMS / resource["path"]).read_bytes() + assert digest(raw) == RELEASE["required_resources"][logical] + for dest in (author / "atoms" / resource["path"], release / LIBRARY / logical): + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(raw) + target = root / "installed" + generation = build_generation( + author, target, permits=allow, source_roots={RELEASE_COMMIT: release} + ) + return InstalledGeneration(target, expected=generation) + + +def test_original_paths_permissions_and_released_decision(installed): + _, bundle = installed.read_resolved(REF, revision=installed.catalog[REF]["revision"]) + assert bundle.view()["resources"] == RELEASE["required_resources"] + assert len(bundle.content) == 10 and sum(map(len, bundle.content.values())) == 130869 + assert bundle.dependencies == RELEASE["dependencies"] == {} + metadata = dict(bundle.metadata) + metadata.pop("composition") + metadata["sources"] = metadata["sources"][1:] + assert ( + digest(canonical(metadata)) + == "ae20a01935831d1ceb202eb125b6fb80f52e222537aa1603fc7cf34c32769e06" + ) + layers = {} + for level in ("L0", "L1", "L2", "L3"): + result = select(installed, REF, level, 1_000_000) + size = sum(map(len, result.bodies)) + assert result.receipt["status"] == "delivered" and result.receipt["body_bytes"] == size + assert select(installed, REF, level, size) == result + short = select(installed, REF, level, size - 1) + assert_empty(short, "over_budget") + assert short.receipt["required_bytes"] == size + assert_empty( + select(installed, REF, level, size, revision=RELEASE["revision"]), + "unavailable_revision", + ) + for denied in {REF, *(row["ref"] for row in result.receipt["delivered"])}: + incomplete = select( + installed, REF, level, size, permits=lambda pin, op: pin.ref != denied + ) + assert_empty(incomplete, "permission_denied") + for body, row in zip(result.bodies, result.receipt["delivered"], strict=True): + lo, hi = row["source_byte_range"] + path = row["source_path"].removeprefix(LIBRARY) + assert body == bundle.content[path][lo:hi] + assert row["source"]["commit"] == RELEASE_COMMIT + assert row["source_range_verification"] == "verified_at_build" + assert row["source_sha256"] == digest(body) + layers[level] = result.bodies + guide = RELEASE["entrypoint"] + (decision,) = layers["L1"] + assert bundle.content[guide].startswith(layers["L0"][0]) + assert layers["L2"][0] == decision and b"".join(layers["L2"]) == bundle.content[guide] + assert layers["L3"] == tuple(bundle.content[path] for path in sorted(bundle.content)) + _, fields = _skill_search_source(decision.decode()) + card = DecisionSource(REF, RELEASE["revision"], "skill", guide, guide, fields).project()["card"] + assert card["status"] == "partial" and card["missing_fields"] == ["validation"] + assert len(canonical(card)) == RELEASE["card_bytes"] == 11661 + assert digest(canonical(card)) == RELEASE["card_sha256"] + + +def test_huggingarch_credit_scope_and_navigation(installed): + _, bundle = installed.read_resolved(REF, revision=installed.catalog[REF]["revision"]) + (credit,) = bundle.metadata["attribution"] + assert bundle.metadata["sources"][1:] == [credit] + assert credit["url"] == "https://github.com/shenh10/HuggingArch" + assert credit["commit"] == "e69d20a028e5b17524aa48b53bddf8b9aad5d15b" + assert credit["license"] == "MIT" and len(set(credit["paths"])) == 36 + assert credit["readset"] == "references/huggingarch-model-sol.md" + assert credit["identity"] == "references/huggingarch-source-identity.json" + base = PurePosixPath(RELEASE["entrypoint"]).parent + identity = json.loads(bundle.content[(base / credit["identity"]).as_posix()]) + verified = identity["verification"] + assert verified["locally_verified"] is False + assert verified["native_execution"] == verified["empirical_validation"] == "not_run" + nodes = bundle.metadata["composition"]["nodes"] + manifest = json.loads((ATOMS.parent / "compositions" / (NAME + ".json")).read_bytes()) + for path, label in manifest["directory_resources"].items(): + node = nodes[label] + _, atom = installed.read_resolved(node["ref"], revision=node["revision"]) + rel = PurePosixPath(path).relative_to(base).as_posix() + credits = [credit] if rel in {"SKILL.md", credit["identity"], credit["readset"]} else [] + assert atom.metadata["attribution"] == credits + assert atom.metadata["sources"][1:] == credits + + links = RELEASE["relative_guide_links"].values() + outside = [link["path"] for link in links if not link["in_directory"]] + assert len(outside) == 5 and len(set(outside)) == 4 + assert set(outside).isdisjoint(bundle.content) + inside = [link["path"] for link in links if link["in_directory"]] + assert len(inside) == 6 and set(inside).issubset(bundle.content) + assert NAME not in installed.skills + + +def test_released_qwen_calculator_from_installed_l3(installed, tmp_path): + result = select(installed, REF, "L3", 1_000_000) + prefix = PurePosixPath(LIBRARY, RELEASE["entrypoint"]).parent + for row, body in zip(result.receipt["delivered"], result.bodies, strict=True): + dest = tmp_path / PurePosixPath(row["source_path"]).relative_to(prefix) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(body) + command = [sys.executable, "-B", str(tmp_path / "scripts" / "qwen38_h200_tp4.py")] + for arguments, tokens, steps, times in ( + ([], (8192, 256), 255, [0.2785117744889662, 0.2785117744889662]), + (["--prompt-tokens", "1", "--output-tokens", "1"], (1, 1), 0, [0.0009398058666666666]), + ): + completed = subprocess.run( + command + arguments, cwd=tmp_path, capture_output=True, check=True + ) + report = json.loads(completed.stdout) + assert completed.stderr == b"" + assert (report["prompt_tokens"], report["output_tokens"]) == tokens + assert report["decode_steps"] == steps and report["request_resource_s"] == pytest.approx( + times + ) + assert report["revision"] == "812d96e10a0dd82b69d749e68693698cf6c36daa" + assert report["hardware"] == "H200-SXM" and report["tp"] == 4 + assert report["allocated_fit"] == "unverified" + whole = report["whole_model"] + assert whole["analysis_status"] == "INSUFFICIENT_EVIDENCE" + assert whole["qualified_bound_s"] is None and whole["measured_latency_s"] is None + invalid = subprocess.run(command + ["--prompt-tokens", "0"], cwd=tmp_path, capture_output=True) + assert invalid.returncode != 0 and not invalid.stdout + assert ( + invalid.stderr.splitlines()[-1] + == b"ValueError: Use positive lengths within the model context" + )