diff --git a/src/inferrsi/knowledge/atoms/playbooks/video-diffusion-optimization.md b/src/inferrsi/knowledge/atoms/playbooks/video-diffusion-optimization.md new file mode 100644 index 000000000..508826837 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/video-diffusion-optimization.md @@ -0,0 +1,219 @@ +--- +name: video-diffusion-optimization +description: 'Run and verify goal-driven video diffusion optimization, backend-agnostic. Use when the user asks for latency, RTF, throughput, or memory targets across VLM, DiT, MoE, attention, or VAE, on any accelerator. Not for text-only LLMs.' +metadata: + inferrsi: | + { + "schema_version": 1, + "profile": "local-skill-v1", + "kind": "skill", + "status": "candidate", + "origin": [ + "first-party" + ], + "tags": [ + "video-diffusion", + "dit", + "moe", + "attention", + "vae", + "performance", + "profiling", + "serving", + "optimization" + ], + "empirical_validation": "not_run", + "verification": { + "locally_verified": false, + "evidence_level": "guidance", + "note": "Procedure is first-hand workflow guidance. The linked field notes are not reproducible as published. No acceptance campaign under this repository's evidence contract backs this skill, and no public performance claim is made." + }, + "applicability": { + "scope": "Backend-agnostic video diffusion inference and serving optimization", + "hardware": "Any accelerator (Ascend NPU, CUDA GPU, and others); operator names, memory layouts, and profiler references are re-derived per backend", + "prerequisites": "A reproducible benchmark, a frozen quality check, and numeric gates defined in the governing acceptance issue" + }, + "limitations": [ + "Backend-agnostic skeleton only. The first-hand field notes are Ascend-specific and live in the ascend-video-diffusion-optimization skill; every operator, layout and profiler reference (TransData, FRACTAL_NZ, CANN) must be re-derived per backend.", + "Candidate workflow guidance; not independently validated.", + "Model identifiers, campaign revisions, and numeric gates are intentionally excluded and remain issue-scoped." + ], + "provenance_readsets": [], + "consumption_mode": "packaged" + } +--- + +# Video Diffusion Optimization + +Status: candidate workflow guidance, backend-agnostic. The procedure is first-hand and has not been independently validated. Keep model identifiers, campaign revisions, and numeric gates out of this file; they belong to an acceptance issue and its frozen evidence. + +Own the performance objective through implementation and final verification. Do not stop after profiling, proposing changes, or showing a faster microbenchmark. Continue the measure-change-verify loop until the target is met, the authorized budget is exhausted, or an external blocker prevents execution. + +This skeleton is backend-agnostic. Operator names, memory layouts, and profiler references are backend-specific. The `ascend-video-diffusion-optimization` skill under `systems/platforms/ascend/` specializes this skeleton with Ascend annotations (`TransData`, `FRACTAL_NZ`, `CANN`) and first-hand field notes; re-derive those per backend before following the candidate-selection sections below. + +Verify every stage against the packaged [benchmark design](../../measurement/inference-benchmark-design/SKILL.md) and [evidence discipline](../../../workflows/governance/rsi-evidence/SKILL.md). A microbenchmark or operator parity check is not end-to-end evidence. + +## 1. Freeze The Goal Contract + +Write the contract before editing code: + +- Primary metric and direction, such as a latency, RTF, throughput, or peak-memory bar. +- Exact timing boundary and RTF denominator. +- Required workload set: representative short input, production-shaped input, longest supported input, and held-out cases. +- Quality gates, such as tensor tolerance, image or video metrics, recognition success, prompt adherence, or human review. +- Resource gates: no OOM, maximum memory, device count, and prohibited offload. +- Approximation policy: exact, numerically tolerant, perceptually gated, or task-quality gated. +- Warmup count, measured repetitions, aggregation rule, and maximum acceptable variance. +- Optimization budget: allowed code changes, lossy methods, experiment count, and wall time. + +Numeric gates come from the governing acceptance issue. Do not invent them in this skill, in workflow defaults, or in reusable recipes. + +If the user supplied a target, preserve it exactly. If no numeric target exists, establish one before claiming success. A vague request to "make it faster" permits exploration, not a `PASS`. + +Freeze model and checkpoint revision, architecture mode, hardware SKU, device mapping, runtime and custom-op revisions, input, prompt, size, frames, FPS, steps, guidance, seed, dtype, scheduler, and output validator. + +Align actual initial noise or latent across frameworks. Equal seed values are insufficient when RNG advancement differs. + +## 2. Build A Reproducible Baseline + +Start from a clean process. Exclude warmup from steady-state measurements and report cold start separately. + +Measure synchronized wall time and peak memory for: + +1. Input decode and preprocessing. +2. Each condition encoder and vision path. +3. Source-video VAE encode when present. +4. DiT denoising, with attention, MoE or MLP, normalization, and residual attribution when needed. +5. VAE decode. +6. Postprocessing, layout conversion, device-to-host transfer, and encoding. + +Collect at least three measured repetitions; use five or more for final acceptance. Preserve raw samples and report median plus range or IQR. On a shared machine, interleave baseline and candidate in the same allocation window. + +Do not optimize while the baseline is unstable. Investigate device health, neighbor load, thermal or frequency state, compilation, cache state, and synchronization until variance is within the contract. + +Compute an Amdahl ceiling from non-overlapping stage wall-time fractions. Use it to rank work and to expose when the requested target requires multiple stages or an algorithmic change. + +## 3. Run The Optimization Loop + +Maintain an experiment ledger. For every round record: + +- Hypothesis and profiler evidence. +- Expected end-to-end gain and resource cost. +- Exact code or configuration delta. +- Quality and correctness result. +- Raw performance samples, aggregate, peak memory, and variance. +- Verdict: keep, revert, or inconclusive. + +Execute this loop: + +1. Profile the current accepted state. +2. Select the largest removable exposed cost, not the largest summed kernel duration. +3. Make one bounded change, keeping one declared plane per step. +4. Run the fastest correctness gate that can reject it. +5. Run a short A/B probe with identical workload and synchronization. +6. Revert regressions and failed quality gates. +7. Keep a win only when it exceeds measurement noise and does not violate any gate. +8. Re-profile the accepted state because the bottleneck may move. +9. Evaluate the goal contract with `scripts/evaluate_target.py`. +10. Continue until final acceptance passes or the budget is exhausted. + +Do not leave rejected experimental code enabled. Preserve only logs, evidence, and accepted production changes. + +## 4. Choose Candidates From Evidence + +### Condition And Scheduling + +- Verify visual pixel, frame, and token budgets before changing kernels. +- Keep frequently reused condition encoders resident only when transfer or reload cost dominates and memory headroom permits. +- Quantize large language-MLP weights selectively; keep attention, embeddings, normalization, routers, and vision paths in higher precision until separately validated. +- Treat condition/VAE overlap as a conditional candidate, never a default optimization. Draw the request-level dependency DAG before creating streams. Record each stage's inputs, outputs, mutable state, consumers, and earliest legal start. +- Permit overlap only when condition encoding does not consume VAE latents or metadata, VAE does not consume condition outputs, neither stage mutates shared buffers or module state, and both outputs are needed only at a later join. +- Prove runtime safety separately from logical independence. Verify every operator supports the selected streams, establish producer-consumer events, record tensor lifetimes on side streams, and join both streams before their first common consumer. +- Check resource compatibility before enabling overlap. Concurrent work must not cause OOM, allocator pressure, workspace collision, or enough compute and bandwidth contention to erase the wall-time gain. +- If only subgraphs are independent, overlap only those subgraphs. Keep the dependent prefix or suffix serial. If any dependency or lifetime is uncertain, preserve serial execution. +- Accept overlap only when the profiler timeline shows real concurrency and synchronized end-to-end A/B measurements improve beyond noise while quality and memory gates pass. The maximum theoretical saving is bounded by the shorter exposed stage; configured streams alone are not evidence. +- Localize cold start around vision embeddings, patch merging, compilation, weight loading, and format conversion. + +### DiT, MoE, And Quantization + +- Prefer large linear projections and expert weights as initial quantization candidates. +- Instantiate final quantized modules directly to avoid simultaneous full-precision and quantized copies. +- Release loader references before format conversion and before loading the next component. +- Materialize contiguous weights before any backend-specific packed-layout conversion when source strides can differ from physical order. +- Measure intermediate cast and copy cost. Treat changed intermediate precision as approximate unless equivalence is proven. +- Validate attention and MoE independently before combining optimizations. + +### Attention + +- Establish a dense fused baseline first. +- Use sparse attention only when token geometry and sequence length amortize setup cost. +- Derive dense-prefix and sparse-grid regions from actual token packing. +- Require eligibility checks and a dense fallback. +- Tune activation step, skipped layers, and sparsity separately. +- Re-profile after a kernel win; VAE, MoE, casts, or synchronization may become dominant. + +### VAE And Long Video + +- Use no-tiling decode only when the measured shape has safe memory headroom. +- Enable temporal or spatial chunking dynamically for larger shapes. +- Replace repeated growing concatenation operations with list accumulation and one final concatenation. +- Attribute layout-conversion and copy costs before designing fusion or format-preserving wrappers. +- Distinguish capacity failure, model temporal-quality failure, and algorithmic cost growth. +- Derive chunk length and overlap experimentally. For text or sharp structures, compare midpoint hard cuts against blending. +- Do not move VAE to host when RTF and numerical consistency are hard gates unless explicitly authorized. + +## 5. Protect Correctness + +When output diverges: + +1. Verify checkpoint structure and architecture mode. +2. Align media preprocessing, frame sampling, resize, normalization, text cleanup, tokenization, masks, and padding. +3. Inject identical initial latents and compare one denoising step. +4. Compare scheduler coefficients, patch order, and unpatchify order. +5. Find the first divergent block, then inspect normalization, attention, routing, experts, residual, and projection. +6. For MoE, verify indices, routing weights, activation semantics, packed weight order, transpose rules, and accelerator layout. +7. Remove dumps, golden injection, and debug-only paths after verification. + +Do not use output hash equality as the only quality proof. Do not label sparse attention, lower precision, or changed accumulation order as lossless without evidence. + +## 6. Final Acceptance + +After the target first appears met, restart from the final code and configuration. Do not validate a stale process or a best-seen intermediate state. + +Run the full acceptance set: + +- At least five interleaved baseline/candidate groups in the same measurement window. +- Representative short, production-shaped, longest supported, and held-out inputs. +- Cold-start and steady-state measurements when loading or compilation changed. +- Primary performance metric, stage breakdown, peak memory, and raw samples. +- Every automatic quality gate plus required visual or task review. +- No OOM, corruption, fallback, hidden host offload, skipped work, or invalid output. + +A local pre-check is available: + +```bash +cp {skill_path}/assets/campaign.template.json campaign.json +# Replace every placeholder with measured samples and the issue-scoped gates. +python3 {skill_path}/scripts/evaluate_target.py campaign.json +``` + +The script checks target attainment, minimum improvement, variance, quality gates, and resource gates. It is an aid, not the verdict. The authoritative verdict comes from the acceptance issue's frozen gates and its `evidence//` tree, and it stays `INCONCLUSIVE` while any required level or artifact is missing. + +Return `PASS` only when the final restarted artifact satisfies the frozen gates, with pinned baseline and candidate revisions and complete evidence. A microbenchmark win, one fast run, a profiler estimate, or an earlier best result is insufficient. + +Return `FAIL` when complete enough evidence shows a gate was not met. Report the measured gap, accepted gains, rejected rounds, binding bottleneck, remaining ceiling, and the next change required. + +Return `INCONCLUSIVE` when a freeze is missing, runs are partial, the environment does not qualify, or required levels were not executed. Report the exact missing prerequisite and preserve the completed evidence. + +## 7. Final Report + +Report: + +- Final verdict: `PASS`, `FAIL`, or `INCONCLUSIVE`. +- Frozen goal and quality contract, with its acceptance issue. +- Baseline and final raw samples, aggregates, variance, RTF, and peak memory. +- End-to-end improvement and whether it exceeds noise. +- Quality and longest-input results. +- Accepted and reverted changes. +- Final artifact revision and exact runtime configuration. +- Remaining gap and ceiling when the target is not met. diff --git a/src/inferrsi/knowledge/atoms/playbooks/video-diffusion-optimization/assets/campaign.template.json b/src/inferrsi/knowledge/atoms/playbooks/video-diffusion-optimization/assets/campaign.template.json new file mode 100644 index 000000000..25fdefa34 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/video-diffusion-optimization/assets/campaign.template.json @@ -0,0 +1,40 @@ +{ + "_readme": [ + "Template only. Every value below is synthetic and must be replaced before use.", + "Numeric gates, workload definitions, and revisions are owned by the governing", + "acceptance issue; they must not be copied into skills, workflow defaults, or", + "reusable recipes. Copy the frozen gates from that issue, then record raw samples", + "from the final restarted artifact. This file is intentionally not campaign evidence." + ], + "primary_metric": { + "name": "", + "direction": "lower", + "target": 3.0, + "minimum_improvement_percent": 5.0, + "max_relative_range": 0.05, + "baseline": [4.0, 4.01, 3.99, 4.0, 4.02], + "candidate": [2.9, 2.91, 2.89, 2.9, 2.9] + }, + "quality_gates": [ + { + "name": "", + "op": ">=", + "threshold": 0.95, + "value": 0.96 + } + ], + "resource_gates": [ + { + "name": "peak_hbm_gib", + "op": "<=", + "threshold": 48.0, + "value": 47.0 + }, + { + "name": "oom_count", + "op": "==", + "threshold": 0.0, + "value": 0.0 + } + ] +} diff --git a/src/inferrsi/knowledge/atoms/playbooks/video-diffusion-optimization/scripts/evaluate_target.py b/src/inferrsi/knowledge/atoms/playbooks/video-diffusion-optimization/scripts/evaluate_target.py new file mode 100644 index 000000000..fa272686f --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/video-diffusion-optimization/scripts/evaluate_target.py @@ -0,0 +1,242 @@ +#!/usr/bin/env python3 +"""Pre-check a campaign's final samples against frozen target and safety gates. + +This is a local aid, not the campaign verdict. The authoritative verdict is +produced by the acceptance issue's frozen gates and its evidence tree, and it +stays INCONCLUSIVE while a required level or artifact is missing. + +Verdicts follow the repository claim contract: PASS, FAIL, INCONCLUSIVE. +An unreadable or malformed input file reports INVALID with exit code 2, which +is a tool error rather than a campaign verdict. + +Exit codes: 0 PASS, 1 FAIL, 2 INVALID, 3 INCONCLUSIVE. +""" + +from __future__ import annotations + +import argparse +import json +import math +import statistics +import sys +from pathlib import Path +from typing import Any + +OPS = { + "<": lambda value, threshold: value < threshold, + "<=": lambda value, threshold: value <= threshold, + ">": lambda value, threshold: value > threshold, + ">=": lambda value, threshold: value >= threshold, + "==": lambda value, threshold: value == threshold, +} + + +def finite_number(value: Any, field: str) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError(f"{field} must be a number") + result = float(value) + if not math.isfinite(result): + raise ValueError(f"{field} must be finite") + return result + + +def samples(value: Any, field: str) -> list[float]: + if not isinstance(value, list) or len(value) < 3: + raise ValueError(f"{field} must contain at least three samples") + return [finite_number(item, f"{field}[{index}]") for index, item in enumerate(value)] + + +def summarize(values: list[float]) -> dict[str, float]: + median = statistics.median(values) + spread = max(values) - min(values) + relative_range = math.inf if median == 0 and spread else ( + 0.0 if median == 0 else spread / abs(median) + ) + return { + "median": median, + "min": min(values), + "max": max(values), + "relative_range": relative_range, + } + + +def evaluate_gates(data: Any, field: str) -> list[dict[str, Any]]: + if data is None: + return [] + if not isinstance(data, list): + raise ValueError(f"{field} must be a list") + + results = [] + for index, gate in enumerate(data): + if not isinstance(gate, dict): + raise ValueError(f"{field}[{index}] must be an object") + name = gate.get("name") + op = gate.get("op") + if not isinstance(name, str) or not name: + raise ValueError(f"{field}[{index}].name must be non-empty") + if not isinstance(op, str) or op not in OPS: + raise ValueError(f"{field}[{index}].op must be one of {sorted(OPS)}") + value = finite_number(gate.get("value"), f"{field}[{index}].value") + threshold = finite_number( + gate.get("threshold"), f"{field}[{index}].threshold" + ) + results.append( + { + "name": name, + "value": value, + "op": op, + "threshold": threshold, + "passed": OPS[op](value, threshold), + } + ) + return results + + +def evaluate(campaign: dict[str, Any]) -> tuple[dict[str, Any], int]: + primary = campaign.get("primary_metric") + if not isinstance(primary, dict): + raise ValueError("primary_metric must be an object") + + name = primary.get("name") + direction = primary.get("direction") + if not isinstance(name, str) or not name: + raise ValueError("primary_metric.name must be non-empty") + if not isinstance(direction, str) or direction not in {"lower", "higher"}: + raise ValueError("primary_metric.direction must be lower or higher") + + target = finite_number(primary.get("target"), "primary_metric.target") + minimum_improvement = finite_number( + primary.get("minimum_improvement_percent"), + "primary_metric.minimum_improvement_percent", + ) + max_relative_range = finite_number( + primary.get("max_relative_range"), "primary_metric.max_relative_range" + ) + if minimum_improvement < 0: + raise ValueError("minimum_improvement_percent must be non-negative") + if max_relative_range < 0: + raise ValueError("max_relative_range must be non-negative") + + baseline_values = samples(primary.get("baseline"), "primary_metric.baseline") + candidate_values = samples(primary.get("candidate"), "primary_metric.candidate") + baseline = summarize(baseline_values) + candidate = summarize(candidate_values) + + if baseline["median"] == 0: + improvement = ( + math.inf + if direction == "higher" and candidate["median"] > 0 + else 0.0 + ) + elif direction == "lower": + improvement = ( + (baseline["median"] - candidate["median"]) + / abs(baseline["median"]) + * 100.0 + ) + else: + improvement = ( + (candidate["median"] - baseline["median"]) + / abs(baseline["median"]) + * 100.0 + ) + + target_passed = ( + candidate["median"] <= target + if direction == "lower" + else candidate["median"] >= target + ) + improvement_passed = improvement >= minimum_improvement + variance_passed = ( + baseline["relative_range"] <= max_relative_range + and candidate["relative_range"] <= max_relative_range + ) + + quality_gates = evaluate_gates(campaign.get("quality_gates"), "quality_gates") + resource_gates = evaluate_gates( + campaign.get("resource_gates"), "resource_gates" + ) + failed_gates = [ + gate for gate in quality_gates + resource_gates if not gate["passed"] + ] + + reasons = [] + if not variance_passed: + verdict = "INCONCLUSIVE" + reasons.append( + "sample variance exceeds max_relative_range, so the comparison is not qualified" + ) + exit_code = 3 + elif failed_gates: + verdict = "FAIL" + reasons.append("one or more quality or resource gates failed") + exit_code = 1 + elif not target_passed: + verdict = "FAIL" + reasons.append("primary metric target was not reached") + exit_code = 1 + elif not improvement_passed: + verdict = "FAIL" + reasons.append("improvement did not exceed the required minimum") + exit_code = 1 + else: + verdict = "PASS" + reasons.append("target, improvement, variance, and automated gates passed") + exit_code = 0 + + result = { + "verdict": verdict, + "reasons": reasons, + "scope_note": ( + "Local pre-check only. A public PASS additionally requires pinned " + "baseline and candidate revisions, validators frozen before candidate " + "search, and a complete evidence tree for the campaign." + ), + "primary_metric": { + "name": name, + "direction": direction, + "target": target, + "baseline": baseline, + "candidate": candidate, + "improvement_percent": improvement, + "minimum_improvement_percent": minimum_improvement, + "max_relative_range": max_relative_range, + "target_passed": target_passed, + "improvement_passed": improvement_passed, + "variance_passed": variance_passed, + }, + "quality_gates": quality_gates, + "resource_gates": resource_gates, + } + return result, exit_code + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Pre-check final benchmark samples against campaign gates." + ) + parser.add_argument( + "campaign", + help="Campaign JSON path, or - to read JSON from standard input.", + ) + return parser.parse_args() + + +def main() -> int: + args = parse_args() + try: + raw = sys.stdin.read() if args.campaign == "-" else Path(args.campaign).read_text() + campaign = json.loads(raw) + if not isinstance(campaign, dict): + raise ValueError("campaign root must be an object") + result, exit_code = evaluate(campaign) + except (OSError, json.JSONDecodeError, ValueError) as error: + result = {"verdict": "INVALID", "reasons": [str(error)]} + exit_code = 2 + + print(json.dumps(result, indent=2, sort_keys=True)) + return exit_code + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization.md b/src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization.md new file mode 100644 index 000000000..60e9e2625 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization.md @@ -0,0 +1,624 @@ +--- +name: weight-loading-optimization +description: 'Optimize the serving-level weight load path from storage to device: judge the load path on four dimensions (source, format, placement, duplication), account startup fixed overhead separately from per-request cost with bytes-and-counts lines and hit-criteria warmup validation, verify sharded weight downloads against the safetensors index, apply device-side weight prefetch only on profiled memory-bound hot spots, and order CPU-tier offload candidates by change surface. Includes source-scoped disk-loading modes, pinned staging, synchronous checkpoint save semantics and fastsafetensors broadcast/scatter/coalesced delivery; also audit streamed expert-cache byte correctness and begin/end overlap contracts. Use when startup/loading latency dominates or a streamed expert-cache change needs correctness verification; route DCP asynchronous save performance and distributed recovery validity to their separate skills. + + ' +metadata: + inferrsi: | + { + "tags": [ + "storage", + "weight-loading", + "startup", + "prefetch", + "offload", + "serving", + "npu", + "collectives", + "tensor-parallel", + "Flare", + "model-preparation", + "prepared-runtime-package", + "expert-cache", + "loader-correctness" + ], + "status": "candidate", + "profile": "local-skill-v1", + "schema_version": 1, + "kind": "skill", + "origin": [ + "external" + ], + "sources": [ + { + "type": "git", + "url": "https://github.com/ggml-org/llama.cpp", + "commit": "3e390af18de1131dda27913c00511725b4274c8a", + "paths": [ + "common/arg.cpp", + "common/common.cpp", + "common/fit.cpp", + "src/llama-model.cpp", + "src/llama-model-loader.cpp", + "src/llama-model-loader.h", + "src/llama-mmap.cpp", + "src/llama-mmap.h", + "LICENSE" + ], + "readset": "references/llama-loading-readset.md" + }, + { + "type": "git", + "url": "https://github.com/foundation-model-stack/fastsafetensors", + "commit": "219e2561a41ede2d5d8eba611c248bb0effbf580", + "paths": [ + "fastsafetensors/loader.py", + "fastsafetensors/file_buffer.py", + "fastsafetensors/tensor_factory.py", + "fastsafetensors/parallel_loader.py", + "fastsafetensors/frameworks/_torch.py", + "fastsafetensors/frameworks/_paddle.py", + "docs/overview.md", + "examples/run_parallel.py", + "tests/unit/test_broadcast_runs.py", + "tests/unit/test_subgroup.py", + "LICENSE" + ], + "readset": "references/fastsafetensors-transfer-readset.md" + }, + { + "type": "git", + "url": "https://github.com/NVIDIA/flare-local-inference", + "resolved_url": "https://github.com/NVIDIA/local-inference", + "commit": "bce032c014bae34502ba22d3304fa084d5b40afe", + "paths": [ + "README.md", + "docs/runtime-package-design.md", + "helios/src/runtime_package/format.rs", + "helios/src/runtime_package/model.rs", + "helios/src/execution/manifest.rs", + "helios/src/model/contract.rs", + "helios/src/model/catalog.rs", + "LICENSE" + ], + "readset": "references/flare-preparation-boundary.md", + "license": "Apache-2.0" + }, + { + "type": "git", + "url": "https://github.com/ronak-create/deepseek-v4-in-c", + "commit": "d0402056d0da4bf7edfd2d4977de479a0db9d201", + "paths": [ + "LICENSE", + "README.md", + "Makefile", + "src/cache/dsv4_cache.c", + "src/cache/dsv4_cache.h", + "src/io/dsv4_st.c", + "src/io/dsv4_st.h", + "src/model/dsv4_layer.h", + "src/model/dsv4_layer.c", + "src/cli/dsv4_run.c", + "tests/unit/test_cache.c", + "tests/unit/test_model_oracle.c", + "tools/make_st_fixture.py", + "tools/make_tiny_checkpoint.py", + "tools/dsv4_ref.py" + ], + "readset": "references/deepseek-expert-cache-oracles.md", + "license": "Apache-2.0 (repository declaration and selected-file notices; third-party/model rights excluded)" + } + ], + "empirical_validation": "not_run", + "applicability": { + "scope": "Diagnosing the serving-level weight load path from storage to device and choosing changes to it when startup or loading latency dominates: locating the cost by source, format, placement and duplication, accounting once-per-process loading and warmup apart from per-request cost, verifying sharded downloads, restricting device-side prefetch to profiled memory-bound hot spots and ordering CPU-tier offload; also covers source-scoped disk-loading modes, pinned staging, synchronous checkpoint save semantics, fastsafetensors broadcast/scatter/coalesced delivery and the separation of model preparation from serving. Request-time host overhead belongs to host-overhead-profiling, DCP asynchronous save performance to dcp-async-save-performance and distributed recovery validity to checkpoint-recovery-consistency; for disk-streamed routed experts, audit independent byte identity, resident/pending slot ownership, ordered accumulation and actual oracle callback coverage; the DeepSeek source slice describes POSIX storage, C/OpenMP and pthread ownership; target validation must identify its actual direct/buffered and reader-pool paths", + "prerequisites": "Flag names and API entry paths are re-verified against the pinned source revisions, and torch_npu.npu_prefetch details against the target CANN version, before they are relied on; card state is checked before launch and process placement fixed before measuring, through ascend-device-health and os-process-placement; the Diffusers enable_model_cpu_offload path requires accelerate", + "input_contract": "The current load path's byte source, file format, host-first or direct device placement and duplicated copies across processes or instances; startup timings for loading and warmup with byte and access counts per segment, and the expected warmup hit criteria; the safetensors index weight_map and the downloaded shard set; a profile showing memory-bound hot spots and the adjacent compute or communication segments; free device memory and whether an OOM occurs during construction or inference; for cross-rank delivery, the file-to-loader-group-rank map, tensor names, shapes, dtypes and call order, the required replicated or sliced output, the model's expected shard layout and the collective backend; for streamed expert-cache changes, the selected direct/buffered I/O and reader-pool path, tensor offsets and cache-slot budget, requested keys, source callback table, independent byte/numerical reference and checked fixture coverage", + "produced_artifact": "The located load-path cost on the four dimensions with its matching lever, a startup ledger that keeps fixed overhead apart from per-request cost, a structural shard-completeness result naming the missing shards, a prefetch proposal behind an enable_prefetch switch defaulting to False or a recorded decision not to prefetch, an offload candidate order, the recorded loading mode, a distributed delivery choice with its proposed verification, and a preparation/serving record of serialized and rebuilt state, live resource owners and ABI/prepared-contract versions; proposed changes and verification targets, not a measured startup or delivery gain; a source-bound expert-cache byte/state audit and oracle-path coverage record, with synthetic-fixture, fallback and SKIP limits", + "failure_modes": [ + "Loading and warmup are amortized into per-request latency, or a host segment without timing points is treated as costing nothing", + "Warmup is accepted on total time while mismatched warmup shapes have warmed a different set of cache entries", + "In-flight .incomplete shards are re-downloaded as corrupt, or gap-free shard numbering is accepted without matching the index weight_map", + "Prefetch is forced without a profiled memory-bound hot spot or a non-memory-bound dependency window", + "Resolution or CFG tier-downs are applied to a construction-phase OOM, or offload is adopted when compute already hides the transfer", + "A free-memory probe runs on an mmap-backed load, or a run whose first mlock failure latched with only a warning is treated as fully resident", + "Disk counters that include cache and pipes are read as physical writes, or a run without a page-cache drop is reported as a cold start", + "The ceil-block scatter partition is used without checking it against the model's expected shard layout, or ranks run different orders or plans so their collectives mismatch", + "A faster H2D copy, local clone or rank-local filtered read is counted as a cross-rank communication gain", + "Serial and concurrent cache paths agree on identically corrupted placement bytes, or a contiguous fixture misses a separated-run alignment failure", + "Resident bytes or ordered per-k accumulation change while misses are pending, or an exit-zero SKIP/non-overlapped oracle is counted as overlap validation" + ], + "refusal_point": "Withholds a load-path win until the verification checklist holds and keeps the distributed-delivery checks as verification targets rather than results; does not force prefetch without a safe dependency window and disables it when neither a smaller size nor a moved position removes a regression; records unsupported save behaviors as unknown; rejects mismatched execution ABI or prepared-contract versions instead of editing their tags; and implies no Ascend support from the llama.cpp or fastsafetensors mechanisms; withholds expert-cache correctness/overlap conclusions when byte coverage, actual I/O/pool dispatch or model-oracle callback reachability is missing", + "hardware": "NPU for the device-side prefetch API (torch_npu.npu_prefetch, checked against the target CANN version) and the Diffusers offload playbook; the prefetch and fastsafetensors methodology transfers while the fastsafetensors and llama.cpp APIs do not, and cross-rank completion follows each collective backend's own wait contract" + }, + "recommendations": [ + "Report preparation/startup/readiness, warmups and measured work as separate numbers, with load latency split into init, header, io and get phases, the cold-cache protocol stated and the effective loading mode identical across compared runs.", + "Place each prefetch behind an enable_prefetch switch defaulting to False, start max_size at 50% of the theoretical size, verify a single operator first and step up to 0.7 and then 1.0 only after verified wins.", + "Try offload candidates in order of change surface: batch size, resolution, CFG/feature flags, CPU or layered offload, tensor-parallel degree, then activation checkpointing; re-estimate the un-overlapped transfer share after adopting each tier.", + "Record whole-set atomic publication, asynchronous checkpointing, multi-rank save coordination and crash durability as unknown for the fastsafetensors saver instead of assuming them.", + "Before adopting coalesced delivery, compare it disabled and enabled with identical checkpoint, rank mapping, backend, topology, dtype, cache state, chunk/queue budgets and consumer retention, then measure complete startup under the same accounting protocol.", + "For streamed expert-cache changes, compare against independent buffered tensor bytes, exercise separated-run geometry, check resident bytes during pending reads, preserve ordered per-k accumulation and verify that the numerical oracle selects the actual callbacks." + ], + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Normalized provenance covers the existing llama.cpp loading slice at 3e390af18de1131dda27913c00511725b4274c8a and the fastsafetensors distributed-delivery slice at 219e2561a41ede2d5d8eba611c248bb0effbf580; other inherited claims remain unnormalized with original identities and limits retained.", + "The readsets record static mechanisms and source recommendations, not validated startup, memory, placement or backend performance.", + "The fastsafetensors delivery readset does not revalidate inherited I/O/save claims or qualify uneven scatter, accelerator/NPU compatibility, inter-node transport or agent efficacy.", + "Flare adds source-only preparation/serving ownership and ABI/contract checks; live exporter handles, native backend execution, startup gains and model/dependency rights are not qualified.", + "The DeepSeek increment records source/test definitions only: its buffered byte oracle shares tensor metadata, its resident snapshot covers w1 bytes, and its tiny PyTorch/batched checks do not qualify the released model, backend performance or agent efficacy." + ], + "provenance_readsets": [ + "references/llama-loading-readset.md", + "references/fastsafetensors-transfer-readset.md", + "references/flare-preparation-boundary.md", + "references/deepseek-expert-cache-oracles.md", + "references/deepseek-expert-cache-source.json" + ], + "consumption_mode": "packaged" + } +--- + +# Weight Loading and Startup Fixed-Overhead Optimization + +Status: candidate. Source-grounded from MindIE-SD `host-opt` + +`env-install/weights-prep` + `dit-perf-opt/resource-fallback-tiers` @ 8481d39b +(Apache-2.0), awesome-ascend-skills `model-infer-prefetch` + +`diffusers-ascend` memory-optimization @ 75ec89c (license UNKNOWN), and — +for loading modes and high-throughput mechanics — ggml-org/llama.cpp @ +3e390af (MIT) and foundation-model-stack/fastsafetensors @ 219e256 +(Apache-2.0). + +## SearchSpace mapping + +SSD / Storage row → Diagnose + Optimize + Verify cells (loading-path level). +Communication / Network row → Configure + Optimize + Verify for §9's +cross-rank collectives only; local staging, cloning and H2D remain storage / +memory work. + +Second-level targets: model weight sharding/loading, startup latency, +weight prefetch, CPU-tier offload, loading-mode selection. + +Related skills: `host-overhead-profiling` (request-time host overhead — this +skill covers the once-per-process side), `ascend-device-health` (card state +before launch), `os-process-placement` (process placement before measuring), +`kv-tier-management` (runtime KV offload — a different lifecycle concern), +`storage-io-measurement` (device/process-level I/O attribution and fio +methodology — the measurement layer beneath §7's phase timers), +`performance-ceiling-analysis` (checkpoint anchoring of L1 weight demand — +its gates live there; see §3). + +--- + +## 1. Judge the load path on four dimensions + +Before optimizing, locate the problem along these axes (MindIE-SD host-opt): + +| Dimension | Options | Question | +|---|---|---| +| Source | network disk / local disk / memory cache | Where do the bytes come from? | +| Format | per-tensor reads vs single large file | Read granularity | +| Placement | host-first then to device vs direct device read | Extra hop or not | +| Duplication | multi-process / multi-instance each loading a copy | Redundant reads | + +Optimization levers follow directly: fewer reads, fewer copies, parallelize +what remains, reuse what is already resident. Container/image cold-cache +first-read is a cost line of its own — record it separately. + +## 2. Account startup fixed overhead separately + +The accounting discipline (MindIE-SD host-overhead-account): + +- **Fixed vs per-request split**: loading and warmup happen once per process; + their denominator is startup wall-clock, never amortized into per-request + e2e. Delivery/transfer work is per-request and accounted separately. +- **No timing point, no account**: if the profiler cannot see a host-side + segment, add explicit timing points — an unmeasured segment does not exist + in the ledger. +- **Every line carries**: start/end measurement points + byte count + access + count + evidence. Bytes and counts distinguish "volume problem" (too many + bytes) from "path problem" (too many round trips). +- **Warmup is validated by hit criteria, not total time**: cache-entry count, + graph-hit counters, or expected log lines. Mismatched warmup shapes silently + warm a different set of cache entries while total time looks fine. +- **Seven accounting errors to avoid** (from source): denominator drift; + double counting; timing points inside async branches; comparing absolute + values across windows (same-window A/B only); mixing fixed into per-request; + trusting unmeasured segments; skipping the warmup hit check. +- Benchmark hygiene (InferRSI): report preparation/startup/readiness, warmups, + and measured work as separate numbers. + +## 3. Weight acquisition and verification + +Sharded downloads (modelscope/HF-style) — operational rules: + +- Parallelize with bounded workers (`--max-workers 16` style), select only + needed shards (`--include '{subset}/**'`). +- `.incomplete` marker files mean in-flight shards, not corruption; wait or + resume, do not re-download blindly. +- Verify completeness structurally: shard numbering has no gaps **and** the + set matches `*.safetensors.index.json` `weight_map` keys. On mismatch, + cross-check weight_map and fetch only the missing shards. +- Completeness is not identity: a full shard set, a matching `weight_map` and + a readable header show that the files arrived, not that their tensors match + the model an analysis counts. For the per-tensor checkpoint join and the + per-rank weight ledger, use + [performance-ceiling-analysis](../../measurement/performance-ceiling-analysis/SKILL.md) + ([checkpoint anchoring](../../measurement/performance-ceiling-analysis/references/huggingarch-checkpoint-anchor.md)). + This skill keeps only the loading mechanics. Neither header acquisition nor + a completed load establishes the placement a framework uses at run time. +- Measure aggregate rate by `du -sh` differencing on a stable segment (not + ramp-up); expect single-digit MB/s on slow networks — hours for ~134 GiB is + normal, not a defect. Triage downloader logs as WARNING (transient) vs + ERROR (real failure) to avoid false alarms. +- To test a load path without real bytes, generate structure-identical fake + weights from `model_index.json`/configs (metadata-only download). + +## 4. Device-side weight prefetch + +Decision rules (cannbot `model-infer-prefetch`, `torch_npu.npu_prefetch`; +methodology transfers, the API is NPU-specific): + +- **Only on profiled memory-bound hot spots** — never speculative. +- The **dependency window** (work overlapping the prefetch) must be + non-memory-bound: use the window after a large MatMul completes, or any + compute/communication segment whose output is available. +- `max_size` starts at **50% of the theoretical size**; after verified wins, + step up 0.7 → 1.0 of theoretical. Never start at 1.0. +- Every prefetch sits behind an `enable_prefetch` switch, **default False**. +- Verify a single operator first; then extend position by position. Tuning + order: position ↔ size, iteratively. +- **When to give up**: no safe dependency window → do not force prefetch. + If the window regresses after enabling: shrink size or move position; if + neither works, disable and record. +- Adjacent pattern (TRT-LLM): move periodic background bookkeeping and + weight-movement off the critical stream; the same shape carries to + KV-cache defrag/transfer and weight streaming. + +## 5. CPU-tier offload ordering + +When weights/activations do not fit device memory: + +- **Order candidates by change surface** (smallest first): batch size → + resolution → CFG/feature flags → CPU offload / layered offload → + tensor parallel degree → activation checkpointing. +- **Construction-phase OOM is not an inference-phase OOM**: for construction + OOM use meta-device construction then `to_empty` fill; tier-downs + (resolution, CFG) do not help construction memory. +- **Offload benefit ceiling = the un-overlapped transfer share**: if transfer + is already hidden behind compute, offload buys nothing; re-estimate after + adopting each tier. +- Diffusers-on-NPU playbook by free VRAM (≥ 40 GB / 32–40 / < 32 / < 16): + `enable_model_cpu_offload(device="npu:0")` (do **not** `pipe.to("npu")` + first; requires `accelerate`); gains bounded by PCIe bandwidth; + sequential per-layer offload only as the last resort. +- KV-cache host offload (TRT-LLM pattern): fold side caches into the unified + paged KV manager to inherit host/secondary offload and block reuse; + `host_cache_size` sizing; host-offloaded blocks are indexed by physical + memory-pool index, not logical block ID; null Python views before the C++ + free. +- NPU serving shallow knob: `--swap-space 8` (CPU swap when NPU memory is + full). + +--- + +## 6. Loading modes: mmap / mlock / direct I/O / lazy (llama.cpp pattern) + +For the division between loading, NUMA/thread placement and runtime-state diagnosis, +use the [llama.cpp owner map](../../../systems/engines/llama-cpp/audit-llama-runtime-state/SKILL.md#choose-the-scope). +Source pins and static-inspection dates stay with their respective owners. + +At the pinned revision (3e390af) loading is one unified flag, +`--load-mode {auto|none|mmap|mlock|mmap+mlock|dio}` (default `auto` = mmap +unless the device lacks `mmap_support`). The legacy standalone `--mlock` / +`--no-mmap` flags no longer exist — they are mode values now. Always record +the effective mode; the loader logs it (`load_mode = %s`). + +| Mode | What it does | Trade-off | +|---|---|---| +| `auto` | mmap unless device lacks support | default | +| `none` | full read into RAM | slower load, may reduce pageouts; the only mode with exact load progress (mmap progress is unreliable on some platforms) | +| `mmap` | file-backed pages, on-demand fault | fastest startup, lowest committed RAM; OS may page the model out under pressure | +| `mlock` | force residency, no swap/compress | paging-stall avoidance at committed-RAM cost; gated by RLIMIT_MEMLOCK (`ulimit -l`; Apple `vm.user_wire_limit`; Windows working-set quota) | +| `mmap+mlock` | map then lock | resident + zero-copy start; largest RAM commitment | +| `dio` | direct I/O through a staging buffer | bypasses the page cache; avoids double-caching | + +Mechanics that matter when choosing: + +- **mmap prefetch tuning**: Linux path issues `POSIX_FADV_SEQUENTIAL`, adds + `MAP_POPULATE` only when prefetching and no lazy ranges exist (populate + would fault lazy ranges in), `POSIX_MADV_WILLNEED` for non-lazy ranges and + `POSIX_MADV_RANDOM` for lazy ones. +- **NUMA disables eager populate**: when NUMA handling is active, the mmap + path forces prefetch off and uses `MADV_RANDOM` over the whole mapping — + placement and loading mode interact; do not tune them independently. Docs + recommend dropping the page cache before the first NUMA-enabled run, and + warn that kernel auto NUMA balancing (`/proc/sys/kernel/numa_balancing`) + impairs performance. +- **mlock grows incrementally**: the locked extent tracks the highest loaded + offset (`grow_to(offs + n_size)`), not the whole file up front; lazy + tensors are deliberately excluded (locking would fault them fully in). + First lock failure latches silently — a run can end partially locked with + only a warning; check `ulimit -l` before relying on residency. +- **Lazy mode** (`--lazy-mode on|auto|off`, default auto = tensors > 4 GiB): + read rows of huge tensors (per-layer embeddings) from disk on demand + instead of keeping them resident — requires mmap; trades startup/RAM for + disk re-reads on access. +- **Memory-fit probes force `--load-mode none`**: mmap-backed free-memory + accounting is distorted; any "how much VRAM is free" measurement must + bypass mmap. +- Host/GPU split flags route weights without reloading: `--cpu-moe` / + `--n-cpu-moe` / `--n-cpu-ffn` keep expert/FFN weights in host buffers via + tensor buffer-type overrides; `--moe-cache-mib` adds a GPU staging cache + for CPU-kept experts; KV on device vs host toggles separately. + +## 7. High-throughput loading mechanics (fastsafetensors pattern) + +The complementary design point: **not** using mmap at all on the main path, +because per-tensor mmap faulting cannot saturate NVMe. Instead: parallel +async file→device copy, then lazy zero-copy tensor instantiation (DLPack +capsules over the device buffer with refcounted shared ownership). mmap +survives only as the unified-memory fallback (mmap → `pin_memory` → +`memcpyAsync`: kernel readahead + pinning in one path). + +Bounce-buffer reader (the no-GDS path): + +- Persistent worker pool per loader; each worker alternates **2 pinned host + slots and 2 streams**, so `pread` on one slot overlaps H2D copy on the + other. +- Block size = `ceil(bounce_budget / (threads × 2))`; default budget 16 MiB, + default threads 16. Auto-tune heuristic: threads = physical cores of the + GPU's NUMA node; budget = that node's total L2 cache size. +- Reader workers NUMA-bind to the GPU's node. +- O_DIRECT per filesystem policy: network filesystems and tmpfs/ramfs stay + buffered (keep kernel readahead); O_DIRECT EINVAL retries once then warns. +- Windows serializes `pread` under a file mutex — expect lower reader + parallelism there. + +Direct-to-device (GDS/cuFile, CUDA/ROCm-bound): worker-split `cuFileRead` +into the device buffer; 4 KiB-aligned rounding with coalesced boundary +pages; in-device `memmove` repair for unaligned whole-file loads (blocking); +the GDS bounce cache is charged as fixed overhead from +`cuFileDriverGetProperties`; check `/dev/nvidia-fs0` before driver init +(half-configured hosts close fd 0); per-loader fallback to the bounce path. +CUDA ≥ 12.2 tolerates non-O_DIRECT descriptors. + +Tensor-readiness overlap: publish tensor views while IO is in flight; a +consumer waits only on the completed DMA prefix covering its tensor (fenced +prefix for pread paths, 16 MiB blocks for unified memory). Accessing unread +bytes raises an error rather than returning garbage. Enabled only when the +alignment repair is not needed (it would race the DMA). + +Partial reads and memory planning: + +- Byte-range filtering: read only kept tensors' offsets, coalesced with a + 4 KiB merge gap; expert-parallel ranks filter to owned experts — unowned + MoE bytes are never read. +- Sub-file chunking bounded by `max_batch_bytes`; a chunk must be at least + the largest tensor. +- Static fit planner: `resident + depth × multiplier × budget + overhead ≤ + budget` at every moment; all inputs header-derived → deterministic plans, + identical across ranks (lockstep without collectives); pipeline depth + auto-clamps as residency grows; no runtime feedback — failures re-plan. + +Measurement protocol for any load path (how fastsafetensors benchmarks): + +- Phase timers reported separately: init / header registration / copy (io) / + tensor instantiation (get). Never one elapsed number. +- Cold-cache runs via `posix_fadvise(POSIX_FADV_DONTNEED)` per file (or a + global page-cache drop); `iostat 1` / dool CSV captured alongside. +- Baseline = stock loader (mmap + pageable copy) on identical files; flag to + exclude driver init when measuring loader-only cost. +- Author-reported (not locally validated): bounce path 6.02 GB/s vs mmap + 1.28 GB/s (GPT-2 Medium, MI300X); 26.4 GB/s NVMe→GPU with GDS on 4 GPUs; + vLLM startup 12.39 s → 4.74 s. The pipeline/chunking/overlap features have + no perf harness at that revision — correctness tests only. + +--- + +## 8. Checkpoint save/restore (fastsafetensors saver pattern) + +What the save path actually supports at 219e256 (observed in `saver.py`, +`docs/overview.md` §"Saving checkpoints", and saver tests): + +**Supported:** + +- Synchronous, blocking, sharded safetensors writes (`ParallelSaver.save` / + `save_entries`, or the `save_sharded` / `plan_shards` / `write_shards` + function layer). Default 16 size-balanced shards + (`{base}-00001-of-000NN.safetensors`), largest-first packing. +- Parallel per-tensor fill threads that block on all results before + returning — parallel writes, synchronous completion. Custom `fill` + encoders accept opaque sources and manage their own parallelism. +- Per-file atomic publish: each shard is written to a unique temp file, + then `os.replace`d to its final path. A failed fill removes all temps — + nothing is left at final paths. +- Disk-space preflight (`min_free_bytes`) before any file is created. +- fsync of file + mmap + directory is **opt-in** (`fsync=False` default; + directory fsync skipped on Windows). +- Device tensors saved via host copy (detach → contiguous → flat); dtype + preserved as-is (F4 packed layout supported). No dtype conversion happens + inside the saver — downcast/quantize before entry or inside a custom + fill. +- Reload is the existing loader: returned paths feed `ParallelLoader` / + `fastsafe_open` directly (round-trip tested). +- Every shard header carries `fst.shard.index/count/set` (a per-write id) + so a set can be validated later — but `validate_shard_set` is called by + no production code and is not exported; set integrity is caller logic. + +**Explicitly not supported / unknown — record as unknown, never assume:** + +- Whole-set atomic publish — documented: "the set is not published + atomically". A mid-rename failure can leave a mixed set (some finals + published, temps gone); this path is untested and recovery is a caller + obligation. +- Async checkpointing: no submit/wait split, no futures, no completion + callbacks (unlike the loader's producer/consumer pipeline). +- Distributed / multi-rank save coordination: no rank or process-group + logic exists. +- Crash durability: `fsync=True` flushes file/mmap/directory, but no + crash behavior is documented or tested anywhere in the inspected files. +- GDS / direct-storage writing: not implemented — device tensors go + through host copy. +- Concurrent saves to the same base: last rename wins per path; no + locking (in-process threads only). + +## 9. Choose distributed tensor delivery (fastsafetensors pattern) + +Use this procedure when files have designated loading ranks and the consumer +needs replicated weights or tensor-parallel (TP) slices. TP means ranks hold +different slices of a model tensor. The source-scoped +[transfer contract and readset](references/fastsafetensors-transfer-readset.md) +bind these rules to `219e2561a41ede2d5d8eba611c248bb0effbf580` (Apache-2.0). +They describe implementation and proposed checks, not measured gains. + +1. **Fix ownership and order before choosing a collective.** Give every rank + the same file-to-loader-group-rank map, tensor names, shapes, dtypes and + call order. The file owner reads the selected data into its device buffer; + `FilesBufferOnDevice` then delivers it. Use ranks within the loader's + process group, including for a subgroup whose members differ from world + ranks. A file assignment is not the final model-shard assignment. +2. **Choose by the required output, not by file size.** + + | Required output | Entry and path at this source pin | Cost / condition | + |---|---|---| + | Complete tensor on every rank | `get_tensor(name)` → `get_sharded(name, -1)` → broadcast | Owner clones its tensor; receivers allocate a full tensor. Every rank retains a full copy. | + | A slice along one tensor dimension | `get_sharded(name, dim)` → `shuffle` → scatter | Source forms contiguous slices; each rank allocates its slice. This is not direct reading of only that rank's shard bytes from storage. | + | Whole tensors streamed through the pipeline | `ParallelLoader.iterate_weights()` → eligible coalesced runs, otherwise per-tensor broadcast | This iterator does not choose TP shard dimensions; apply the consumer's slicing contract separately if needed. | + | Independent, rank-specific filtered reads | `ParallelLoader(all_local=True, tensor_filter=...)` | Uses a single-process loader group per rank; no cross-rank loader broadcast. Do not count these reads as network optimization. | + + Scatter uses `block = ceil(shape[dim] / group_size)` and rank `r`'s + interval `[r * block, min((r + 1) * block, shape[dim]))`. Validate that this + partition matches the model's expected shard layout. Uneven or empty + slices need backend-specific qualification; the slicing calculation alone + does not establish that a collective accepts unequal sizes. Start with a + divisible dimension and supported dtype rather than promising arbitrary + TP layouts or packed-dtype behavior. +3. **Consider coalescing for many adjacent replicated tensors.** At this pin + it is enabled only for a multi-rank PyTorch loader, positive + `broadcast_run_bytes` and `broadcast_run_tensors`, and + `resident_tensor is None`. Defaults are 16 MiB and 64 tensors; either + limit set to zero disables it. All ranks must use identical limits and + planning inputs. Runs preserve checkpoint order and split at a different + file/owner, byte gap, byte or count limit, incompatible dtype alignment, + or empty tensor. An individual tensor larger than the byte limit travels + alone; the setting does not split tensors or impose a hard peak-memory cap. +4. **Charge the local work and preserve completion.** The coalesced PyTorch + path waits for every source range in the run, clones the contiguous span + once into owned byte storage, broadcasts it once and rebuilds typed views + sharing that storage. Receivers allocate the run too. This reduces collective + calls where tensors can join; it does not eliminate payload bytes or the + source clone. For CUDA/NCCL, `work.wait()` orders the current CUDA stream; + it is not a CPU-blocking whole-device drain. CPU/Gloo completion follows + that backend's wait contract; do not apply CUDA stream semantics to it. + The iterator drains transient CUDA runs and its final CUDA stream before + releasing the load buffers. Keep that completion path. +5. **Match retention to the consumer.** Default owning outputs survive buffer + close, but a small retained view can keep an entire coalesced run alive. + A `resident_tensor` predicate disables coalescing so selected resident + tensors do not retain unrelated run storage. With + `accumulate_resident=False`, relocate and release each yielded tensor + before requesting the next; do not retain a dictionary of transient views. + Close a partially consumed iterator before closing its loader. Borrowed + tensors require a single-process loader group and completion before + advance/close; they cannot be combined with this distributed path. + +**Counter-signals:** one rank or Paddle does not select this coalesced +PyTorch path; rank-specific filters with a distributed loader are rejected; +different rank orders/plans can mismatch collectives. Gapped or mostly large +tensors may offer few joins, and retaining a run to keep one small tensor can +cost more memory than individual delivery. A faster H2D copy or a local clone +does not prove faster cross-rank communication or inter-node network use. + +**Proposed verification before adoption:** compare coalescing disabled versus +enabled with identical checkpoint, rank mapping, backend, topology, dtype, +cache state, chunk/queue budgets and consumer retention. On every rank compare +key order, shape, dtype and tensor bytes with the reference; for scatter +compare the expected dimension slice, including a non-prefix subgroup. Cover +mixed dtypes/alignment, gaps, an empty tensor, an oversized singleton, +early iterator close and filtered-read rejection. Observe actual collective +count/payload, copy/wait time and peak live storage separately from file I/O; +check completion and buffer release after both exhaustion and early close. +Then measure complete startup under §2/§7's accounting protocol. These are +verification targets, not results from this distillation. + +## Negative findings and remaining gaps + +First-layer scan (8 local repos, 2026-10-15, scoped to inspected +sparse-checkout paths): no mmap/pinned/shard-parallel loading mechanics, no +checkpoint save/restore I/O, no disk-tier offload, no fio-class storage +benchmarking — recorded because the three big repos are skill-doc-only +checkouts; absence there is not absence upstream. + +Wave-5/6 approved sources closed most of this: loading modes and mmap/mlock +placement decisions (llama.cpp), pinned-staging parallel-read mechanics and +a load-path measurement protocol (fastsafetensors), runtime KV-to-disk +tiering (LMCache → `kv-tier-management`), block-device measurement +methodology (fio/sysstat → `storage-io-measurement`), and checkpoint +save/restore semantics (§8 above). The fastsafetensors-specific save-performance +gap remains: its inspected saver supplied no perf harness, benchmarks or +documented tuning levers. Wave 7 adds separate candidates rather than extending +that source's support claims: + +- `dcp-async-save-performance`: DCP-only staging/pause/buffer-lifetime decisions. +- `checkpoint-recovery-consistency`: DLRover and NVIDIA Resiliency Extension + generation/replica/failure-domain contracts, not save-throughput evidence. + +Measurement caveat (mindie-agent): disk read/write counters include cache +and pipes — they are **logical I/O, not physical disk writes**; without +dropping the OS file cache, a run is not a cold-start physical test. + +## Known limitations + +- MindIE-SD host-opt numbers (134 GiB / hours / single-digit MB/s) are + author-observed on their network, not benchmarks. +- The prefetch escalation ladder (50% → 0.7 → 1.0) is source guidance, not + a measured optimum. +- `model-infer-prefetch` API details (`torch_npu.npu_prefetch` signature, + dependency wiring) are NPU-specific; consult the CANN docs of the target + version. +- fastsafetensors mechanisms are CUDA/ROCm/Windows-bound — **no Ascend/NPU + path exists in that repo**; the methodology (bounce buffering, readiness + overlap, static planning, phase-timed measurement) transfers, the APIs do + not. All its numbers are author-reported. +- llama.cpp loading modes are POSIX/Windows, CPU-centric mechanisms; their + trade-offs are qualitatively documented with no numeric benchmarks in the + docs, and NUMA handling is Linux-only. Never imply Ascend support. +- Flag surfaces move between revisions (llama.cpp replaced `--mlock` / + `--no-mmap` with `--load-mode` values); re-verify entry paths against the + pinned revision before relying on any flag name. + +## 10. Separate preparation from serving + +The [Flare preparation boundary](references/flare-preparation-boundary.md) +adds a source-scoped example of Python load/tune/compile/capture, a native +exporter and Rust serving. Record what is serialized, what must be rebuilt, +which live resource owners stay in the preparation process, and the independent +execution ABI/prepared-contract versions. Reject mismatches instead of editing +their tags. Keep preparation/export, package load/readiness and request timing +separate; changing language at the boundary does not by itself establish a gain. +For complete runtime KV/recurrent/convolution/tail state, follow that reference +to the Flare session owner. The addition remains candidate and empirical not_run. + +## 11. Verify streamed expert-cache bytes and overlap + +For aligned reads, cache-slot placement or overlapping routed-expert loads, use +the [DeepSeek expert-cache reference](references/deepseek-expert-cache-oracles.md). +Compare bytes through an independent read path, preserve resident/pending slot +lifetimes and ordered caller accumulation, and confirm that the numerical oracle +reaches the actual callbacks. Keep its synthetic-fixture and SKIP boundaries; +request-time expert reads remain separate from startup loading. These are +source-derived verification targets, not executed model or performance results. + +## Verification checklist (before claiming a load-path win) + +- [ ] Fixed overhead accounted separately from per-request cost +- [ ] Every accounting line has timing points + bytes + counts + evidence +- [ ] Warmup validated by hit criteria (cache entries / graph hits / logs) +- [ ] Before/after compared same-window, same affinity, same device state +- [ ] Loading mode recorded and identical across compared runs (mmap state + changes cache temperature; fit probes bypass mmap) +- [ ] Load latency reported per phase (init / header / io / get), cold-cache + protocol stated (fadvise or page-cache drop) +- [ ] Prefetch changes verified single-op first, switch defaults recorded +- [ ] Offload tier wins re-estimated against un-overlapped transfer share +- [ ] Streamed expert-cache changes checked for independent bytes, resident/pending lifetime and actual oracle-path coverage diff --git a/src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization/references/deepseek-expert-cache-oracles.md b/src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization/references/deepseek-expert-cache-oracles.md new file mode 100644 index 000000000..346c07bea --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization/references/deepseek-expert-cache-oracles.md @@ -0,0 +1,132 @@ +# Audit streamed expert-cache bytes and overlap + +Status: source-derived candidate. Use this reference when changing aligned reads, +cache-slot placement or overlapped routed-expert loading. The +[source record](deepseek-expert-cache-source.json) fixes the repository revision, +inspected regions, file hashes, rights and exclusions. It describes checks to +perform on an authorized target; it supplies no loader implementation or measured +gain. + +Keep startup loading separate from request-time expert traffic. Before judging a +change, identify the checkpoint and tensor metadata, effective direct/buffered +read path, cache-slot budget, requested expert keys, source callback table and +numerical reference. A higher cache hit rate can accompany corrupted expert +bytes and changed routing. + +## Check bytes through an independent read path + +Compare each cached weight and scale with a plain buffered read of the same +tensor bytes. Serial and concurrent cache loads can agree while sharing the same +placement error; matching pointers, shapes or the two fast paths is insufficient. +The source's byte oracle uses the safetensors reader's tensor offsets and buffered +file descriptors, then bypasses its aligned/coalesced placement code. It does not +independently validate the shared metadata parser. + +Exercise the layout that can expose the error. The source fixture separates an +expert's scale and weight runs, gives the runs different 4096-byte alignment +residues and writes nonconstant payload bytes. A single contiguous run cannot +expose a later widened read overwriting an earlier run. An aligned read starts +before its payload; reserving space only for the payload leaves that earlier +storage vulnerable. + +For an aligned-placement check, confirm that the actual run selected direct I/O. +A successful buffered fallback does not exercise the widened-window path. Retain +the compared tensor set and actual checked count; a skipped or absent tensor is +not byte-identity evidence. + +Sources: [fixture geometry and payload](https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/tools/make_st_fixture.py#L130-L202), +[independent byte check](https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/tests/unit/test_cache.c#L137-L186), +[run placement](https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/src/cache/dsv4_cache.c#L260-L389), +[aligned and buffered reads](https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/src/io/dsv4_st.c#L470-L508). + +## Trace resident and pending ownership + +At this source pin, `begin` makes hit/miss, victim and recency decisions serially +in request order before starting the reads. Slots already claimed by this call +cannot be chosen again as victims. It returns usable resident experts immediately; +misses and duplicate requests for an in-flight expert remain unpublished until +`end` completes that read. + +| State | Bytes and visibility | Required boundary | +| --- | --- | --- | +| Returned resident | `out[k]` points to a complete claimed slot. | Keep its bytes usable while pending reads run. | +| Pending miss | The selected slot is marked invalid while a reader fills it; `out[k]` is null. | Publish its key and output only after successful completion in `end`. | +| Missing or invalid tensor metadata | Resolution fails before choosing a victim. | Surface failure; do not interpret it as a completed cache load. | +| Partial I/O failure | The chosen slot can contain partial replacement bytes and stays invalid. | Complete the batch wait and reject the unavailable expert; do not reuse its old key. | + +Only one batch may be active per cache. Call `end` before another `begin` or any +other cache operation. Shutdown stops and joins readers before freeing their slot +storage. When the reader pool is unavailable, the source performs reads inside +`end`; the same callback pair then supplies no overlap with caller computation. +Callback selection alone does not prove the asynchronous path executed. + +The resident check warms a subset, calls `begin` with both hits and misses, +copies resident `w1` bytes during the gap, then compares them after `end` and with +serial loads. This specifically tests those resident `w1` bytes. It does not +establish every tensor's stability under all eviction, capacity or timing cases. +The separate serial/concurrent check compares weight and scale bytes and includes +a duplicate request. + +Sources: [single-batch interface](https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/src/cache/dsv4_cache.h#L220-L270), +[decide, wait and publish](https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/src/cache/dsv4_cache.c#L563-L701), +[reader cleanup](https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/src/cache/dsv4_cache.c#L199-L210), +[concurrent and resident checks](https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/tests/unit/test_cache.c#L188-L298). + +## Follow the model consumer and its accumulation order + +Check the callback table used by both the real caller and its oracle. The layer +selects overlap only when both `begin` and `end` exist; otherwise it uses +`get_many` or serial `get`. A test wired only to `get` cannot cover the overlap +branch. The CLI and current model-oracle test both supply the overlapped pair. + +The caller computes available residents while misses are being read, waits in +`end`, and then computes the remaining experts. Each expert writes to its own +per-`k` output storage, separate from the MoE input. The weighted sum happens +afterwards in `k` order. Completion order must not change that sum: floating-point +addition can produce different results when reordered. Expert matmuls remain +sequential because their working scratch is shared; I/O is what overlaps them. + +The batched caller deduplicates expert requests and fetches the union in bounded +chunks, while retaining a separate output for each `(token, k)` and summing in +`k` order per token. An unavailable expert after the wait aborts the model path; +silently skipping it would change the routed computation. + +Sources: [source interface and scratch](https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/src/model/dsv4_layer.h#L9-L74), +[per-token consumer](https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/src/model/dsv4_layer.c#L369-L483), +[batched consumer](https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/src/model/dsv4_layer.c#L714-L831), +[CLI wiring](https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/src/cli/dsv4_run.c#L313-L315), +[oracle wiring](https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/tests/unit/test_model_oracle.c#L57-L83). + +## Interpret the numerical evidence at its actual scope + +| Check | Source-defined comparison | Interpretation | +| --- | --- | --- | +| Cache byte oracle | Buffered tensor bytes versus cached weights/scales. | Read/placement identity for the checked bytes, with shared tensor metadata. | +| Tiny per-token model | C logits against a repo-owned PyTorch reference, using a vector-scaled tolerance and matching argmax. | Numerical agreement for the synthetic checkpoint and supplied positions; not bit equality to PyTorch. | +| Batched prefill | Bitwise C-logit comparison against the per-token run after its PyTorch check, across several chunk sizes and fresh layer states. | Batched/per-token agreement within that anchored fixture. | + +The tiny checkpoint draws FP8/FP4 weights from exactly representable values and +uses the real config/reader/binder/trunk/cache entry points. Its dimensions and +token sequence are synthetic. The repo-owned PyTorch reimplementation omits +activation-quantization simulation and Hadamard rotation; it is not an execution +of the released model's official GPU reference. Missing tiny checkpoint or trunk +resources print `SKIP` and return exit status 0, so an exit code alone is not a +model-oracle pass. + +Return the selected I/O and callback paths, byte/resident coverage, failure and +cleanup boundaries, numerical comparison and unresolved gaps. Retain the +campaign's independent acceptance and workload controls. These source +definitions and historical reports establish no locally executed C/model check, +full-model quality, device performance or agent efficacy. + +Sources: [fixture/reference producer](https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/tools/make_tiny_checkpoint.py#L17-L50), +[reference exclusions](https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/tools/dsv4_ref.py#L3-L30), +[model comparisons and cleanup](https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/tests/unit/test_model_oracle.c#L145-L390). + +## Attribution + +Original analysis of Ronak Parmar's `ronak-create/deepseek-v4-in-c` at the pinned +revision. The repository declares Apache-2.0 and attributes its streaming design +to Fareed Khan's `kimi-k3-in-c`, also Apache-2.0. Selected-file notices and excluded +third-party/model material remain in the source record. No upstream source code, +prose, checkpoint or fixture payload is redistributed. diff --git a/src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization/references/deepseek-expert-cache-source.json b/src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization/references/deepseek-expert-cache-source.json new file mode 100644 index 000000000..54d074b30 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization/references/deepseek-expert-cache-source.json @@ -0,0 +1,361 @@ +{ + "title": "DeepSeek streamed expert-cache byte and overlap oracle source record", + "repository": { + "url": "https://github.com/ronak-create/deepseek-v4-in-c", + "id": "1340526651", + "commit": "d0402056d0da4bf7edfd2d4977de479a0db9d201", + "git_tree": "cec1a0fdeab62419ca70269f86706d1572768b4c", + "default_license_declaration": "Apache-2.0", + "tree_entries": 91, + "tree_truncated": false, + "verified_blobs": 74 + }, + "inspected_on": "2026-11-03", + "files": [ + { + "path": "LICENSE", + "url": "https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/LICENSE", + "bytes": 11358, + "git_blob_sha1": "d645695673349e3947e8e5ae42332d0ac3164cd7", + "sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", + "read_regions_one_based": [ + [ + 1, + 202 + ] + ], + "read_scope": "Complete root license declaration", + "license_observation": "Complete Apache-2.0 root license text", + "execution_status": "not_run" + }, + { + "path": "README.md", + "url": "https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/README.md", + "bytes": 38462, + "git_blob_sha1": "ceeffc5ffaa5b66c190051d4c11e29d428909cca", + "sha256": "352c90deefd9bfabd5a5bb0ab1513efbcfd5f6607e7b87eca2694bda4db5ec60", + "read_regions_one_based": [ + [ + 1, + 15 + ], + [ + 268, + 318 + ], + [ + 799, + 801 + ] + ], + "read_scope": "Attribution and historical common-corruption/fixture counterexample; author report", + "license_observation": "Repository default Apache-2.0; no separate selected-file license marker; no source bytes redistributed", + "execution_status": "not_run" + }, + { + "path": "Makefile", + "url": "https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/Makefile", + "bytes": 13807, + "git_blob_sha1": "775d8aac970dead45390c491ca4a44645f96e8b5", + "sha256": "2604f1a95c317c2b9347358e92618fdd21a98ede84cd75791ba5cd63d8b0c428", + "read_regions_one_based": [ + [ + 1, + 170 + ] + ], + "read_scope": "Build inputs, stale-binary dependency fix, fixture producers, selected test targets; definitions only", + "license_observation": "Apache-2.0 SPDX marker in file and repository root declaration", + "execution_status": "not_run" + }, + { + "path": "src/cache/dsv4_cache.c", + "url": "https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/src/cache/dsv4_cache.c", + "bytes": 30440, + "git_blob_sha1": "c9397a3b4e5562fddbbf9de1f67e41d47031151f", + "sha256": "416220036f925511be98f9b202dc6cd7523e6b11caf1ded5b09829bc641941e1", + "read_regions_one_based": [ + [ + 1, + 721 + ] + ], + "read_scope": "Complete byte geometry, placement, resolve/read failure distinction, reader pool, begin/end and shutdown implementation", + "license_observation": "Apache-2.0 SPDX marker in file and repository root declaration", + "execution_status": "not_run" + }, + { + "path": "src/cache/dsv4_cache.h", + "url": "https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/src/cache/dsv4_cache.h", + "bytes": 13817, + "git_blob_sha1": "f7bd20e497e483013f08fa0f4b1e671d2ad2fd00", + "sha256": "3b26e722a62855e8d8f9524e145368cff4fd2c6a84c1aeb2f031ec2835940ba4", + "read_regions_one_based": [ + [ + 1, + 275 + ] + ], + "read_scope": "Complete cache data structures and single-batch/lifetime contracts; performance commentary is excluded", + "license_observation": "Apache-2.0 SPDX marker in file and repository root declaration", + "execution_status": "not_run" + }, + { + "path": "src/io/dsv4_st.c", + "url": "https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/src/io/dsv4_st.c", + "bytes": 24526, + "git_blob_sha1": "aa5aca702e80407e38e73d0e978b62f4ca1549d5", + "sha256": "e33d9ef4d30fc56bec29e0e3e1293c119c84cd17bad8b4713f4fdc55c5e4f4eb", + "read_regions_one_based": [ + [ + 455, + 508 + ] + ], + "read_scope": "Lookup and aligned/buffered byte-read consumer only; parser implementation not qualified", + "license_observation": "Repository default Apache-2.0; no separate selected-file license marker; no source bytes redistributed", + "execution_status": "not_run" + }, + { + "path": "src/io/dsv4_st.h", + "url": "https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/src/io/dsv4_st.h", + "bytes": 7249, + "git_blob_sha1": "ddc87a56a1d3d2cae3dd9481b709c52e74bfda5c", + "sha256": "71e67e89f58c12b2293d968119dfefafb800f4798adab44d4beb750facdc0092", + "read_regions_one_based": [ + [ + 1, + 150 + ] + ], + "read_scope": "Complete tensor metadata and aligned-read contract, including port attribution", + "license_observation": "No SPDX marker; header attributes kimi-k3-in-c port as Apache-2.0; repository default Apache-2.0", + "execution_status": "not_run" + }, + { + "path": "src/model/dsv4_layer.h", + "url": "https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/src/model/dsv4_layer.h", + "bytes": 10549, + "git_blob_sha1": "42a7ae2fceefefbdbc78a73f84f85d6cdcc17c8e", + "sha256": "73b35193caec04fe5127aa4d392ea8431b4b90c268accad3ff58c728909ccaaa", + "read_regions_one_based": [ + [ + 1, + 80 + ] + ], + "read_scope": "Scratch aliasing and source callback contract", + "license_observation": "Apache-2.0 SPDX marker in file and repository root declaration", + "execution_status": "not_run" + }, + { + "path": "src/model/dsv4_layer.c", + "url": "https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/src/model/dsv4_layer.c", + "bytes": 41201, + "git_blob_sha1": "c2ad079a852ad45551050f65e88a346105939e68", + "sha256": "8eecb6dbc5db356018a299f9cc103fd7115dbd6c17bf83f978b9f32781cea22b", + "read_regions_one_based": [ + [ + 369, + 487 + ], + [ + 714, + 835 + ] + ], + "read_scope": "Per-token and batched MoE consumers, per-k storage, ordered accumulation and failure behavior", + "license_observation": "Apache-2.0 SPDX marker in file and repository root declaration", + "execution_status": "not_run" + }, + { + "path": "src/cli/dsv4_run.c", + "url": "https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/src/cli/dsv4_run.c", + "bytes": 23806, + "git_blob_sha1": "0b001241e5a87c6c2b57e3abf4d42ba60d982130", + "sha256": "710ad8a4edfadb112b3e3845e8ee6eefd6e1d8638c59774df2d71cbd3164a18f", + "read_regions_one_based": [ + [ + 50, + 80 + ], + [ + 298, + 328 + ] + ], + "read_scope": "Actual cache callbacks, one in-flight handle and source wiring", + "license_observation": "Apache-2.0 SPDX marker in file and repository root declaration", + "execution_status": "not_run" + }, + { + "path": "tests/unit/test_cache.c", + "url": "https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/tests/unit/test_cache.c", + "bytes": 14466, + "git_blob_sha1": "559fd71edaa602da1c5a6e50fff715e573ccce3d", + "sha256": "635d63a60ef9f1170234a2810bb78ea8549b5f993ea91e53b17461ff96019bf5", + "read_regions_one_based": [ + [ + 1, + 305 + ] + ], + "read_scope": "Complete test definition, including independent byte Gate 6, serial/concurrent Gate 7 and w1-only resident snapshot Gate 8", + "license_observation": "Apache-2.0 SPDX marker in file and repository root declaration", + "execution_status": "not_run" + }, + { + "path": "tests/unit/test_model_oracle.c", + "url": "https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/tests/unit/test_model_oracle.c", + "bytes": 17599, + "git_blob_sha1": "8ebbdf5a0817e8d95085a75e03db0806e533a6d3", + "sha256": "fecc5880efb5ff5fb3f62e5273651baf2d0376a4aae73969a2b1167d653f2487", + "read_regions_one_based": [ + [ + 1, + 391 + ] + ], + "read_scope": "Complete test definition; overlap wiring, exit-zero SKIP, tolerant PyTorch/argmax and batched bit-equality boundaries", + "license_observation": "Apache-2.0 SPDX marker in file and repository root declaration", + "execution_status": "not_run" + }, + { + "path": "tools/make_st_fixture.py", + "url": "https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/tools/make_st_fixture.py", + "bytes": 13639, + "git_blob_sha1": "c0b383fb6618ae2fe14f224554fa4a54b844b94c", + "sha256": "bd157bfcf68d8a2a11ebfbb5b872848420a776d2bdcba63d38496cc5850bc889", + "read_regions_one_based": [ + [ + 1, + 249 + ] + ], + "read_scope": "Complete synthetic separated-run fixture definition; multiple experts and nonconstant data", + "license_observation": "Apache-2.0 SPDX marker in file and repository root declaration", + "execution_status": "not_run" + }, + { + "path": "tools/make_tiny_checkpoint.py", + "url": "https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/tools/make_tiny_checkpoint.py", + "bytes": 14454, + "git_blob_sha1": "6a8f3f7fdec9a46f70c59c7e8d82ac9cbf775bce", + "sha256": "2f8d5e238e46de18bc4e409d4c173f1d35ef18602b3589d1312e82d460cdbc7a", + "read_regions_one_based": [ + [ + 1, + 312 + ] + ], + "read_scope": "Complete synthetic checkpoint/expected-logit producer; tiny geometry, exact-representable values and repo-owned reference calls", + "license_observation": "Apache-2.0 SPDX marker in file and repository root declaration", + "execution_status": "not_run" + }, + { + "path": "tools/dsv4_ref.py", + "url": "https://github.com/ronak-create/deepseek-v4-in-c/blob/d0402056d0da4bf7edfd2d4977de479a0db9d201/tools/dsv4_ref.py", + "bytes": 16532, + "git_blob_sha1": "801bfeaf66e323d7c19ed73a7580f9b360b98c1c", + "sha256": "d32cee0a657cc636783661279ce35c4cf205293e352e1e647cec48438c8c18c1", + "read_regions_one_based": [ + [ + 1, + 65 + ] + ], + "read_scope": "Reference provenance and omitted activation quantization/Hadamard scope; full mathematics not qualified", + "license_observation": "Apache-2.0 SPDX marker in file and repository root declaration", + "execution_status": "not_run" + } + ], + "extracted_scope": [ + "Independent buffered tensor-byte comparison versus shared aligned/coalesced placement; separated-run, different-residue and nonconstant-payload fixture geometry", + "Resident and pending expert-slot lifetimes across begin/end, single-batch ownership, metadata versus partial-read failure and join-before-free cleanup", + "Actual I/O and reader-pool dispatch, per-token/batched callback reachability, per-k nonaliasing output storage and ordered accumulation", + "Tiny model reference, tolerance/argmax, batched bit-equality and exit-zero missing-fixture SKIP boundaries" + ], + "evidence_levels": { + "code_observation": "Pinned file bodies/regions, test definitions, callback dispatch predicates, read/publish/cleanup ownership", + "deduction": "A test using get alone cannot select the begin/end overlap branch; equal outputs from shared placement logic do not independently establish correct bytes", + "author_reports": "Historical common-corruption bug, gate repair, actual checkpoint layout and numerical/performance results remain attributed upstream reports", + "executed_cpu_tests": "none", + "device_model_execution": "none", + "agent_effects": "not_evaluated" + }, + "claim_boundaries": [ + "Buffered pread byte oracle shares the safetensors metadata/index; its independence is from aligned/coalesced placement, not from parsing.", + "Gate 6 byte-compares six tensors for fixture experts it obtains; do not describe its skip-on-missing behavior as exhaustive coverage.", + "Gate 8 snapshots resident w1 weights only; no all-tensor/all-eviction/all-timing proof follows.", + "Missing/invalid tensor metadata is rejected before victim selection; a partial I/O failure invalidates the chosen slot and is fatal to the model consumer.", + "Only one batch per cache is contracted. Returned residents and claimed pending slots have different lifetimes; end waits and publishes successful misses, and shutdown joins readers before freeing storage.", + "Expert computation uses shared scratch sequentially; reads overlap it. Per-k outputs do not alias the MoE input and are summed in k order.", + "Model gate wires begin/end, checks tolerant PyTorch logits plus argmax, then checks batched C logits bitwise against its validated per-token C path.", + "Tiny checkpoint/reference omit production-scale quality, full model domain, activation quantization and Hadamard behavior. Missing resources print SKIP and return 0." + ], + "rights": { + "repository_default": "Apache-2.0", + "attribution": "Ronak Parmar / ronak-create/deepseek-v4-in-c; cache/reader design port attributed upstream to Fareed Khan's kimi-k3-in-c (Apache-2.0)", + "redistribution": "Original attributed analysis and immutable links only; no upstream source code, prose, checkpoint/config/fixture payload, reference implementation or third-party header is redistributed", + "third_party": [ + { + "path": "third_party/json.h", + "inspected_regions": [ + [ + 1, + 50 + ] + ], + "observation": "No separate notice in inspected header; parser is a dependency, not extracted source", + "disposition": "exclude; no independent redistribution grant asserted" + }, + { + "path": "third_party/dsv4_unicode.h", + "inspected_regions": [ + [ + 1, + 50 + ] + ], + "observation": "Generated Unicode 15.0.0/Python 3.12.3 category data", + "disposition": "exclude; no data or tokenizer extraction" + }, + { + "material": "DeepSeek checkpoints/config payloads and external inference/model.py or inference/kernel.py", + "disposition": "exclude; external model/source rights and official numerical equivalence not qualified" + } + ], + "notice_inventory": "No NOTICE or additional license file appears in the complete pinned tree inventory", + "scope": "Selected-file observations preserve declared provenance; the root license is not blanket clearance of third-party, checkpoint or external model/reference rights" + }, + "source_script_disposition": [ + { + "path": "tools/make_st_fixture.py", + "disposition": "reference-only", + "reason": "Explains fixture coverage; no script or generated payload copied" + }, + { + "path": "tools/make_tiny_checkpoint.py", + "disposition": "reference-only", + "reason": "Explains the synthetic model-oracle producer; not executed or bundled" + }, + { + "path": "tools/dsv4_ref.py", + "disposition": "reference-only", + "reason": "Identifies the repo-owned PyTorch comparator and its omissions; not copied or qualified as the official model reference" + } + ], + "existing_owner_boundary": "The weight-loading owner retains byte/readiness/lifetime responsibility. Generic benchmark acceptance, caller/oracle authority and baseline-only agreement limits remain existing inference-benchmark-design responsibilities; this increment creates no second owner or benchmark controller.", + "exclusions": [ + "thermal/order drift", + "history/prefetch/useful-miss estimation", + "cache policy simulation", + "reader pool width performance", + "general benchmark controller", + "whole model mathematics or acceptance", + "new schema/runtime/backend/skill" + ], + "status": "candidate", + "empirical_validation": "not_run", + "efficacy": "not_evaluated" +} diff --git a/src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization/references/fastsafetensors-transfer-readset.md b/src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization/references/fastsafetensors-transfer-readset.md new file mode 100644 index 000000000..31e16e4ba --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization/references/fastsafetensors-transfer-readset.md @@ -0,0 +1,61 @@ +# fastsafetensors distributed delivery contract + +Source: [foundation-model-stack/fastsafetensors](https://github.com/foundation-model-stack/fastsafetensors/tree/219e2561a41ede2d5d8eba611c248bb0effbf580), +commit `219e2561a41ede2d5d8eba611c248bb0effbf580`, statically inspected on +2026-10-22. This resolves the owner's historical `219e256` prefix; it does not +replace that pin or revalidate its inherited loading/save claims. + +License: [LICENSE:1-5](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/LICENSE#L1-L5) +identifies Apache License 2.0; the inspected implementation and test Python files also declare +`SPDX-License-Identifier: Apache-2.0`. This source attribution applies to this +slice, not the other sources in the multi-source owner. + +## Caller → ownership/completion → collective + +| Owner §9 clause | Pinned source readset | Source observation and boundary | +|---|---|---| +| Register files and keep collective order | [loader.py:175-201,237-258](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/fastsafetensors/loader.py#L175-L258), [file_buffer.py:14-28](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/fastsafetensors/file_buffer.py#L14-L28), [examples/run_parallel.py:49-60](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/examples/run_parallel.py#L49-L60) | CODE assigns a copier only to the designated rank. DOC/example requires identical method order on all ranks. File ownership and consumer tensor partition are separate decisions. | +| Whole tensor versus TP slice | [file_buffer.py:110-191](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/fastsafetensors/file_buffer.py#L110-L191), [tensor_factory.py:162-237](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/fastsafetensors/tensor_factory.py#L162-L237) | CODE routes dim -1 to broadcast; other dims use ceiling-sized rank slices and contiguous scatter inputs. The source clone/receive allocation is device-memory work; scatter is the collective. Uneven-shape collective acceptance is not established by this calculation. | +| Rank namespace and per-tensor completion | [frameworks/_torch.py:150-205](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/fastsafetensors/frameworks/_torch.py#L150-L205), [frameworks/_paddle.py:125-170](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/fastsafetensors/frameworks/_paddle.py#L125-L170) | CODE uses PyTorch `group_src`; Paddle maps group ranks to world ranks. Per-tensor wrappers synchronize the CUDA device when available. These facts do not qualify either backend on a local host. | +| Pipeline dispatch and incompatible modes | [parallel_loader.py:149-250](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/fastsafetensors/parallel_loader.py#L149-L250), [658-680](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/fastsafetensors/parallel_loader.py#L658-L680), [824-870](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/fastsafetensors/parallel_loader.py#L824-L870), [932-968](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/fastsafetensors/parallel_loader.py#L932-L968) | CODE gates coalescing on multi-rank PyTorch, positive limits and no resident predicate. It rejects per-rank filtering or borrowed tensors in distributed loader groups. `all_local=True` selects independent reads. The iterator delivers whole tensors, not automatic TP slices. | +| Coalescing boundaries and readiness | [file_buffer.py:208-305](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/fastsafetensors/file_buffer.py#L208-L305), [tensor_factory.py:47-98,162-171](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/fastsafetensors/tensor_factory.py#L47-L171) | CODE splits runs at file/owner, gaps, limits, alignment or empty tensors; the first oversized tensor is still a singleton. Source bytes must be ready before cloning. The run iterator preserves its final stream drain on early exit. | +| Byte transport and shared run storage | [frameworks/_torch.py:259-308](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/fastsafetensors/frameworks/_torch.py#L259-L308) | CODE validates adjacency, clones the source byte span, allocates a byte receive buffer, performs one async broadcast and waits on its work, then creates dtype/shape views. The source's stream-ordering comment is specific to NCCL/CUDA, not CPU/Gloo completion. A view can retain the complete run. Reduced call count is a mechanism, not a measured throughput result. | +| Output ownership and early close | [file_buffer.py:14-28,77-95](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/fastsafetensors/file_buffer.py#L14-L95), [tensor_factory.py:308-347](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/fastsafetensors/tensor_factory.py#L308-L347), [parallel_loader.py:731-792](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/fastsafetensors/parallel_loader.py#L731-L792), [docs/overview.md:61-69](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/docs/overview.md#L61-L69) | CODE/DOC distinguishes owning outputs from borrowed local views; close drains I/O and releases the factory's references. Pipeline iterator cleanup precedes loader close. Non-resident consumers must relocate each yield; retaining all views contradicts the budget contract. | + +The relevant concrete call chains are: + +```text +SafeTensorsFileLoader.add_filenames → owner-only copier → copy_files_to_device + → FilesBufferOnDevice.get_tensor/get_sharded → LazyTensorFactory.shuffle + → source clone or contiguous slices + receive allocation → group broadcast/scatter + +ParallelLoader.iterate_weights → _consume_single_batch (coalescing eligibility) + → FilesBufferOnDevice._iter_tensors → wait source ranges → owned byte run + → TorchOp.broadcast_contiguous_run → work.wait → shared typed views + → per-run/final stream drain → file-buffer close → iterator/loader cleanup +``` + +## Source tests inspected, not executed + +- [test_broadcast_runs.py:17-219](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/tests/unit/test_broadcast_runs.py#L17-L219) + supplies author tests for bounded source spans, mixed dtype/alignment, empty + tensors, scalar values, chunking, overlap, residency and early close. It + compares bytes after buffer/iterator close and checks run counts and memory + counters; it does not measure performance. +- [test_subgroup.py:1-132](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/tests/unit/test_subgroup.py#L1-L132) + defines four-rank, non-prefix subgroup broadcast/scatter/send-receive cases. + Its Paddle Gloo subgroup case is skipped for a documented rendezvous issue. + That skip is a source test restriction, not a local failure or validation. + +Inspected supporting intent: [docs/overview.md:1-27](https://github.com/foundation-model-stack/fastsafetensors/blob/219e2561a41ede2d5d8eba611c248bb0effbf580/docs/overview.md#L1-L27). +Selected implementation ranges above establish the delivery mechanism. The +remaining runtime, native extension, device/backend compatibility, uneven +scatter, model integration, transport topology and performance are unverified +here. No source tests, model loads or accelerator runs were executed. Existing +§7 I/O and §8 saver evidence is carried forward rather than re-mined. + +Completion terminology was cross-checked against the +[PyTorch 2.14 distributed operation contract](https://docs.pytorch.org/docs/2.14/distributed.html#synchronous-and-asynchronous-collective-operations): +CPU `wait()` blocks the process until completion, whereas CUDA `wait()` orders +the active stream. This distinction does not qualify this repository against +PyTorch 2.14 or extend its supported version range. diff --git a/src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization/references/flare-preparation-boundary.md b/src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization/references/flare-preparation-boundary.md new file mode 100644 index 000000000..f337ac210 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization/references/flare-preparation-boundary.md @@ -0,0 +1,75 @@ +# Flare preparation and native-serving boundary + +Source-derived candidate; empirical validation **not_run**. This adds one +preparation-contract example to the existing loading owner, not another generic +loading skill. The [pinned source map](../../../../systems/engines/flare-local-inference/audit-flare-session-lifecycle/references/source-notes.md#preparation-readset) +defines the immutable files and symbols. No Flare installation or preparation +was performed. + +## Responsibility and lifetime + +| Owner | During preparation | What reaches serving | +|---|---|---| +| Ignition (Python) | Model recipes, checkpoint acquisition, load/tune/compile/capture; declares allocations/cache, tensor views, semantic contracts, graph handles and resource owners | Export declarations and data supplied to heliopause; its live Python owners stay on the preparation side | +| heliopause (Rust CPython extension) | Preparation allocator, graph introspection, pointer reachability, payload transfers, graph/package serialization and publication; retains resources through native export work | Serialized graphs/storage/contracts and packaged assets, rather than live Python/graph handles | +| Helios (Rust library) | No Python preparation ownership | Loads/validates the package, rebuilds storage and CUDA graphs in a live context, and owns native scheduling/cache execution | +| flare (Rust executable) | Public deployment build/CLI | Links Helios and serves the prepared package; no embedded Python interpreter | + +The dependency direction is `flare → Helios` and `heliopause → Helios`. +The design says graph templates, storage, CUDA contexts and Python resource +owners are retained until native export work drains; failed drain retains them. +`ignition export` writes the package, closes the prepared model and exits; +`flare run` loads the result in a separate process. CUDA graph handles and +Python resource owners do **not** cross that boundary. These exporter lifetime +details are DOC evidence; the exporter implementation itself is outside the +selected readset. + +The saved package describes storage/graphs/contracts so the serving process can +reconstruct them. Recorded addresses and relocation metadata are package data; +they do not make a process-local CUDA handle or Python object portable. The +prepared model also declares disposable KV/scratch state separately from +initialized weights and required metadata. Do not infer that exporting every +live preparation allocation is necessary or that a smaller payload proves +lower peak preparation memory. + +## Verify independent version domains + +| Domain | Pinned rule | Concrete source | +|---|---|---| +| Execution ABI | Version 4; another value is rejected and requests re-export | `execution/manifest.rs::ABI_VERSION`, `ExecutionManifest::validate`, `runtime_package/format.rs::Package::validate` | +| Prepared model contract | Version 2; typed vocabulary/geometry, vision/frontend and graph semantics must validate | `model/contract.rs::PreparedContract::validate` | +| Payload/carrier format | Documentation describes payload format 2 and signed format-6 logical-resource containers; neither number is an execution/prepared-contract version | `docs/runtime-package-design.md`, carrier implementation not qualified here | +| External embedding resources | Every referenced graph embedding-table index must exist in the loaded table catalog | `runtime_package/model.rs` typed-contract decode and table-bound check | + +P: For a load rejection, first record exporter/source pin, package digest, +runtime pin, all three domains and the actual error. If ABI or prepared +contract differs, re-export through the matching preparation path when +authorized. Rewriting a version tag does not convert graph parameters, +storage geometry or semantic bindings. A successful format parse is not +semantic validation, and semantic validation is not model-output validation. + +## Account preparation separately + +P: Keep checkpoint acquisition, compilation/tuning, graph capture/export, +serving package read/reconstruction, readiness warmup and request execution as +separate phases. Compare equivalent package/model/configuration and cold/warm +conditions before attributing a startup change. "No Python in serving" describes +the process boundary; it alone supplies no performance-causation evidence. + +For request-time prefix reuse, continue with the +[Flare session owner](../../../../systems/engines/flare-local-inference/audit-flare-session-lifecycle/SKILL.md). +Its KV chain must accompany recurrent/convolution/partial-tail continuation +state. A prepared package is different from a per-session persisted checkpoint. + +## Applicability and licenses + +The source is a research prototype targeting NVIDIA SM120/SM121 and selected +models/local workloads. No cross-backend, broad multi-card or device execution +qualification follows from these contracts. Its GDS transport remains deferred; +preparation serialization is unrelated to a claim of direct-storage execution. + +The selected repository files are under the root Apache-2.0 +[license retained by the Flare owner](../../../../systems/engines/flare-local-inference/audit-flare-session-lifecycle/LICENSE). +This notice covers source attribution, not a grant over model weights, +tokenizer/assets or separate dependencies. Their own licenses and access +conditions remain separate; none was imported or independently cleared here. diff --git a/src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization/references/llama-loading-readset.md b/src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization/references/llama-loading-readset.md new file mode 100644 index 000000000..965b2bbae --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization/references/llama-loading-readset.md @@ -0,0 +1,26 @@ +# llama.cpp loading provenance + +This readset normalizes only the pre-existing llama.cpp slice in §6 of the owner procedure. Its abbreviated `3e390af` source resolves to [ggml-org/llama.cpp @ 3e390af18de1131dda27913c00511725b4274c8a](https://github.com/ggml-org/llama.cpp/tree/3e390af18de1131dda27913c00511725b4274c8a). Source objects were read statically at that full commit on 2026-10-22; no repository code, model, loading benchmark or native test was run. This is a different revision from the separate `707616` intake and does not borrow that intake's validation. + +License: [LICENSE:1-10](https://github.com/ggml-org/llama.cpp/blob/3e390af18de1131dda27913c00511725b4274c8a/LICENSE#L1-L10) identifies MIT and copyright 2023–2026 The ggml authors. This reference attributes the inspected mechanisms without copying their implementation. It does not assign MIT to the owner's other original sources. + +## Bounded reading map + +CODE denotes implementation at this pin; DOC denotes source help text or comments. Performance proposals and comparisons in the procedure remain unvalidated. + +| Owner clause / symbol | Full-SHA source and inspected lines | Observation and boundary | +|---|---|---| +| Mode parsing: `common_params_parser_init` | [common/arg.cpp:2693-2724](https://github.com/ggml-org/llama.cpp/blob/3e390af18de1131dda27913c00511725b4274c8a/common/arg.cpp#L2693-L2724) | CODE parses unified load modes and lazy modes; DOC describes their intended behavior and lazy auto threshold. This bounded read does not make a tree-wide absence claim about every legacy flag spelling. | +| CLI → model parameters → effective mode | [common/common.cpp:1671-1683](https://github.com/ggml-org/llama.cpp/blob/3e390af18de1131dda27913c00511725b4274c8a/common/common.cpp#L1671-L1683), [llama_model_loader constructor:540-562](https://github.com/ggml-org/llama.cpp/blob/3e390af18de1131dda27913c00511725b4274c8a/src/llama-model-loader.cpp#L540-L562), [llama_model_base::load_tensors:1562-1602](https://github.com/ggml-org/llama.cpp/blob/3e390af18de1131dda27913c00511725b4274c8a/src/llama-model.cpp#L1562-L1602) | CODE passes mode values, derives mmap/direct-I/O flags, disables AUTO mmap when a selected device lacks support and logs the resolved mode. No installed backend was qualified. | +| Mapping contract and NUMA/prefetch consumer | [llama-model-loader.h:241](https://github.com/ggml-org/llama.cpp/blob/3e390af18de1131dda27913c00511725b4274c8a/src/llama-model-loader.h#L241), [llama_model_loader::init_mappings:1411-1441](https://github.com/ggml-org/llama.cpp/blob/3e390af18de1131dda27913c00511725b4274c8a/src/llama-model-loader.cpp#L1411-L1441), [llama-mmap.h:47-54](https://github.com/ggml-org/llama.cpp/blob/3e390af18de1131dda27913c00511725b4274c8a/src/llama-mmap.h#L47-L54), [llama_mmap::impl:482-526](https://github.com/ggml-org/llama.cpp/blob/3e390af18de1131dda27913c00511725b4274c8a/src/llama-mmap.cpp#L482-L526) | CODE passes the CPU backend's NUMA result and lazy ranges into mapping. The inspected POSIX/Linux branch suppresses eager prefetch for NUMA, gates MAP_POPULATE on no lazy ranges, and applies WILLNEED/RANDOM advice to the corresponding ranges. Platform branches differ. | +| Incremental locking | [llama_model_loader tensor allocation:1721-1728](https://github.com/ggml-org/llama.cpp/blob/3e390af18de1131dda27913c00511725b4274c8a/src/llama-model-loader.cpp#L1721-L1728), [llama_mlock::impl::grow_to:803-817](https://github.com/ggml-org/llama.cpp/blob/3e390af18de1131dda27913c00511725b4274c8a/src/llama-mmap.cpp#L803-L817) | CODE excludes lazy tensors from locking, grows the locked extent by loaded offset and latches a failed lock. It does not prove complete residency or available OS quotas on a host. | +| Direct-I/O file path and staging size | [llama_file::impl:183-215](https://github.com/ggml-org/llama.cpp/blob/3e390af18de1131dda27913c00511725b4274c8a/src/llama-mmap.cpp#L183-L215), [loader staging:1569-1579](https://github.com/ggml-org/llama.cpp/blob/3e390af18de1131dda27913c00511725b4274c8a/src/llama-model-loader.cpp#L1569-L1579) | CODE tries Linux O_DIRECT for a requested read path, warns and falls back to buffered I/O when opening it fails, and accounts for read alignment in staging size. Selecting `dio` alone does not prove direct I/O executed. | +| Lazy tensor selection | [llama_model_loader::lazy_read::add:1089-1114](https://github.com/ggml-org/llama.cpp/blob/3e390af18de1131dda27913c00511725b4274c8a/src/llama-model-loader.cpp#L1089-L1114) | CODE uses a greater-than-4-GiB AUTO threshold, rejects unsupported mmap and records file ranges/tensor identities. On-demand access cost and its workload trade-off were not measured. | +| Memory-fit probe | [common_get_device_memory_data_impl:30-38,56-60](https://github.com/ggml-org/llama.cpp/blob/3e390af18de1131dda27913c00511725b4274c8a/common/fit.cpp#L30-L60) | CODE sets the probe copy to no_alloc and LOAD_MODE_NONE before loading. This establishes that specific probe's configuration, not a universal rule for all free-memory measurements. | +| CPU expert/FFN routing flags | [common/arg.cpp:2762-2799](https://github.com/ggml-org/llama.cpp/blob/3e390af18de1131dda27913c00511725b4274c8a/common/arg.cpp#L2762-L2799), [common_model_params_to_llama:1695-1699](https://github.com/ggml-org/llama.cpp/blob/3e390af18de1131dda27913c00511725b4274c8a/common/common.cpp#L1695-L1699) | CODE configures tensor-buffer overrides and the MoE cache-size parameter. Full device-buffer placement, reload/transfer behavior and cache efficacy were outside this bounded read. | + +Concrete loading chain: `common_params_parser_init` → `common_model_params_to_llama` → loader mode flags / `llama_model_base::load_tensors` AUTO resolution → `llama_model_loader::init_mappings` → platform-specific `llama_mmap::impl` → mapped tensor allocation / optional `llama_mlock::grow_to`. + +## Limits retained + +Only this llama.cpp source identity is normalized. MindIE-SD, awesome-ascend-skills, fastsafetensors and other inherited source material remain outside this normalization; their original identities, unknowns and procedures are unchanged. The map is not a general revalidation of §1–§7 or a claim that every comparative phrase in §6 is established by source code. No startup, page-fault, RAM, throughput, OS-quota or cross-platform result was reproduced. The candidate and empirical-validation states remain unchanged. diff --git a/src/inferrsi/knowledge/atoms/video-diffusion-optimization.campaign-template.json b/src/inferrsi/knowledge/atoms/video-diffusion-optimization.campaign-template.json new file mode 100644 index 000000000..d136f93b4 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/video-diffusion-optimization.campaign-template.json @@ -0,0 +1,65 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "first-party" + ], + "applicability": { + "scope": "Backend-agnostic video diffusion inference and serving optimization", + "hardware": "Any accelerator (Ascend NPU, CUDA GPU, and others); operator names, memory layouts, and profiler references are re-derived per backend", + "prerequisites": "A reproducible benchmark, a frozen quality check, and numeric gates defined in the governing acceptance issue" + }, + "state": "candidate", + "limitations": [ + "Backend-agnostic skeleton only. The first-hand field notes are Ascend-specific and live in the ascend-video-diffusion-optimization skill; every operator, layout and profiler reference (TransData, FRACTAL_NZ, CANN) must be re-derived per backend.", + "Candidate workflow guidance; not independently validated.", + "Model identifiers, campaign revisions, and numeric gates are intentionally excluded and remain issue-scoped.", + "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": [], + "empirical_validation": "not_run", + "title": "Video diffusion campaign template", + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/optimization/video-diffusion-optimization/assets/campaign.template.json", + "sha256": "1a37f1d136612143ddab8f0cbbf424c80433b4da5312edb18d07c0b9d87ef657" + }, + { + "type": "unknown", + "note": "Legacy provenance remains in procedure/readsets" + } + ], + "id": "video-diffusion-optimization.campaign-template", + "kind": "knowledge", + "entrypoint": "campaign.template.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/optimization/video-diffusion-optimization/assets/campaign.template.json", + "byte_range": [ + 0, + 1089 + ], + "sha256": "1a37f1d136612143ddab8f0cbbf424c80433b4da5312edb18d07c0b9d87ef657" + } + } + }, + "content": { + "campaign.template.json": { + "path": "playbooks/video-diffusion-optimization/assets/campaign.template.json" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/video-diffusion-optimization.evaluate-target.json b/src/inferrsi/knowledge/atoms/video-diffusion-optimization.evaluate-target.json new file mode 100644 index 000000000..ae1c97249 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/video-diffusion-optimization.evaluate-target.json @@ -0,0 +1,65 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "first-party" + ], + "applicability": { + "scope": "Backend-agnostic video diffusion inference and serving optimization", + "hardware": "Any accelerator (Ascend NPU, CUDA GPU, and others); operator names, memory layouts, and profiler references are re-derived per backend", + "prerequisites": "A reproducible benchmark, a frozen quality check, and numeric gates defined in the governing acceptance issue" + }, + "state": "candidate", + "limitations": [ + "Backend-agnostic skeleton only. The first-hand field notes are Ascend-specific and live in the ascend-video-diffusion-optimization skill; every operator, layout and profiler reference (TransData, FRACTAL_NZ, CANN) must be re-derived per backend.", + "Candidate workflow guidance; not independently validated.", + "Model identifiers, campaign revisions, and numeric gates are intentionally excluded and remain issue-scoped.", + "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": [], + "empirical_validation": "not_run", + "title": "Pre-check a campaign's final samples against frozen target and safety gates", + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/optimization/video-diffusion-optimization/scripts/evaluate_target.py", + "sha256": "9e84df051e03d567746fd73ae7243efb2f3c5ec806fef824d3c4d42a8eb9704c" + }, + { + "type": "unknown", + "note": "Legacy provenance remains in procedure/readsets" + } + ], + "id": "video-diffusion-optimization.evaluate-target", + "kind": "knowledge", + "entrypoint": "evaluate_target.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/optimization/video-diffusion-optimization/scripts/evaluate_target.py", + "byte_range": [ + 0, + 8368 + ], + "sha256": "9e84df051e03d567746fd73ae7243efb2f3c5ec806fef824d3c4d42a8eb9704c" + } + } + }, + "content": { + "evaluate_target.py": { + "path": "playbooks/video-diffusion-optimization/scripts/evaluate_target.py" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/video-diffusion-optimization.original.json b/src/inferrsi/knowledge/atoms/video-diffusion-optimization.original.json new file mode 100644 index 000000000..845df79a3 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/video-diffusion-optimization.original.json @@ -0,0 +1,94 @@ +{ + "authority": "checkout", + "metadata": { + "id": "video-diffusion-optimization.original", + "kind": "knowledge", + "entrypoint": "guide.md", + "title": "Run and verify goal-driven video diffusion optimization, backend-agnostic. Use when the user asks for latency, RTF, throughput, or memory targets across VLM, DiT, MoE, attention, or VAE, on any accelerator. Not for text-only LLMs.", + "origin": [ + "first-party" + ], + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/optimization/video-diffusion-optimization/SKILL.md", + "sha256": "6466f46b63f6149e9692fdc344fca5f3af9e1961b59fd48f25b778256089c203" + }, + { + "type": "unknown", + "note": "Legacy provenance remains in procedure/readsets" + } + ], + "applicability": { + "scope": "Backend-agnostic video diffusion inference and serving optimization", + "hardware": "Any accelerator (Ascend NPU, CUDA GPU, and others); operator names, memory layouts, and profiler references are re-derived per backend", + "prerequisites": "A reproducible benchmark, a frozen quality check, and numeric gates defined in the governing acceptance issue" + }, + "state": "candidate", + "limitations": [ + "Backend-agnostic skeleton only. The first-hand field notes are Ascend-specific and live in the ascend-video-diffusion-optimization skill; every operator, layout and profiler reference (TransData, FRACTAL_NZ, CANN) must be re-derived per backend.", + "Candidate workflow guidance; not independently validated.", + "Model identifiers, campaign revisions, and numeric gates are intentionally excluded and remain issue-scoped.", + "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": [], + "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/optimization/video-diffusion-optimization/SKILL.md", + "byte_range": [ + 0, + 14020 + ], + "sha256": "6466f46b63f6149e9692fdc344fca5f3af9e1961b59fd48f25b778256089c203" + } + } + }, + "content": { + "guide.md": { + "path": "playbooks/video-diffusion-optimization.md" + } + }, + "parts": { + "navigation": { + "skill_section": "navigation", + "layer": "L0", + "byte_range": [ + 0, + 285 + ], + "sha256": "dbaa4ad4e692610355e9a1ed1d902c9d90a2c13f47be71396ab6d6455affef41" + }, + "decision": { + "skill_section": "decision", + "layer": "L1", + "byte_range": [ + 0, + 2046 + ], + "sha256": "be85e9abbc07033623effb9e552237e6bc5b0fe0fd6bedb0066a363d82c9861d" + }, + "procedure": { + "skill_section": "procedure", + "layer": "L2", + "byte_range": [ + 2046, + 14020 + ], + "sha256": "ec74181470a187890685936f24a14837d261cd50832bce08cc21f9311bfbae45" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/weight-loading-optimization.deepseek-expert-cache-oracles.json b/src/inferrsi/knowledge/atoms/weight-loading-optimization.deepseek-expert-cache-oracles.json new file mode 100644 index 000000000..83ca70544 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/weight-loading-optimization.deepseek-expert-cache-oracles.json @@ -0,0 +1,130 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Diagnosing the serving-level weight load path from storage to device and choosing changes to it when startup or loading latency dominates: locating the cost by source, format, placement and duplication, accounting once-per-process loading and warmup apart from per-request cost, verifying sharded downloads, restricting device-side prefetch to profiled memory-bound hot spots and ordering CPU-tier offload; also covers source-scoped disk-loading modes, pinned staging, synchronous checkpoint save semantics, fastsafetensors broadcast/scatter/coalesced delivery and the separation of model preparation from serving. Request-time host overhead belongs to host-overhead-profiling, DCP asynchronous save performance to dcp-async-save-performance and distributed recovery validity to checkpoint-recovery-consistency; for disk-streamed routed experts, audit independent byte identity, resident/pending slot ownership, ordered accumulation and actual oracle callback coverage; the DeepSeek source slice describes POSIX storage, C/OpenMP and pthread ownership; target validation must identify its actual direct/buffered and reader-pool paths", + "prerequisites": "Flag names and API entry paths are re-verified against the pinned source revisions, and torch_npu.npu_prefetch details against the target CANN version, before they are relied on; card state is checked before launch and process placement fixed before measuring, through ascend-device-health and os-process-placement; the Diffusers enable_model_cpu_offload path requires accelerate", + "input_contract": "The current load path's byte source, file format, host-first or direct device placement and duplicated copies across processes or instances; startup timings for loading and warmup with byte and access counts per segment, and the expected warmup hit criteria; the safetensors index weight_map and the downloaded shard set; a profile showing memory-bound hot spots and the adjacent compute or communication segments; free device memory and whether an OOM occurs during construction or inference; for cross-rank delivery, the file-to-loader-group-rank map, tensor names, shapes, dtypes and call order, the required replicated or sliced output, the model's expected shard layout and the collective backend; for streamed expert-cache changes, the selected direct/buffered I/O and reader-pool path, tensor offsets and cache-slot budget, requested keys, source callback table, independent byte/numerical reference and checked fixture coverage", + "produced_artifact": "The located load-path cost on the four dimensions with its matching lever, a startup ledger that keeps fixed overhead apart from per-request cost, a structural shard-completeness result naming the missing shards, a prefetch proposal behind an enable_prefetch switch defaulting to False or a recorded decision not to prefetch, an offload candidate order, the recorded loading mode, a distributed delivery choice with its proposed verification, and a preparation/serving record of serialized and rebuilt state, live resource owners and ABI/prepared-contract versions; proposed changes and verification targets, not a measured startup or delivery gain; a source-bound expert-cache byte/state audit and oracle-path coverage record, with synthetic-fixture, fallback and SKIP limits", + "failure_modes": [ + "Loading and warmup are amortized into per-request latency, or a host segment without timing points is treated as costing nothing", + "Warmup is accepted on total time while mismatched warmup shapes have warmed a different set of cache entries", + "In-flight .incomplete shards are re-downloaded as corrupt, or gap-free shard numbering is accepted without matching the index weight_map", + "Prefetch is forced without a profiled memory-bound hot spot or a non-memory-bound dependency window", + "Resolution or CFG tier-downs are applied to a construction-phase OOM, or offload is adopted when compute already hides the transfer", + "A free-memory probe runs on an mmap-backed load, or a run whose first mlock failure latched with only a warning is treated as fully resident", + "Disk counters that include cache and pipes are read as physical writes, or a run without a page-cache drop is reported as a cold start", + "The ceil-block scatter partition is used without checking it against the model's expected shard layout, or ranks run different orders or plans so their collectives mismatch", + "A faster H2D copy, local clone or rank-local filtered read is counted as a cross-rank communication gain", + "Serial and concurrent cache paths agree on identically corrupted placement bytes, or a contiguous fixture misses a separated-run alignment failure", + "Resident bytes or ordered per-k accumulation change while misses are pending, or an exit-zero SKIP/non-overlapped oracle is counted as overlap validation" + ], + "refusal_point": "Withholds a load-path win until the verification checklist holds and keeps the distributed-delivery checks as verification targets rather than results; does not force prefetch without a safe dependency window and disables it when neither a smaller size nor a moved position removes a regression; records unsupported save behaviors as unknown; rejects mismatched execution ABI or prepared-contract versions instead of editing their tags; and implies no Ascend support from the llama.cpp or fastsafetensors mechanisms; withholds expert-cache correctness/overlap conclusions when byte coverage, actual I/O/pool dispatch or model-oracle callback reachability is missing", + "hardware": "NPU for the device-side prefetch API (torch_npu.npu_prefetch, checked against the target CANN version) and the Diffusers offload playbook; the prefetch and fastsafetensors methodology transfers while the fastsafetensors and llama.cpp APIs do not, and cross-rank completion follows each collective backend's own wait contract" + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Normalized provenance covers the existing llama.cpp loading slice at 3e390af18de1131dda27913c00511725b4274c8a and the fastsafetensors distributed-delivery slice at 219e2561a41ede2d5d8eba611c248bb0effbf580; other inherited claims remain unnormalized with original identities and limits retained.", + "The readsets record static mechanisms and source recommendations, not validated startup, memory, placement or backend performance.", + "The fastsafetensors delivery readset does not revalidate inherited I/O/save claims or qualify uneven scatter, accelerator/NPU compatibility, inter-node transport or agent efficacy.", + "Flare adds source-only preparation/serving ownership and ABI/contract checks; live exporter handles, native backend execution, startup gains and model/dependency rights are not qualified.", + "The DeepSeek increment records source/test definitions only: its buffered byte oracle shares tensor metadata, its resident snapshot covers w1 bytes, and its tiny PyTorch/batched checks do not qualify the released model, backend performance or agent efficacy.", + "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/ronak-create/deepseek-v4-in-c", + "commit": "d0402056d0da4bf7edfd2d4977de479a0db9d201", + "paths": [ + "LICENSE", + "README.md", + "Makefile", + "src/cache/dsv4_cache.c", + "src/cache/dsv4_cache.h", + "src/io/dsv4_st.c", + "src/io/dsv4_st.h", + "src/model/dsv4_layer.h", + "src/model/dsv4_layer.c", + "src/cli/dsv4_run.c", + "tests/unit/test_cache.c", + "tests/unit/test_model_oracle.c", + "tools/make_st_fixture.py", + "tools/make_tiny_checkpoint.py", + "tools/dsv4_ref.py" + ], + "readset": "references/deepseek-expert-cache-oracles.md", + "license": "Apache-2.0 (repository declaration and selected-file notices; third-party/model rights excluded)" + } + ], + "empirical_validation": "not_run", + "title": "Audit streamed expert-cache bytes and overlap", + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/optimization/weight-loading-optimization/references/deepseek-expert-cache-oracles.md", + "sha256": "5e42c4a01f9ac810663979dee0658c4cbe87060594c16622ae6ec0b854e44b29" + }, + { + "type": "git", + "url": "https://github.com/ronak-create/deepseek-v4-in-c", + "commit": "d0402056d0da4bf7edfd2d4977de479a0db9d201", + "paths": [ + "LICENSE", + "README.md", + "Makefile", + "src/cache/dsv4_cache.c", + "src/cache/dsv4_cache.h", + "src/io/dsv4_st.c", + "src/io/dsv4_st.h", + "src/model/dsv4_layer.h", + "src/model/dsv4_layer.c", + "src/cli/dsv4_run.c", + "tests/unit/test_cache.c", + "tests/unit/test_model_oracle.c", + "tools/make_st_fixture.py", + "tools/make_tiny_checkpoint.py", + "tools/dsv4_ref.py" + ], + "readset": "references/deepseek-expert-cache-oracles.md", + "license": "Apache-2.0 (repository declaration and selected-file notices; third-party/model rights excluded)", + "revision_precision": "full" + } + ], + "id": "weight-loading-optimization.deepseek-expert-cache-oracles", + "kind": "knowledge", + "entrypoint": "deepseek-expert-cache-oracles.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/optimization/weight-loading-optimization/references/deepseek-expert-cache-oracles.md", + "byte_range": [ + 0, + 9522 + ], + "sha256": "5e42c4a01f9ac810663979dee0658c4cbe87060594c16622ae6ec0b854e44b29" + } + } + }, + "content": { + "deepseek-expert-cache-oracles.md": { + "path": "playbooks/weight-loading-optimization/references/deepseek-expert-cache-oracles.md" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/weight-loading-optimization.deepseek-expert-cache-source.json b/src/inferrsi/knowledge/atoms/weight-loading-optimization.deepseek-expert-cache-source.json new file mode 100644 index 000000000..0fd9d1cf1 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/weight-loading-optimization.deepseek-expert-cache-source.json @@ -0,0 +1,130 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Diagnosing the serving-level weight load path from storage to device and choosing changes to it when startup or loading latency dominates: locating the cost by source, format, placement and duplication, accounting once-per-process loading and warmup apart from per-request cost, verifying sharded downloads, restricting device-side prefetch to profiled memory-bound hot spots and ordering CPU-tier offload; also covers source-scoped disk-loading modes, pinned staging, synchronous checkpoint save semantics, fastsafetensors broadcast/scatter/coalesced delivery and the separation of model preparation from serving. Request-time host overhead belongs to host-overhead-profiling, DCP asynchronous save performance to dcp-async-save-performance and distributed recovery validity to checkpoint-recovery-consistency; for disk-streamed routed experts, audit independent byte identity, resident/pending slot ownership, ordered accumulation and actual oracle callback coverage; the DeepSeek source slice describes POSIX storage, C/OpenMP and pthread ownership; target validation must identify its actual direct/buffered and reader-pool paths", + "prerequisites": "Flag names and API entry paths are re-verified against the pinned source revisions, and torch_npu.npu_prefetch details against the target CANN version, before they are relied on; card state is checked before launch and process placement fixed before measuring, through ascend-device-health and os-process-placement; the Diffusers enable_model_cpu_offload path requires accelerate", + "input_contract": "The current load path's byte source, file format, host-first or direct device placement and duplicated copies across processes or instances; startup timings for loading and warmup with byte and access counts per segment, and the expected warmup hit criteria; the safetensors index weight_map and the downloaded shard set; a profile showing memory-bound hot spots and the adjacent compute or communication segments; free device memory and whether an OOM occurs during construction or inference; for cross-rank delivery, the file-to-loader-group-rank map, tensor names, shapes, dtypes and call order, the required replicated or sliced output, the model's expected shard layout and the collective backend; for streamed expert-cache changes, the selected direct/buffered I/O and reader-pool path, tensor offsets and cache-slot budget, requested keys, source callback table, independent byte/numerical reference and checked fixture coverage", + "produced_artifact": "The located load-path cost on the four dimensions with its matching lever, a startup ledger that keeps fixed overhead apart from per-request cost, a structural shard-completeness result naming the missing shards, a prefetch proposal behind an enable_prefetch switch defaulting to False or a recorded decision not to prefetch, an offload candidate order, the recorded loading mode, a distributed delivery choice with its proposed verification, and a preparation/serving record of serialized and rebuilt state, live resource owners and ABI/prepared-contract versions; proposed changes and verification targets, not a measured startup or delivery gain; a source-bound expert-cache byte/state audit and oracle-path coverage record, with synthetic-fixture, fallback and SKIP limits", + "failure_modes": [ + "Loading and warmup are amortized into per-request latency, or a host segment without timing points is treated as costing nothing", + "Warmup is accepted on total time while mismatched warmup shapes have warmed a different set of cache entries", + "In-flight .incomplete shards are re-downloaded as corrupt, or gap-free shard numbering is accepted without matching the index weight_map", + "Prefetch is forced without a profiled memory-bound hot spot or a non-memory-bound dependency window", + "Resolution or CFG tier-downs are applied to a construction-phase OOM, or offload is adopted when compute already hides the transfer", + "A free-memory probe runs on an mmap-backed load, or a run whose first mlock failure latched with only a warning is treated as fully resident", + "Disk counters that include cache and pipes are read as physical writes, or a run without a page-cache drop is reported as a cold start", + "The ceil-block scatter partition is used without checking it against the model's expected shard layout, or ranks run different orders or plans so their collectives mismatch", + "A faster H2D copy, local clone or rank-local filtered read is counted as a cross-rank communication gain", + "Serial and concurrent cache paths agree on identically corrupted placement bytes, or a contiguous fixture misses a separated-run alignment failure", + "Resident bytes or ordered per-k accumulation change while misses are pending, or an exit-zero SKIP/non-overlapped oracle is counted as overlap validation" + ], + "refusal_point": "Withholds a load-path win until the verification checklist holds and keeps the distributed-delivery checks as verification targets rather than results; does not force prefetch without a safe dependency window and disables it when neither a smaller size nor a moved position removes a regression; records unsupported save behaviors as unknown; rejects mismatched execution ABI or prepared-contract versions instead of editing their tags; and implies no Ascend support from the llama.cpp or fastsafetensors mechanisms; withholds expert-cache correctness/overlap conclusions when byte coverage, actual I/O/pool dispatch or model-oracle callback reachability is missing", + "hardware": "NPU for the device-side prefetch API (torch_npu.npu_prefetch, checked against the target CANN version) and the Diffusers offload playbook; the prefetch and fastsafetensors methodology transfers while the fastsafetensors and llama.cpp APIs do not, and cross-rank completion follows each collective backend's own wait contract" + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Normalized provenance covers the existing llama.cpp loading slice at 3e390af18de1131dda27913c00511725b4274c8a and the fastsafetensors distributed-delivery slice at 219e2561a41ede2d5d8eba611c248bb0effbf580; other inherited claims remain unnormalized with original identities and limits retained.", + "The readsets record static mechanisms and source recommendations, not validated startup, memory, placement or backend performance.", + "The fastsafetensors delivery readset does not revalidate inherited I/O/save claims or qualify uneven scatter, accelerator/NPU compatibility, inter-node transport or agent efficacy.", + "Flare adds source-only preparation/serving ownership and ABI/contract checks; live exporter handles, native backend execution, startup gains and model/dependency rights are not qualified.", + "The DeepSeek increment records source/test definitions only: its buffered byte oracle shares tensor metadata, its resident snapshot covers w1 bytes, and its tiny PyTorch/batched checks do not qualify the released model, backend performance or agent efficacy.", + "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/ronak-create/deepseek-v4-in-c", + "commit": "d0402056d0da4bf7edfd2d4977de479a0db9d201", + "paths": [ + "LICENSE", + "README.md", + "Makefile", + "src/cache/dsv4_cache.c", + "src/cache/dsv4_cache.h", + "src/io/dsv4_st.c", + "src/io/dsv4_st.h", + "src/model/dsv4_layer.h", + "src/model/dsv4_layer.c", + "src/cli/dsv4_run.c", + "tests/unit/test_cache.c", + "tests/unit/test_model_oracle.c", + "tools/make_st_fixture.py", + "tools/make_tiny_checkpoint.py", + "tools/dsv4_ref.py" + ], + "readset": "references/deepseek-expert-cache-oracles.md", + "license": "Apache-2.0 (repository declaration and selected-file notices; third-party/model rights excluded)" + } + ], + "empirical_validation": "not_run", + "title": "DeepSeek streamed expert-cache byte and overlap oracle source record", + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/optimization/weight-loading-optimization/references/deepseek-expert-cache-source.json", + "sha256": "65bf0623616b4f633d8f51b30134798cbf71176716c8a8613209e2fc48ff84bd" + }, + { + "type": "git", + "url": "https://github.com/ronak-create/deepseek-v4-in-c", + "commit": "d0402056d0da4bf7edfd2d4977de479a0db9d201", + "paths": [ + "LICENSE", + "README.md", + "Makefile", + "src/cache/dsv4_cache.c", + "src/cache/dsv4_cache.h", + "src/io/dsv4_st.c", + "src/io/dsv4_st.h", + "src/model/dsv4_layer.h", + "src/model/dsv4_layer.c", + "src/cli/dsv4_run.c", + "tests/unit/test_cache.c", + "tests/unit/test_model_oracle.c", + "tools/make_st_fixture.py", + "tools/make_tiny_checkpoint.py", + "tools/dsv4_ref.py" + ], + "readset": "references/deepseek-expert-cache-oracles.md", + "license": "Apache-2.0 (repository declaration and selected-file notices; third-party/model rights excluded)", + "revision_precision": "full" + } + ], + "id": "weight-loading-optimization.deepseek-expert-cache-source", + "kind": "knowledge", + "entrypoint": "deepseek-expert-cache-source.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/optimization/weight-loading-optimization/references/deepseek-expert-cache-source.json", + "byte_range": [ + 0, + 16564 + ], + "sha256": "65bf0623616b4f633d8f51b30134798cbf71176716c8a8613209e2fc48ff84bd" + } + } + }, + "content": { + "deepseek-expert-cache-source.json": { + "path": "playbooks/weight-loading-optimization/references/deepseek-expert-cache-source.json" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/weight-loading-optimization.fastsafetensors-transfer-readset.json b/src/inferrsi/knowledge/atoms/weight-loading-optimization.fastsafetensors-transfer-readset.json new file mode 100644 index 000000000..c5f73d30f --- /dev/null +++ b/src/inferrsi/knowledge/atoms/weight-loading-optimization.fastsafetensors-transfer-readset.json @@ -0,0 +1,120 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Diagnosing the serving-level weight load path from storage to device and choosing changes to it when startup or loading latency dominates: locating the cost by source, format, placement and duplication, accounting once-per-process loading and warmup apart from per-request cost, verifying sharded downloads, restricting device-side prefetch to profiled memory-bound hot spots and ordering CPU-tier offload; also covers source-scoped disk-loading modes, pinned staging, synchronous checkpoint save semantics, fastsafetensors broadcast/scatter/coalesced delivery and the separation of model preparation from serving. Request-time host overhead belongs to host-overhead-profiling, DCP asynchronous save performance to dcp-async-save-performance and distributed recovery validity to checkpoint-recovery-consistency; for disk-streamed routed experts, audit independent byte identity, resident/pending slot ownership, ordered accumulation and actual oracle callback coverage; the DeepSeek source slice describes POSIX storage, C/OpenMP and pthread ownership; target validation must identify its actual direct/buffered and reader-pool paths", + "prerequisites": "Flag names and API entry paths are re-verified against the pinned source revisions, and torch_npu.npu_prefetch details against the target CANN version, before they are relied on; card state is checked before launch and process placement fixed before measuring, through ascend-device-health and os-process-placement; the Diffusers enable_model_cpu_offload path requires accelerate", + "input_contract": "The current load path's byte source, file format, host-first or direct device placement and duplicated copies across processes or instances; startup timings for loading and warmup with byte and access counts per segment, and the expected warmup hit criteria; the safetensors index weight_map and the downloaded shard set; a profile showing memory-bound hot spots and the adjacent compute or communication segments; free device memory and whether an OOM occurs during construction or inference; for cross-rank delivery, the file-to-loader-group-rank map, tensor names, shapes, dtypes and call order, the required replicated or sliced output, the model's expected shard layout and the collective backend; for streamed expert-cache changes, the selected direct/buffered I/O and reader-pool path, tensor offsets and cache-slot budget, requested keys, source callback table, independent byte/numerical reference and checked fixture coverage", + "produced_artifact": "The located load-path cost on the four dimensions with its matching lever, a startup ledger that keeps fixed overhead apart from per-request cost, a structural shard-completeness result naming the missing shards, a prefetch proposal behind an enable_prefetch switch defaulting to False or a recorded decision not to prefetch, an offload candidate order, the recorded loading mode, a distributed delivery choice with its proposed verification, and a preparation/serving record of serialized and rebuilt state, live resource owners and ABI/prepared-contract versions; proposed changes and verification targets, not a measured startup or delivery gain; a source-bound expert-cache byte/state audit and oracle-path coverage record, with synthetic-fixture, fallback and SKIP limits", + "failure_modes": [ + "Loading and warmup are amortized into per-request latency, or a host segment without timing points is treated as costing nothing", + "Warmup is accepted on total time while mismatched warmup shapes have warmed a different set of cache entries", + "In-flight .incomplete shards are re-downloaded as corrupt, or gap-free shard numbering is accepted without matching the index weight_map", + "Prefetch is forced without a profiled memory-bound hot spot or a non-memory-bound dependency window", + "Resolution or CFG tier-downs are applied to a construction-phase OOM, or offload is adopted when compute already hides the transfer", + "A free-memory probe runs on an mmap-backed load, or a run whose first mlock failure latched with only a warning is treated as fully resident", + "Disk counters that include cache and pipes are read as physical writes, or a run without a page-cache drop is reported as a cold start", + "The ceil-block scatter partition is used without checking it against the model's expected shard layout, or ranks run different orders or plans so their collectives mismatch", + "A faster H2D copy, local clone or rank-local filtered read is counted as a cross-rank communication gain", + "Serial and concurrent cache paths agree on identically corrupted placement bytes, or a contiguous fixture misses a separated-run alignment failure", + "Resident bytes or ordered per-k accumulation change while misses are pending, or an exit-zero SKIP/non-overlapped oracle is counted as overlap validation" + ], + "refusal_point": "Withholds a load-path win until the verification checklist holds and keeps the distributed-delivery checks as verification targets rather than results; does not force prefetch without a safe dependency window and disables it when neither a smaller size nor a moved position removes a regression; records unsupported save behaviors as unknown; rejects mismatched execution ABI or prepared-contract versions instead of editing their tags; and implies no Ascend support from the llama.cpp or fastsafetensors mechanisms; withholds expert-cache correctness/overlap conclusions when byte coverage, actual I/O/pool dispatch or model-oracle callback reachability is missing", + "hardware": "NPU for the device-side prefetch API (torch_npu.npu_prefetch, checked against the target CANN version) and the Diffusers offload playbook; the prefetch and fastsafetensors methodology transfers while the fastsafetensors and llama.cpp APIs do not, and cross-rank completion follows each collective backend's own wait contract" + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Normalized provenance covers the existing llama.cpp loading slice at 3e390af18de1131dda27913c00511725b4274c8a and the fastsafetensors distributed-delivery slice at 219e2561a41ede2d5d8eba611c248bb0effbf580; other inherited claims remain unnormalized with original identities and limits retained.", + "The readsets record static mechanisms and source recommendations, not validated startup, memory, placement or backend performance.", + "The fastsafetensors delivery readset does not revalidate inherited I/O/save claims or qualify uneven scatter, accelerator/NPU compatibility, inter-node transport or agent efficacy.", + "Flare adds source-only preparation/serving ownership and ABI/contract checks; live exporter handles, native backend execution, startup gains and model/dependency rights are not qualified.", + "The DeepSeek increment records source/test definitions only: its buffered byte oracle shares tensor metadata, its resident snapshot covers w1 bytes, and its tiny PyTorch/batched checks do not qualify the released model, backend performance or agent efficacy.", + "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/foundation-model-stack/fastsafetensors", + "commit": "219e2561a41ede2d5d8eba611c248bb0effbf580", + "paths": [ + "fastsafetensors/loader.py", + "fastsafetensors/file_buffer.py", + "fastsafetensors/tensor_factory.py", + "fastsafetensors/parallel_loader.py", + "fastsafetensors/frameworks/_torch.py", + "fastsafetensors/frameworks/_paddle.py", + "docs/overview.md", + "examples/run_parallel.py", + "tests/unit/test_broadcast_runs.py", + "tests/unit/test_subgroup.py", + "LICENSE" + ], + "readset": "references/fastsafetensors-transfer-readset.md" + } + ], + "empirical_validation": "not_run", + "title": "fastsafetensors distributed delivery contract", + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/optimization/weight-loading-optimization/references/fastsafetensors-transfer-readset.md", + "sha256": "5a39f14b102b0cee304541e011aa31e44e6b13527d1bee9987c3f3b66c064d3d" + }, + { + "type": "git", + "url": "https://github.com/foundation-model-stack/fastsafetensors", + "commit": "219e2561a41ede2d5d8eba611c248bb0effbf580", + "paths": [ + "fastsafetensors/loader.py", + "fastsafetensors/file_buffer.py", + "fastsafetensors/tensor_factory.py", + "fastsafetensors/parallel_loader.py", + "fastsafetensors/frameworks/_torch.py", + "fastsafetensors/frameworks/_paddle.py", + "docs/overview.md", + "examples/run_parallel.py", + "tests/unit/test_broadcast_runs.py", + "tests/unit/test_subgroup.py", + "LICENSE" + ], + "readset": "references/fastsafetensors-transfer-readset.md", + "revision_precision": "full" + } + ], + "id": "weight-loading-optimization.fastsafetensors-transfer-readset", + "kind": "knowledge", + "entrypoint": "fastsafetensors-transfer-readset.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/optimization/weight-loading-optimization/references/fastsafetensors-transfer-readset.md", + "byte_range": [ + 0, + 8656 + ], + "sha256": "5a39f14b102b0cee304541e011aa31e44e6b13527d1bee9987c3f3b66c064d3d" + } + } + }, + "content": { + "fastsafetensors-transfer-readset.md": { + "path": "playbooks/weight-loading-optimization/references/fastsafetensors-transfer-readset.md" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/weight-loading-optimization.flare-preparation-boundary.json b/src/inferrsi/knowledge/atoms/weight-loading-optimization.flare-preparation-boundary.json new file mode 100644 index 000000000..d4955a4d0 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/weight-loading-optimization.flare-preparation-boundary.json @@ -0,0 +1,118 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Diagnosing the serving-level weight load path from storage to device and choosing changes to it when startup or loading latency dominates: locating the cost by source, format, placement and duplication, accounting once-per-process loading and warmup apart from per-request cost, verifying sharded downloads, restricting device-side prefetch to profiled memory-bound hot spots and ordering CPU-tier offload; also covers source-scoped disk-loading modes, pinned staging, synchronous checkpoint save semantics, fastsafetensors broadcast/scatter/coalesced delivery and the separation of model preparation from serving. Request-time host overhead belongs to host-overhead-profiling, DCP asynchronous save performance to dcp-async-save-performance and distributed recovery validity to checkpoint-recovery-consistency; for disk-streamed routed experts, audit independent byte identity, resident/pending slot ownership, ordered accumulation and actual oracle callback coverage; the DeepSeek source slice describes POSIX storage, C/OpenMP and pthread ownership; target validation must identify its actual direct/buffered and reader-pool paths", + "prerequisites": "Flag names and API entry paths are re-verified against the pinned source revisions, and torch_npu.npu_prefetch details against the target CANN version, before they are relied on; card state is checked before launch and process placement fixed before measuring, through ascend-device-health and os-process-placement; the Diffusers enable_model_cpu_offload path requires accelerate", + "input_contract": "The current load path's byte source, file format, host-first or direct device placement and duplicated copies across processes or instances; startup timings for loading and warmup with byte and access counts per segment, and the expected warmup hit criteria; the safetensors index weight_map and the downloaded shard set; a profile showing memory-bound hot spots and the adjacent compute or communication segments; free device memory and whether an OOM occurs during construction or inference; for cross-rank delivery, the file-to-loader-group-rank map, tensor names, shapes, dtypes and call order, the required replicated or sliced output, the model's expected shard layout and the collective backend; for streamed expert-cache changes, the selected direct/buffered I/O and reader-pool path, tensor offsets and cache-slot budget, requested keys, source callback table, independent byte/numerical reference and checked fixture coverage", + "produced_artifact": "The located load-path cost on the four dimensions with its matching lever, a startup ledger that keeps fixed overhead apart from per-request cost, a structural shard-completeness result naming the missing shards, a prefetch proposal behind an enable_prefetch switch defaulting to False or a recorded decision not to prefetch, an offload candidate order, the recorded loading mode, a distributed delivery choice with its proposed verification, and a preparation/serving record of serialized and rebuilt state, live resource owners and ABI/prepared-contract versions; proposed changes and verification targets, not a measured startup or delivery gain; a source-bound expert-cache byte/state audit and oracle-path coverage record, with synthetic-fixture, fallback and SKIP limits", + "failure_modes": [ + "Loading and warmup are amortized into per-request latency, or a host segment without timing points is treated as costing nothing", + "Warmup is accepted on total time while mismatched warmup shapes have warmed a different set of cache entries", + "In-flight .incomplete shards are re-downloaded as corrupt, or gap-free shard numbering is accepted without matching the index weight_map", + "Prefetch is forced without a profiled memory-bound hot spot or a non-memory-bound dependency window", + "Resolution or CFG tier-downs are applied to a construction-phase OOM, or offload is adopted when compute already hides the transfer", + "A free-memory probe runs on an mmap-backed load, or a run whose first mlock failure latched with only a warning is treated as fully resident", + "Disk counters that include cache and pipes are read as physical writes, or a run without a page-cache drop is reported as a cold start", + "The ceil-block scatter partition is used without checking it against the model's expected shard layout, or ranks run different orders or plans so their collectives mismatch", + "A faster H2D copy, local clone or rank-local filtered read is counted as a cross-rank communication gain", + "Serial and concurrent cache paths agree on identically corrupted placement bytes, or a contiguous fixture misses a separated-run alignment failure", + "Resident bytes or ordered per-k accumulation change while misses are pending, or an exit-zero SKIP/non-overlapped oracle is counted as overlap validation" + ], + "refusal_point": "Withholds a load-path win until the verification checklist holds and keeps the distributed-delivery checks as verification targets rather than results; does not force prefetch without a safe dependency window and disables it when neither a smaller size nor a moved position removes a regression; records unsupported save behaviors as unknown; rejects mismatched execution ABI or prepared-contract versions instead of editing their tags; and implies no Ascend support from the llama.cpp or fastsafetensors mechanisms; withholds expert-cache correctness/overlap conclusions when byte coverage, actual I/O/pool dispatch or model-oracle callback reachability is missing", + "hardware": "NPU for the device-side prefetch API (torch_npu.npu_prefetch, checked against the target CANN version) and the Diffusers offload playbook; the prefetch and fastsafetensors methodology transfers while the fastsafetensors and llama.cpp APIs do not, and cross-rank completion follows each collective backend's own wait contract" + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Normalized provenance covers the existing llama.cpp loading slice at 3e390af18de1131dda27913c00511725b4274c8a and the fastsafetensors distributed-delivery slice at 219e2561a41ede2d5d8eba611c248bb0effbf580; other inherited claims remain unnormalized with original identities and limits retained.", + "The readsets record static mechanisms and source recommendations, not validated startup, memory, placement or backend performance.", + "The fastsafetensors delivery readset does not revalidate inherited I/O/save claims or qualify uneven scatter, accelerator/NPU compatibility, inter-node transport or agent efficacy.", + "Flare adds source-only preparation/serving ownership and ABI/contract checks; live exporter handles, native backend execution, startup gains and model/dependency rights are not qualified.", + "The DeepSeek increment records source/test definitions only: its buffered byte oracle shares tensor metadata, its resident snapshot covers w1 bytes, and its tiny PyTorch/batched checks do not qualify the released model, backend performance or agent efficacy.", + "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/NVIDIA/flare-local-inference", + "resolved_url": "https://github.com/NVIDIA/local-inference", + "commit": "bce032c014bae34502ba22d3304fa084d5b40afe", + "paths": [ + "README.md", + "docs/runtime-package-design.md", + "helios/src/runtime_package/format.rs", + "helios/src/runtime_package/model.rs", + "helios/src/execution/manifest.rs", + "helios/src/model/contract.rs", + "helios/src/model/catalog.rs", + "LICENSE" + ], + "readset": "references/flare-preparation-boundary.md", + "license": "Apache-2.0" + } + ], + "empirical_validation": "not_run", + "title": "Flare preparation and native-serving boundary", + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/optimization/weight-loading-optimization/references/flare-preparation-boundary.md", + "sha256": "c0d787522451f5b69a6d20b188d573183fa6d67de30f695ea668ca1ab7108929" + }, + { + "type": "git", + "url": "https://github.com/NVIDIA/flare-local-inference", + "resolved_url": "https://github.com/NVIDIA/local-inference", + "commit": "bce032c014bae34502ba22d3304fa084d5b40afe", + "paths": [ + "README.md", + "docs/runtime-package-design.md", + "helios/src/runtime_package/format.rs", + "helios/src/runtime_package/model.rs", + "helios/src/execution/manifest.rs", + "helios/src/model/contract.rs", + "helios/src/model/catalog.rs", + "LICENSE" + ], + "readset": "references/flare-preparation-boundary.md", + "license": "Apache-2.0", + "revision_precision": "full" + } + ], + "id": "weight-loading-optimization.flare-preparation-boundary", + "kind": "knowledge", + "entrypoint": "flare-preparation-boundary.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/optimization/weight-loading-optimization/references/flare-preparation-boundary.md", + "byte_range": [ + 0, + 5388 + ], + "sha256": "c0d787522451f5b69a6d20b188d573183fa6d67de30f695ea668ca1ab7108929" + } + } + }, + "content": { + "flare-preparation-boundary.md": { + "path": "playbooks/weight-loading-optimization/references/flare-preparation-boundary.md" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/weight-loading-optimization.llama-loading-readset.json b/src/inferrsi/knowledge/atoms/weight-loading-optimization.llama-loading-readset.json new file mode 100644 index 000000000..fe6acaaf3 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/weight-loading-optimization.llama-loading-readset.json @@ -0,0 +1,116 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Diagnosing the serving-level weight load path from storage to device and choosing changes to it when startup or loading latency dominates: locating the cost by source, format, placement and duplication, accounting once-per-process loading and warmup apart from per-request cost, verifying sharded downloads, restricting device-side prefetch to profiled memory-bound hot spots and ordering CPU-tier offload; also covers source-scoped disk-loading modes, pinned staging, synchronous checkpoint save semantics, fastsafetensors broadcast/scatter/coalesced delivery and the separation of model preparation from serving. Request-time host overhead belongs to host-overhead-profiling, DCP asynchronous save performance to dcp-async-save-performance and distributed recovery validity to checkpoint-recovery-consistency; for disk-streamed routed experts, audit independent byte identity, resident/pending slot ownership, ordered accumulation and actual oracle callback coverage; the DeepSeek source slice describes POSIX storage, C/OpenMP and pthread ownership; target validation must identify its actual direct/buffered and reader-pool paths", + "prerequisites": "Flag names and API entry paths are re-verified against the pinned source revisions, and torch_npu.npu_prefetch details against the target CANN version, before they are relied on; card state is checked before launch and process placement fixed before measuring, through ascend-device-health and os-process-placement; the Diffusers enable_model_cpu_offload path requires accelerate", + "input_contract": "The current load path's byte source, file format, host-first or direct device placement and duplicated copies across processes or instances; startup timings for loading and warmup with byte and access counts per segment, and the expected warmup hit criteria; the safetensors index weight_map and the downloaded shard set; a profile showing memory-bound hot spots and the adjacent compute or communication segments; free device memory and whether an OOM occurs during construction or inference; for cross-rank delivery, the file-to-loader-group-rank map, tensor names, shapes, dtypes and call order, the required replicated or sliced output, the model's expected shard layout and the collective backend; for streamed expert-cache changes, the selected direct/buffered I/O and reader-pool path, tensor offsets and cache-slot budget, requested keys, source callback table, independent byte/numerical reference and checked fixture coverage", + "produced_artifact": "The located load-path cost on the four dimensions with its matching lever, a startup ledger that keeps fixed overhead apart from per-request cost, a structural shard-completeness result naming the missing shards, a prefetch proposal behind an enable_prefetch switch defaulting to False or a recorded decision not to prefetch, an offload candidate order, the recorded loading mode, a distributed delivery choice with its proposed verification, and a preparation/serving record of serialized and rebuilt state, live resource owners and ABI/prepared-contract versions; proposed changes and verification targets, not a measured startup or delivery gain; a source-bound expert-cache byte/state audit and oracle-path coverage record, with synthetic-fixture, fallback and SKIP limits", + "failure_modes": [ + "Loading and warmup are amortized into per-request latency, or a host segment without timing points is treated as costing nothing", + "Warmup is accepted on total time while mismatched warmup shapes have warmed a different set of cache entries", + "In-flight .incomplete shards are re-downloaded as corrupt, or gap-free shard numbering is accepted without matching the index weight_map", + "Prefetch is forced without a profiled memory-bound hot spot or a non-memory-bound dependency window", + "Resolution or CFG tier-downs are applied to a construction-phase OOM, or offload is adopted when compute already hides the transfer", + "A free-memory probe runs on an mmap-backed load, or a run whose first mlock failure latched with only a warning is treated as fully resident", + "Disk counters that include cache and pipes are read as physical writes, or a run without a page-cache drop is reported as a cold start", + "The ceil-block scatter partition is used without checking it against the model's expected shard layout, or ranks run different orders or plans so their collectives mismatch", + "A faster H2D copy, local clone or rank-local filtered read is counted as a cross-rank communication gain", + "Serial and concurrent cache paths agree on identically corrupted placement bytes, or a contiguous fixture misses a separated-run alignment failure", + "Resident bytes or ordered per-k accumulation change while misses are pending, or an exit-zero SKIP/non-overlapped oracle is counted as overlap validation" + ], + "refusal_point": "Withholds a load-path win until the verification checklist holds and keeps the distributed-delivery checks as verification targets rather than results; does not force prefetch without a safe dependency window and disables it when neither a smaller size nor a moved position removes a regression; records unsupported save behaviors as unknown; rejects mismatched execution ABI or prepared-contract versions instead of editing their tags; and implies no Ascend support from the llama.cpp or fastsafetensors mechanisms; withholds expert-cache correctness/overlap conclusions when byte coverage, actual I/O/pool dispatch or model-oracle callback reachability is missing", + "hardware": "NPU for the device-side prefetch API (torch_npu.npu_prefetch, checked against the target CANN version) and the Diffusers offload playbook; the prefetch and fastsafetensors methodology transfers while the fastsafetensors and llama.cpp APIs do not, and cross-rank completion follows each collective backend's own wait contract" + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Normalized provenance covers the existing llama.cpp loading slice at 3e390af18de1131dda27913c00511725b4274c8a and the fastsafetensors distributed-delivery slice at 219e2561a41ede2d5d8eba611c248bb0effbf580; other inherited claims remain unnormalized with original identities and limits retained.", + "The readsets record static mechanisms and source recommendations, not validated startup, memory, placement or backend performance.", + "The fastsafetensors delivery readset does not revalidate inherited I/O/save claims or qualify uneven scatter, accelerator/NPU compatibility, inter-node transport or agent efficacy.", + "Flare adds source-only preparation/serving ownership and ABI/contract checks; live exporter handles, native backend execution, startup gains and model/dependency rights are not qualified.", + "The DeepSeek increment records source/test definitions only: its buffered byte oracle shares tensor metadata, its resident snapshot covers w1 bytes, and its tiny PyTorch/batched checks do not qualify the released model, backend performance or agent efficacy.", + "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/ggml-org/llama.cpp", + "commit": "3e390af18de1131dda27913c00511725b4274c8a", + "paths": [ + "common/arg.cpp", + "common/common.cpp", + "common/fit.cpp", + "src/llama-model.cpp", + "src/llama-model-loader.cpp", + "src/llama-model-loader.h", + "src/llama-mmap.cpp", + "src/llama-mmap.h", + "LICENSE" + ], + "readset": "references/llama-loading-readset.md" + } + ], + "empirical_validation": "not_run", + "title": "llama.cpp loading provenance", + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/optimization/weight-loading-optimization/references/llama-loading-readset.md", + "sha256": "6c640f28ee3f0253a17b81461c865cb9f947367002cb75bf72550c4572d02e97" + }, + { + "type": "git", + "url": "https://github.com/ggml-org/llama.cpp", + "commit": "3e390af18de1131dda27913c00511725b4274c8a", + "paths": [ + "common/arg.cpp", + "common/common.cpp", + "common/fit.cpp", + "src/llama-model.cpp", + "src/llama-model-loader.cpp", + "src/llama-model-loader.h", + "src/llama-mmap.cpp", + "src/llama-mmap.h", + "LICENSE" + ], + "readset": "references/llama-loading-readset.md", + "revision_precision": "full" + } + ], + "id": "weight-loading-optimization.llama-loading-readset", + "kind": "knowledge", + "entrypoint": "llama-loading-readset.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/optimization/weight-loading-optimization/references/llama-loading-readset.md", + "byte_range": [ + 0, + 6392 + ], + "sha256": "6c640f28ee3f0253a17b81461c865cb9f947367002cb75bf72550c4572d02e97" + } + } + }, + "content": { + "llama-loading-readset.md": { + "path": "playbooks/weight-loading-optimization/references/llama-loading-readset.md" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/weight-loading-optimization.original.json b/src/inferrsi/knowledge/atoms/weight-loading-optimization.original.json new file mode 100644 index 000000000..7a0d702b9 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/weight-loading-optimization.original.json @@ -0,0 +1,270 @@ +{ + "authority": "checkout", + "metadata": { + "id": "weight-loading-optimization.original", + "kind": "knowledge", + "entrypoint": "guide.md", + "title": "Optimize the serving-level weight load path from storage to device: judge the load path on four dimensions (source, format, placement, duplication), account startup fixed overhead separately from per-request cost with bytes-and-counts lines and hit-criteria warmup validation, verify sharded weight downloads against the safetensors index, apply device-side weight prefetch only on profiled memory-bound hot spots, and order CPU-tier offload candidates by change surface. Includes source-scoped disk-loading modes, pinned staging, synchronous checkpoint save semantics and fastsafetensors broadcast/scatter/coalesced delivery; also audit streamed expert-cache byte correctness and begin/end overlap contracts. Use when startup/loading latency dominates or a streamed expert-cache change needs correctness verification; route DCP asynchronous save performance and distributed recovery validity to their separate skills.\n", + "origin": [ + "external" + ], + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/optimization/weight-loading-optimization/SKILL.md", + "sha256": "e5be547a1ddac312be09a5d8a8d61645f4de1c8e3f23e432cd297bcef677cc8e" + }, + { + "type": "git", + "url": "https://github.com/ggml-org/llama.cpp", + "commit": "3e390af18de1131dda27913c00511725b4274c8a", + "paths": [ + "common/arg.cpp", + "common/common.cpp", + "common/fit.cpp", + "src/llama-model.cpp", + "src/llama-model-loader.cpp", + "src/llama-model-loader.h", + "src/llama-mmap.cpp", + "src/llama-mmap.h", + "LICENSE" + ], + "readset": "references/llama-loading-readset.md", + "revision_precision": "full" + }, + { + "type": "git", + "url": "https://github.com/foundation-model-stack/fastsafetensors", + "commit": "219e2561a41ede2d5d8eba611c248bb0effbf580", + "paths": [ + "fastsafetensors/loader.py", + "fastsafetensors/file_buffer.py", + "fastsafetensors/tensor_factory.py", + "fastsafetensors/parallel_loader.py", + "fastsafetensors/frameworks/_torch.py", + "fastsafetensors/frameworks/_paddle.py", + "docs/overview.md", + "examples/run_parallel.py", + "tests/unit/test_broadcast_runs.py", + "tests/unit/test_subgroup.py", + "LICENSE" + ], + "readset": "references/fastsafetensors-transfer-readset.md", + "revision_precision": "full" + }, + { + "type": "git", + "url": "https://github.com/NVIDIA/flare-local-inference", + "resolved_url": "https://github.com/NVIDIA/local-inference", + "commit": "bce032c014bae34502ba22d3304fa084d5b40afe", + "paths": [ + "README.md", + "docs/runtime-package-design.md", + "helios/src/runtime_package/format.rs", + "helios/src/runtime_package/model.rs", + "helios/src/execution/manifest.rs", + "helios/src/model/contract.rs", + "helios/src/model/catalog.rs", + "LICENSE" + ], + "readset": "references/flare-preparation-boundary.md", + "license": "Apache-2.0", + "revision_precision": "full" + }, + { + "type": "git", + "url": "https://github.com/ronak-create/deepseek-v4-in-c", + "commit": "d0402056d0da4bf7edfd2d4977de479a0db9d201", + "paths": [ + "LICENSE", + "README.md", + "Makefile", + "src/cache/dsv4_cache.c", + "src/cache/dsv4_cache.h", + "src/io/dsv4_st.c", + "src/io/dsv4_st.h", + "src/model/dsv4_layer.h", + "src/model/dsv4_layer.c", + "src/cli/dsv4_run.c", + "tests/unit/test_cache.c", + "tests/unit/test_model_oracle.c", + "tools/make_st_fixture.py", + "tools/make_tiny_checkpoint.py", + "tools/dsv4_ref.py" + ], + "readset": "references/deepseek-expert-cache-oracles.md", + "license": "Apache-2.0 (repository declaration and selected-file notices; third-party/model rights excluded)", + "revision_precision": "full" + } + ], + "applicability": { + "scope": "Diagnosing the serving-level weight load path from storage to device and choosing changes to it when startup or loading latency dominates: locating the cost by source, format, placement and duplication, accounting once-per-process loading and warmup apart from per-request cost, verifying sharded downloads, restricting device-side prefetch to profiled memory-bound hot spots and ordering CPU-tier offload; also covers source-scoped disk-loading modes, pinned staging, synchronous checkpoint save semantics, fastsafetensors broadcast/scatter/coalesced delivery and the separation of model preparation from serving. Request-time host overhead belongs to host-overhead-profiling, DCP asynchronous save performance to dcp-async-save-performance and distributed recovery validity to checkpoint-recovery-consistency; for disk-streamed routed experts, audit independent byte identity, resident/pending slot ownership, ordered accumulation and actual oracle callback coverage; the DeepSeek source slice describes POSIX storage, C/OpenMP and pthread ownership; target validation must identify its actual direct/buffered and reader-pool paths", + "prerequisites": "Flag names and API entry paths are re-verified against the pinned source revisions, and torch_npu.npu_prefetch details against the target CANN version, before they are relied on; card state is checked before launch and process placement fixed before measuring, through ascend-device-health and os-process-placement; the Diffusers enable_model_cpu_offload path requires accelerate", + "input_contract": "The current load path's byte source, file format, host-first or direct device placement and duplicated copies across processes or instances; startup timings for loading and warmup with byte and access counts per segment, and the expected warmup hit criteria; the safetensors index weight_map and the downloaded shard set; a profile showing memory-bound hot spots and the adjacent compute or communication segments; free device memory and whether an OOM occurs during construction or inference; for cross-rank delivery, the file-to-loader-group-rank map, tensor names, shapes, dtypes and call order, the required replicated or sliced output, the model's expected shard layout and the collective backend; for streamed expert-cache changes, the selected direct/buffered I/O and reader-pool path, tensor offsets and cache-slot budget, requested keys, source callback table, independent byte/numerical reference and checked fixture coverage", + "produced_artifact": "The located load-path cost on the four dimensions with its matching lever, a startup ledger that keeps fixed overhead apart from per-request cost, a structural shard-completeness result naming the missing shards, a prefetch proposal behind an enable_prefetch switch defaulting to False or a recorded decision not to prefetch, an offload candidate order, the recorded loading mode, a distributed delivery choice with its proposed verification, and a preparation/serving record of serialized and rebuilt state, live resource owners and ABI/prepared-contract versions; proposed changes and verification targets, not a measured startup or delivery gain; a source-bound expert-cache byte/state audit and oracle-path coverage record, with synthetic-fixture, fallback and SKIP limits", + "failure_modes": [ + "Loading and warmup are amortized into per-request latency, or a host segment without timing points is treated as costing nothing", + "Warmup is accepted on total time while mismatched warmup shapes have warmed a different set of cache entries", + "In-flight .incomplete shards are re-downloaded as corrupt, or gap-free shard numbering is accepted without matching the index weight_map", + "Prefetch is forced without a profiled memory-bound hot spot or a non-memory-bound dependency window", + "Resolution or CFG tier-downs are applied to a construction-phase OOM, or offload is adopted when compute already hides the transfer", + "A free-memory probe runs on an mmap-backed load, or a run whose first mlock failure latched with only a warning is treated as fully resident", + "Disk counters that include cache and pipes are read as physical writes, or a run without a page-cache drop is reported as a cold start", + "The ceil-block scatter partition is used without checking it against the model's expected shard layout, or ranks run different orders or plans so their collectives mismatch", + "A faster H2D copy, local clone or rank-local filtered read is counted as a cross-rank communication gain", + "Serial and concurrent cache paths agree on identically corrupted placement bytes, or a contiguous fixture misses a separated-run alignment failure", + "Resident bytes or ordered per-k accumulation change while misses are pending, or an exit-zero SKIP/non-overlapped oracle is counted as overlap validation" + ], + "refusal_point": "Withholds a load-path win until the verification checklist holds and keeps the distributed-delivery checks as verification targets rather than results; does not force prefetch without a safe dependency window and disables it when neither a smaller size nor a moved position removes a regression; records unsupported save behaviors as unknown; rejects mismatched execution ABI or prepared-contract versions instead of editing their tags; and implies no Ascend support from the llama.cpp or fastsafetensors mechanisms; withholds expert-cache correctness/overlap conclusions when byte coverage, actual I/O/pool dispatch or model-oracle callback reachability is missing", + "hardware": "NPU for the device-side prefetch API (torch_npu.npu_prefetch, checked against the target CANN version) and the Diffusers offload playbook; the prefetch and fastsafetensors methodology transfers while the fastsafetensors and llama.cpp APIs do not, and cross-rank completion follows each collective backend's own wait contract" + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Normalized provenance covers the existing llama.cpp loading slice at 3e390af18de1131dda27913c00511725b4274c8a and the fastsafetensors distributed-delivery slice at 219e2561a41ede2d5d8eba611c248bb0effbf580; other inherited claims remain unnormalized with original identities and limits retained.", + "The readsets record static mechanisms and source recommendations, not validated startup, memory, placement or backend performance.", + "The fastsafetensors delivery readset does not revalidate inherited I/O/save claims or qualify uneven scatter, accelerator/NPU compatibility, inter-node transport or agent efficacy.", + "Flare adds source-only preparation/serving ownership and ABI/contract checks; live exporter handles, native backend execution, startup gains and model/dependency rights are not qualified.", + "The DeepSeek increment records source/test definitions only: its buffered byte oracle shares tensor metadata, its resident snapshot covers w1 bytes, and its tiny PyTorch/batched checks do not qualify the released model, backend performance or agent efficacy.", + "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/ggml-org/llama.cpp", + "commit": "3e390af18de1131dda27913c00511725b4274c8a", + "paths": [ + "common/arg.cpp", + "common/common.cpp", + "common/fit.cpp", + "src/llama-model.cpp", + "src/llama-model-loader.cpp", + "src/llama-model-loader.h", + "src/llama-mmap.cpp", + "src/llama-mmap.h", + "LICENSE" + ], + "readset": "references/llama-loading-readset.md" + }, + { + "type": "git", + "url": "https://github.com/foundation-model-stack/fastsafetensors", + "commit": "219e2561a41ede2d5d8eba611c248bb0effbf580", + "paths": [ + "fastsafetensors/loader.py", + "fastsafetensors/file_buffer.py", + "fastsafetensors/tensor_factory.py", + "fastsafetensors/parallel_loader.py", + "fastsafetensors/frameworks/_torch.py", + "fastsafetensors/frameworks/_paddle.py", + "docs/overview.md", + "examples/run_parallel.py", + "tests/unit/test_broadcast_runs.py", + "tests/unit/test_subgroup.py", + "LICENSE" + ], + "readset": "references/fastsafetensors-transfer-readset.md" + }, + { + "type": "git", + "url": "https://github.com/NVIDIA/flare-local-inference", + "resolved_url": "https://github.com/NVIDIA/local-inference", + "commit": "bce032c014bae34502ba22d3304fa084d5b40afe", + "paths": [ + "README.md", + "docs/runtime-package-design.md", + "helios/src/runtime_package/format.rs", + "helios/src/runtime_package/model.rs", + "helios/src/execution/manifest.rs", + "helios/src/model/contract.rs", + "helios/src/model/catalog.rs", + "LICENSE" + ], + "readset": "references/flare-preparation-boundary.md", + "license": "Apache-2.0" + }, + { + "type": "git", + "url": "https://github.com/ronak-create/deepseek-v4-in-c", + "commit": "d0402056d0da4bf7edfd2d4977de479a0db9d201", + "paths": [ + "LICENSE", + "README.md", + "Makefile", + "src/cache/dsv4_cache.c", + "src/cache/dsv4_cache.h", + "src/io/dsv4_st.c", + "src/io/dsv4_st.h", + "src/model/dsv4_layer.h", + "src/model/dsv4_layer.c", + "src/cli/dsv4_run.c", + "tests/unit/test_cache.c", + "tests/unit/test_model_oracle.c", + "tools/make_st_fixture.py", + "tools/make_tiny_checkpoint.py", + "tools/dsv4_ref.py" + ], + "readset": "references/deepseek-expert-cache-oracles.md", + "license": "Apache-2.0 (repository declaration and selected-file notices; third-party/model rights excluded)" + } + ], + "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/optimization/weight-loading-optimization/SKILL.md", + "byte_range": [ + 0, + 41025 + ], + "sha256": "e5be547a1ddac312be09a5d8a8d61645f4de1c8e3f23e432cd297bcef677cc8e" + } + } + }, + "content": { + "guide.md": { + "path": "playbooks/weight-loading-optimization.md" + } + }, + "parts": { + "navigation": { + "skill_section": "navigation", + "layer": "L0", + "byte_range": [ + 0, + 976 + ], + "sha256": "05a67f51263c9e85cf4c8b6a549cbe24d209af347b34452fcc0d013e7fdf41b2" + }, + "decision": { + "skill_section": "decision", + "layer": "L1", + "byte_range": [ + 0, + 13662 + ], + "sha256": "8cc9a39e67a624167820199e6dacde5d74181b6e8cba88641378db404bc2ec3d" + }, + "procedure": { + "skill_section": "procedure", + "layer": "L2", + "byte_range": [ + 13662, + 41025 + ], + "sha256": "85fb9d206c3a4159fa0aebe7644b2eb28e54f557d4ab71cefec766501439c649" + } + } +} diff --git a/src/inferrsi/knowledge/compositions/video-diffusion-optimization.json b/src/inferrsi/knowledge/compositions/video-diffusion-optimization.json new file mode 100644 index 000000000..b905978e5 --- /dev/null +++ b/src/inferrsi/knowledge/compositions/video-diffusion-optimization.json @@ -0,0 +1,117 @@ +{ + "authority": "checkout", + "metadata": { + "id": "video-diffusion-optimization", + "kind": "skill", + "entrypoint": "playbooks/optimization/video-diffusion-optimization/SKILL.md", + "title": "Run and verify goal-driven video diffusion optimization, backend-agnostic. Use when the user asks for latency, RTF, throughput, or memory targets across VLM, DiT, MoE, attention, or VAE, on any accelerator. Not for text-only LLMs.", + "origin": [ + "first-party" + ], + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/optimization/video-diffusion-optimization/SKILL.md", + "sha256": "6466f46b63f6149e9692fdc344fca5f3af9e1961b59fd48f25b778256089c203" + }, + { + "type": "unknown", + "note": "Legacy provenance remains in procedure/readsets" + } + ], + "applicability": { + "scope": "Backend-agnostic video diffusion inference and serving optimization", + "hardware": "Any accelerator (Ascend NPU, CUDA GPU, and others); operator names, memory layouts, and profiler references are re-derived per backend", + "prerequisites": "A reproducible benchmark, a frozen quality check, and numeric gates defined in the governing acceptance issue" + }, + "state": "candidate", + "limitations": [ + "Backend-agnostic skeleton only. The first-hand field notes are Ascend-specific and live in the ascend-video-diffusion-optimization skill; every operator, layout and profiler reference (TransData, FRACTAL_NZ, CANN) must be re-derived per backend.", + "Candidate workflow guidance; not independently validated.", + "Model identifiers, campaign revisions, and numeric gates are intentionally excluded and remain issue-scoped.", + "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": [], + "empirical_validation": "not_run", + "required_resources": [ + "playbooks/optimization/video-diffusion-optimization/SKILL.md", + "playbooks/optimization/video-diffusion-optimization/assets/campaign.template.json", + "playbooks/optimization/video-diffusion-optimization/scripts/evaluate_target.py" + ], + "composition": { + "when": {}, + "license": "Apache-2.0", + "permissions": { + "read": true, + "retain": true, + "redistribute": true + }, + "nodes": { + "navigation": { + "ref": "checkout:video-diffusion-optimization.original.navigation", + "revision": "sha256:46ea77ecea2f8001f5d3263393838725bd9f4036d768529a3bbc2219f288701f" + }, + "decision": { + "ref": "checkout:video-diffusion-optimization.original.decision", + "revision": "sha256:ba9d9ef6ab1ae24cc8c0ba57d1b54bd935d60b6f15285d2cb0e8bfbfb12d5cfd" + }, + "procedure": { + "ref": "checkout:video-diffusion-optimization.original.procedure", + "revision": "sha256:8bce934f6c902f81c7cd13c33e2cb069798c4826094067232f2b2041efb8be59", + "requires": [ + "decision" + ] + }, + "original": { + "ref": "checkout:video-diffusion-optimization.original", + "revision": "sha256:34708addf198eb98dc7fe54a083d94fed33e1c95e0203d54232d202b78860b26" + }, + "campaign-template": { + "ref": "checkout:video-diffusion-optimization.campaign-template", + "revision": "sha256:77057d9c28f378ae4b7075a624d48135bd045a7047e488a1586bbbf84298707d" + }, + "evaluate-target": { + "ref": "checkout:video-diffusion-optimization.evaluate-target", + "revision": "sha256:c7718bb0a4378a4535b41d69f8744a1ff39dce65a83cb3916b5e3c87cdecff67" + } + }, + "routes": { + "navigation": { + "layer": "L0", + "required": [ + "navigation" + ] + }, + "decision": { + "layer": "L1", + "required": [ + "decision" + ] + }, + "procedure": { + "layer": "L2", + "required": [ + "procedure" + ] + }, + "originals": { + "layer": "L3", + "required": [ + "original", + "campaign-template", + "evaluate-target" + ] + } + } + } + }, + "directory_resources": { + "playbooks/optimization/video-diffusion-optimization/SKILL.md": "original", + "playbooks/optimization/video-diffusion-optimization/assets/campaign.template.json": "campaign-template", + "playbooks/optimization/video-diffusion-optimization/scripts/evaluate_target.py": "evaluate-target" + } +} diff --git a/src/inferrsi/knowledge/compositions/weight-loading-optimization.json b/src/inferrsi/knowledge/compositions/weight-loading-optimization.json new file mode 100644 index 000000000..ca9d538b0 --- /dev/null +++ b/src/inferrsi/knowledge/compositions/weight-loading-optimization.json @@ -0,0 +1,314 @@ +{ + "authority": "checkout", + "metadata": { + "id": "weight-loading-optimization", + "kind": "skill", + "entrypoint": "playbooks/optimization/weight-loading-optimization/SKILL.md", + "title": "Optimize the serving-level weight load path from storage to device: judge the load path on four dimensions (source, format, placement, duplication), account startup fixed overhead separately from per-request cost with bytes-and-counts lines and hit-criteria warmup validation, verify sharded weight downloads against the safetensors index, apply device-side weight prefetch only on profiled memory-bound hot spots, and order CPU-tier offload candidates by change surface. Includes source-scoped disk-loading modes, pinned staging, synchronous checkpoint save semantics and fastsafetensors broadcast/scatter/coalesced delivery; also audit streamed expert-cache byte correctness and begin/end overlap contracts. Use when startup/loading latency dominates or a streamed expert-cache change needs correctness verification; route DCP asynchronous save performance and distributed recovery validity to their separate skills.\n", + "origin": [ + "external" + ], + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/optimization/weight-loading-optimization/SKILL.md", + "sha256": "e5be547a1ddac312be09a5d8a8d61645f4de1c8e3f23e432cd297bcef677cc8e" + }, + { + "type": "git", + "url": "https://github.com/ggml-org/llama.cpp", + "commit": "3e390af18de1131dda27913c00511725b4274c8a", + "paths": [ + "common/arg.cpp", + "common/common.cpp", + "common/fit.cpp", + "src/llama-model.cpp", + "src/llama-model-loader.cpp", + "src/llama-model-loader.h", + "src/llama-mmap.cpp", + "src/llama-mmap.h", + "LICENSE" + ], + "readset": "references/llama-loading-readset.md", + "revision_precision": "full" + }, + { + "type": "git", + "url": "https://github.com/foundation-model-stack/fastsafetensors", + "commit": "219e2561a41ede2d5d8eba611c248bb0effbf580", + "paths": [ + "fastsafetensors/loader.py", + "fastsafetensors/file_buffer.py", + "fastsafetensors/tensor_factory.py", + "fastsafetensors/parallel_loader.py", + "fastsafetensors/frameworks/_torch.py", + "fastsafetensors/frameworks/_paddle.py", + "docs/overview.md", + "examples/run_parallel.py", + "tests/unit/test_broadcast_runs.py", + "tests/unit/test_subgroup.py", + "LICENSE" + ], + "readset": "references/fastsafetensors-transfer-readset.md", + "revision_precision": "full" + }, + { + "type": "git", + "url": "https://github.com/NVIDIA/flare-local-inference", + "resolved_url": "https://github.com/NVIDIA/local-inference", + "commit": "bce032c014bae34502ba22d3304fa084d5b40afe", + "paths": [ + "README.md", + "docs/runtime-package-design.md", + "helios/src/runtime_package/format.rs", + "helios/src/runtime_package/model.rs", + "helios/src/execution/manifest.rs", + "helios/src/model/contract.rs", + "helios/src/model/catalog.rs", + "LICENSE" + ], + "readset": "references/flare-preparation-boundary.md", + "license": "Apache-2.0", + "revision_precision": "full" + }, + { + "type": "git", + "url": "https://github.com/ronak-create/deepseek-v4-in-c", + "commit": "d0402056d0da4bf7edfd2d4977de479a0db9d201", + "paths": [ + "LICENSE", + "README.md", + "Makefile", + "src/cache/dsv4_cache.c", + "src/cache/dsv4_cache.h", + "src/io/dsv4_st.c", + "src/io/dsv4_st.h", + "src/model/dsv4_layer.h", + "src/model/dsv4_layer.c", + "src/cli/dsv4_run.c", + "tests/unit/test_cache.c", + "tests/unit/test_model_oracle.c", + "tools/make_st_fixture.py", + "tools/make_tiny_checkpoint.py", + "tools/dsv4_ref.py" + ], + "readset": "references/deepseek-expert-cache-oracles.md", + "license": "Apache-2.0 (repository declaration and selected-file notices; third-party/model rights excluded)", + "revision_precision": "full" + } + ], + "applicability": { + "scope": "Diagnosing the serving-level weight load path from storage to device and choosing changes to it when startup or loading latency dominates: locating the cost by source, format, placement and duplication, accounting once-per-process loading and warmup apart from per-request cost, verifying sharded downloads, restricting device-side prefetch to profiled memory-bound hot spots and ordering CPU-tier offload; also covers source-scoped disk-loading modes, pinned staging, synchronous checkpoint save semantics, fastsafetensors broadcast/scatter/coalesced delivery and the separation of model preparation from serving. Request-time host overhead belongs to host-overhead-profiling, DCP asynchronous save performance to dcp-async-save-performance and distributed recovery validity to checkpoint-recovery-consistency; for disk-streamed routed experts, audit independent byte identity, resident/pending slot ownership, ordered accumulation and actual oracle callback coverage; the DeepSeek source slice describes POSIX storage, C/OpenMP and pthread ownership; target validation must identify its actual direct/buffered and reader-pool paths", + "prerequisites": "Flag names and API entry paths are re-verified against the pinned source revisions, and torch_npu.npu_prefetch details against the target CANN version, before they are relied on; card state is checked before launch and process placement fixed before measuring, through ascend-device-health and os-process-placement; the Diffusers enable_model_cpu_offload path requires accelerate", + "input_contract": "The current load path's byte source, file format, host-first or direct device placement and duplicated copies across processes or instances; startup timings for loading and warmup with byte and access counts per segment, and the expected warmup hit criteria; the safetensors index weight_map and the downloaded shard set; a profile showing memory-bound hot spots and the adjacent compute or communication segments; free device memory and whether an OOM occurs during construction or inference; for cross-rank delivery, the file-to-loader-group-rank map, tensor names, shapes, dtypes and call order, the required replicated or sliced output, the model's expected shard layout and the collective backend; for streamed expert-cache changes, the selected direct/buffered I/O and reader-pool path, tensor offsets and cache-slot budget, requested keys, source callback table, independent byte/numerical reference and checked fixture coverage", + "produced_artifact": "The located load-path cost on the four dimensions with its matching lever, a startup ledger that keeps fixed overhead apart from per-request cost, a structural shard-completeness result naming the missing shards, a prefetch proposal behind an enable_prefetch switch defaulting to False or a recorded decision not to prefetch, an offload candidate order, the recorded loading mode, a distributed delivery choice with its proposed verification, and a preparation/serving record of serialized and rebuilt state, live resource owners and ABI/prepared-contract versions; proposed changes and verification targets, not a measured startup or delivery gain; a source-bound expert-cache byte/state audit and oracle-path coverage record, with synthetic-fixture, fallback and SKIP limits", + "failure_modes": [ + "Loading and warmup are amortized into per-request latency, or a host segment without timing points is treated as costing nothing", + "Warmup is accepted on total time while mismatched warmup shapes have warmed a different set of cache entries", + "In-flight .incomplete shards are re-downloaded as corrupt, or gap-free shard numbering is accepted without matching the index weight_map", + "Prefetch is forced without a profiled memory-bound hot spot or a non-memory-bound dependency window", + "Resolution or CFG tier-downs are applied to a construction-phase OOM, or offload is adopted when compute already hides the transfer", + "A free-memory probe runs on an mmap-backed load, or a run whose first mlock failure latched with only a warning is treated as fully resident", + "Disk counters that include cache and pipes are read as physical writes, or a run without a page-cache drop is reported as a cold start", + "The ceil-block scatter partition is used without checking it against the model's expected shard layout, or ranks run different orders or plans so their collectives mismatch", + "A faster H2D copy, local clone or rank-local filtered read is counted as a cross-rank communication gain", + "Serial and concurrent cache paths agree on identically corrupted placement bytes, or a contiguous fixture misses a separated-run alignment failure", + "Resident bytes or ordered per-k accumulation change while misses are pending, or an exit-zero SKIP/non-overlapped oracle is counted as overlap validation" + ], + "refusal_point": "Withholds a load-path win until the verification checklist holds and keeps the distributed-delivery checks as verification targets rather than results; does not force prefetch without a safe dependency window and disables it when neither a smaller size nor a moved position removes a regression; records unsupported save behaviors as unknown; rejects mismatched execution ABI or prepared-contract versions instead of editing their tags; and implies no Ascend support from the llama.cpp or fastsafetensors mechanisms; withholds expert-cache correctness/overlap conclusions when byte coverage, actual I/O/pool dispatch or model-oracle callback reachability is missing", + "hardware": "NPU for the device-side prefetch API (torch_npu.npu_prefetch, checked against the target CANN version) and the Diffusers offload playbook; the prefetch and fastsafetensors methodology transfers while the fastsafetensors and llama.cpp APIs do not, and cross-rank completion follows each collective backend's own wait contract" + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Normalized provenance covers the existing llama.cpp loading slice at 3e390af18de1131dda27913c00511725b4274c8a and the fastsafetensors distributed-delivery slice at 219e2561a41ede2d5d8eba611c248bb0effbf580; other inherited claims remain unnormalized with original identities and limits retained.", + "The readsets record static mechanisms and source recommendations, not validated startup, memory, placement or backend performance.", + "The fastsafetensors delivery readset does not revalidate inherited I/O/save claims or qualify uneven scatter, accelerator/NPU compatibility, inter-node transport or agent efficacy.", + "Flare adds source-only preparation/serving ownership and ABI/contract checks; live exporter handles, native backend execution, startup gains and model/dependency rights are not qualified.", + "The DeepSeek increment records source/test definitions only: its buffered byte oracle shares tensor metadata, its resident snapshot covers w1 bytes, and its tiny PyTorch/batched checks do not qualify the released model, backend performance or agent efficacy.", + "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/ggml-org/llama.cpp", + "commit": "3e390af18de1131dda27913c00511725b4274c8a", + "paths": [ + "common/arg.cpp", + "common/common.cpp", + "common/fit.cpp", + "src/llama-model.cpp", + "src/llama-model-loader.cpp", + "src/llama-model-loader.h", + "src/llama-mmap.cpp", + "src/llama-mmap.h", + "LICENSE" + ], + "readset": "references/llama-loading-readset.md" + }, + { + "type": "git", + "url": "https://github.com/foundation-model-stack/fastsafetensors", + "commit": "219e2561a41ede2d5d8eba611c248bb0effbf580", + "paths": [ + "fastsafetensors/loader.py", + "fastsafetensors/file_buffer.py", + "fastsafetensors/tensor_factory.py", + "fastsafetensors/parallel_loader.py", + "fastsafetensors/frameworks/_torch.py", + "fastsafetensors/frameworks/_paddle.py", + "docs/overview.md", + "examples/run_parallel.py", + "tests/unit/test_broadcast_runs.py", + "tests/unit/test_subgroup.py", + "LICENSE" + ], + "readset": "references/fastsafetensors-transfer-readset.md" + }, + { + "type": "git", + "url": "https://github.com/NVIDIA/flare-local-inference", + "resolved_url": "https://github.com/NVIDIA/local-inference", + "commit": "bce032c014bae34502ba22d3304fa084d5b40afe", + "paths": [ + "README.md", + "docs/runtime-package-design.md", + "helios/src/runtime_package/format.rs", + "helios/src/runtime_package/model.rs", + "helios/src/execution/manifest.rs", + "helios/src/model/contract.rs", + "helios/src/model/catalog.rs", + "LICENSE" + ], + "readset": "references/flare-preparation-boundary.md", + "license": "Apache-2.0" + }, + { + "type": "git", + "url": "https://github.com/ronak-create/deepseek-v4-in-c", + "commit": "d0402056d0da4bf7edfd2d4977de479a0db9d201", + "paths": [ + "LICENSE", + "README.md", + "Makefile", + "src/cache/dsv4_cache.c", + "src/cache/dsv4_cache.h", + "src/io/dsv4_st.c", + "src/io/dsv4_st.h", + "src/model/dsv4_layer.h", + "src/model/dsv4_layer.c", + "src/cli/dsv4_run.c", + "tests/unit/test_cache.c", + "tests/unit/test_model_oracle.c", + "tools/make_st_fixture.py", + "tools/make_tiny_checkpoint.py", + "tools/dsv4_ref.py" + ], + "readset": "references/deepseek-expert-cache-oracles.md", + "license": "Apache-2.0 (repository declaration and selected-file notices; third-party/model rights excluded)" + } + ], + "empirical_validation": "not_run", + "required_resources": [ + "playbooks/optimization/weight-loading-optimization/SKILL.md", + "playbooks/optimization/weight-loading-optimization/references/deepseek-expert-cache-oracles.md", + "playbooks/optimization/weight-loading-optimization/references/deepseek-expert-cache-source.json", + "playbooks/optimization/weight-loading-optimization/references/fastsafetensors-transfer-readset.md", + "playbooks/optimization/weight-loading-optimization/references/flare-preparation-boundary.md", + "playbooks/optimization/weight-loading-optimization/references/llama-loading-readset.md" + ], + "composition": { + "when": {}, + "license": "Apache-2.0", + "permissions": { + "read": true, + "retain": true, + "redistribute": true + }, + "nodes": { + "navigation": { + "ref": "checkout:weight-loading-optimization.original.navigation", + "revision": "sha256:c288603970f02ef08ee3f3ebf5c23084eba0f2f4592807ccd4017d75baebc8c4" + }, + "decision": { + "ref": "checkout:weight-loading-optimization.original.decision", + "revision": "sha256:6a6bc57fc80c405dadd4d578ccecabef84d77999e1e6c1cb36570993b653e6db" + }, + "procedure": { + "ref": "checkout:weight-loading-optimization.original.procedure", + "revision": "sha256:2232542c416853be806983d9cdf1f1899cd57b0302a6c56fa3650d108f6a75a5", + "requires": [ + "decision" + ] + }, + "original": { + "ref": "checkout:weight-loading-optimization.original", + "revision": "sha256:ff8f9b4fba69352382301af6c926c81ece62b43db05772f96c4389e48f76f730" + }, + "deepseek-expert-cache-oracles": { + "ref": "checkout:weight-loading-optimization.deepseek-expert-cache-oracles", + "revision": "sha256:276bdf99748b5bcee0791a2e32fe40c9d792eaa4d9cd91f7c40cca584d264735" + }, + "deepseek-expert-cache-source": { + "ref": "checkout:weight-loading-optimization.deepseek-expert-cache-source", + "revision": "sha256:3ec493ec9c560277113fd7d80db34e7e8c935a6cf1d839da39339f99266d4631" + }, + "fastsafetensors-transfer-readset": { + "ref": "checkout:weight-loading-optimization.fastsafetensors-transfer-readset", + "revision": "sha256:48073ef79f67a360301aab61abc2bfa974c6a79fb9efd723c8861b0da4fe00a7" + }, + "flare-preparation-boundary": { + "ref": "checkout:weight-loading-optimization.flare-preparation-boundary", + "revision": "sha256:fa7543eb1b7d4e2f49003cd6d5c0a16cd932018b0ea30be9c1bb93f7591c64c7" + }, + "llama-loading-readset": { + "ref": "checkout:weight-loading-optimization.llama-loading-readset", + "revision": "sha256:6cda6bd15fd3126648e6d2cb06ae6af8d738830d2d41940cdabafdbfb7e0a1ea" + } + }, + "routes": { + "navigation": { + "layer": "L0", + "required": [ + "navigation" + ] + }, + "decision": { + "layer": "L1", + "required": [ + "decision" + ] + }, + "procedure": { + "layer": "L2", + "required": [ + "procedure" + ] + }, + "originals": { + "layer": "L3", + "required": [ + "original", + "deepseek-expert-cache-oracles", + "deepseek-expert-cache-source", + "fastsafetensors-transfer-readset", + "flare-preparation-boundary", + "llama-loading-readset" + ] + } + } + } + }, + "directory_resources": { + "playbooks/optimization/weight-loading-optimization/SKILL.md": "original", + "playbooks/optimization/weight-loading-optimization/references/deepseek-expert-cache-oracles.md": "deepseek-expert-cache-oracles", + "playbooks/optimization/weight-loading-optimization/references/deepseek-expert-cache-source.json": "deepseek-expert-cache-source", + "playbooks/optimization/weight-loading-optimization/references/fastsafetensors-transfer-readset.md": "fastsafetensors-transfer-readset", + "playbooks/optimization/weight-loading-optimization/references/flare-preparation-boundary.md": "flare-preparation-boundary", + "playbooks/optimization/weight-loading-optimization/references/llama-loading-readset.md": "llama-loading-readset" + } +} diff --git a/tests/knowledge/test_atomic_optimization_playbooks.py b/tests/knowledge/test_atomic_optimization_playbooks.py new file mode 100644 index 000000000..aa7533de9 --- /dev/null +++ b/tests/knowledge/test_atomic_optimization_playbooks.py @@ -0,0 +1,172 @@ +"""Replay the video diffusion and weight loading Playbooks from the v0.3.4 release.""" + +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 + +VIDEO = "checkout:video-diffusion-optimization" +WEIGHTS = "checkout:weight-loading-optimization" +METADATA_SHA256 = { + VIDEO: "a6414ae5a6c3e0d87f88ad3d81198b3cf0f41bea156430daee9026b18f7ad5eb", + WEIGHTS: "605fc2ccbbf5124b570d323e97dac5f7e0b89f0827cffc139cbb5d78acd6b3bd", +} +RELEASE = json.loads((FIXTURES / "playbook-domain-v0.3.4.json").read_bytes())["refs"] +LIBRARY = "src/inferrsi/knowledge/data/skill_library/" + + +@pytest.fixture(scope="module") +def installed(tmp_path_factory): + root = tmp_path_factory.mktemp("optimization") + author = make_author_root(root) + release = root / "release" + shutil.copytree(RELEASE_ROOT, release) + for ref in (VIDEO, WEIGHTS): + composition = ATOMS.parent / "compositions" / (ref.removeprefix("checkout:") + ".json") + shutil.copyfile(composition, author / "compositions" / composition.name) + spec = json.loads(composition.read_bytes()) + bindings = spec["directory_resources"] + assert bindings.keys() == RELEASE[ref]["required_resources"].keys() + nodes = spec["metadata"]["composition"]["nodes"] + for logical, node in bindings.items(): + descriptor = ATOMS / (nodes[node]["ref"].removeprefix("checkout:") + ".json") + shutil.copyfile(descriptor, author / "atoms" / descriptor.name) + (resource,) = json.loads(descriptor.read_bytes())["content"].values() + raw = (ATOMS / resource["path"]).read_bytes() + assert digest(raw) == RELEASE[ref]["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) + + +@pytest.mark.parametrize("ref", [VIDEO, WEIGHTS]) +def test_released_directory_and_all_four_layers(installed, ref): + old = RELEASE[ref] + _, bundle = installed.read_resolved(ref, revision=installed.catalog[ref]["revision"]) + assert bundle.dependencies == old["dependencies"] == {} + assert bundle.view()["resources"] == old["required_resources"] + metadata = dict(bundle.metadata) + metadata.pop("composition") + metadata["sources"] = metadata["sources"][1:] + assert digest(canonical(metadata)) == METADATA_SHA256[ref] + entry = old["entrypoint"] + layers = {} + for level in ("L0", "L1", "L2", "L3"): + result = select(installed, ref, level, 1_000_000) + assert result.receipt["status"] == "delivered" + size = sum(map(len, result.bodies)) + assert 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=old["revision"]), "unavailable_revision" + ) + for item, body in zip(result.receipt["delivered"], result.bodies, strict=True): + lo, hi = item["source_byte_range"] + path = item["source_path"].removeprefix(LIBRARY) + assert bundle.content[path][lo:hi] == body + assert ( + item["source"]["commit"] == RELEASE_COMMIT and digest(body) == item["source_sha256"] + ) + assert item["source_range_verification"] == "verified_at_build" + for denied in {ref, *(item["ref"] for item in result.receipt["delivered"])}: + failure = select(installed, ref, level, size, permits=lambda pin, op: pin.ref != denied) + assert_empty(failure, "permission_denied") + layers[level] = result.bodies + assert bundle.content[entry].startswith(layers["L0"][0]) + (decision,) = layers["L1"] + _, fields = _skill_search_source(decision.decode()) + card = DecisionSource(ref, old["revision"], "skill", entry, entry, fields).project()["card"] + assert card["status"] == old["status"] == "partial" + assert card["missing_fields"] == old["missing_fields"] + assert (len(canonical(card)), digest(canonical(card))) == ( + old["card_bytes"], + old["card_sha256"], + ) + assert layers["L2"][0] == decision and b"".join(layers["L2"]) == bundle.content[entry] + assert layers["L3"] == tuple(bundle.content[path] for path in sorted(bundle.content)) + + +@pytest.mark.parametrize(("ref", "external_links"), [(VIDEO, 2), (WEIGHTS, 3)]) +def test_navigation_does_not_grant_target_content(installed, ref, external_links): + old = RELEASE[ref] + _, bundle = installed.read_resolved(ref, revision=installed.catalog[ref]["revision"]) + links = tuple(old["relative_guide_links"].values()) + assert sum(not link["in_directory"] for link in links) == external_links + for link in links: + assert (link["path"] in bundle.content) == link["in_directory"] + assert ref not in installed.skills.values() + + +def test_weight_reference_credits_stay_with_their_source(installed): + _, guide = installed.read_resolved(WEIGHTS, revision=installed.catalog[WEIGHTS]["revision"]) + credits = {row["readset"]: row for row in guide.metadata["attribution"]} + upstreams = {row["readset"]: row for row in guide.metadata["sources"][1:]} + assert len(credits) == len(upstreams) == 4 + nodes = guide.metadata["composition"]["nodes"] + for path in sorted(guide.content.keys() - {guide.metadata["entrypoint"]}): + leaf = PurePosixPath(path) + node = nodes[leaf.stem] + _, atom = installed.read_resolved(node["ref"], revision=node["revision"]) + readset = "references/" + leaf.name + if leaf.name == "deepseek-expert-cache-source.json": + readset = "references/deepseek-expert-cache-oracles.md" + assert atom.metadata["attribution"] == [credits[readset]] + assert atom.metadata["sources"][1:] == [upstreams[readset]] + assert credits[readset]["commit"] == upstreams[readset]["commit"] + denied = select( + installed, + WEIGHTS, + "L3", + 1_000_000, + operations={"redistribute"}, + permits=lambda pin, op: (pin.ref, op) != (node["ref"], "redistribute"), + ) + assert_empty(denied, "permission_denied") + + +def test_video_evaluator_accepts_the_delivered_template_and_reports_invalid_json( + installed, tmp_path +): + delivery = select(installed, VIDEO, "L3", 1_000_000) + bodies = { + PurePosixPath(row["source_path"]).name: body + for row, body in zip(delivery.receipt["delivered"], delivery.bodies, strict=True) + } + script = tmp_path / "evaluate_target.py" + script.write_bytes(bodies["evaluate_target.py"]) + for payload, code, verdict in ( + (bodies["campaign.template.json"], 0, "PASS"), + (b"{", 2, "INVALID"), + ): + call = subprocess.run( + [sys.executable, "-I", str(script), "-"], input=payload, capture_output=True + ) + assert call.returncode == code and call.stderr == b"" + assert json.loads(call.stdout)["verdict"] == verdict