From f07575ff6d34349c560a2c502cd8bedfe18263b0 Mon Sep 17 00:00:00 2001 From: dongxinwen Date: Fri, 27 Nov 2026 08:21:57 +0800 Subject: [PATCH 1/2] Preserve training resource budgets, source rights and deep install paths Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (implementation) Signed-off-by: dongxinwen --- src/inferrsi/knowledge/atomic_build.py | 17 +- src/inferrsi/knowledge/atomic_generation.py | 16 +- .../playbooks/training-resource-budget.md | 177 ++++++++++++++++++ .../references/mindspeed-historical.md | 112 +++++++++++ .../references/mindspeed-source-readset.md | 55 ++++++ .../papers-20261015/INTEGRATION_NOTES.md | 60 ++++++ .../cases/paper-grounded-cases.md | 51 +++++ .../knowledge/offload-delta.md | 15 ++ .../notes/training-memory-scheduling.md | 115 ++++++++++++ .../references/source-readset.md | 98 ++++++++++ .../references/sources.md | 61 ++++++ .../references/stas-decision-notes.md | 41 ++++ ...ing-resource-budget.integration-notes.json | 75 ++++++++ ...-resource-budget.mindspeed-historical.json | 75 ++++++++ ...ource-budget.mindspeed-source-readset.json | 75 ++++++++ ...raining-resource-budget.offload-delta.json | 75 ++++++++ .../training-resource-budget.original.json | 104 ++++++++++ ...-resource-budget.paper-grounded-cases.json | 75 ++++++++ ...aining-resource-budget.source-readset.json | 75 ++++++++ .../training-resource-budget.sources.json | 75 ++++++++ ...g-resource-budget.stas-decision-notes.json | 94 ++++++++++ ...rce-budget.training-memory-scheduling.json | 75 ++++++++ .../training-resource-budget.json | 176 +++++++++++++++++ .../knowledge/test_atomic_training_budget.py | 118 ++++++++++++ 24 files changed, 1905 insertions(+), 5 deletions(-) create mode 100644 src/inferrsi/knowledge/atoms/playbooks/training-resource-budget.md create mode 100644 src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/mindspeed-historical.md create mode 100644 src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/mindspeed-source-readset.md create mode 100644 src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/papers-20261015/INTEGRATION_NOTES.md create mode 100644 src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/papers-20261015/cases/paper-grounded-cases.md create mode 100644 src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/papers-20261015/knowledge/offload-delta.md create mode 100644 src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/papers-20261015/notes/training-memory-scheduling.md create mode 100644 src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/papers-20261015/references/source-readset.md create mode 100644 src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/sources.md create mode 100644 src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/stas-decision-notes.md create mode 100644 src/inferrsi/knowledge/atoms/training-resource-budget.integration-notes.json create mode 100644 src/inferrsi/knowledge/atoms/training-resource-budget.mindspeed-historical.json create mode 100644 src/inferrsi/knowledge/atoms/training-resource-budget.mindspeed-source-readset.json create mode 100644 src/inferrsi/knowledge/atoms/training-resource-budget.offload-delta.json create mode 100644 src/inferrsi/knowledge/atoms/training-resource-budget.original.json create mode 100644 src/inferrsi/knowledge/atoms/training-resource-budget.paper-grounded-cases.json create mode 100644 src/inferrsi/knowledge/atoms/training-resource-budget.source-readset.json create mode 100644 src/inferrsi/knowledge/atoms/training-resource-budget.sources.json create mode 100644 src/inferrsi/knowledge/atoms/training-resource-budget.stas-decision-notes.json create mode 100644 src/inferrsi/knowledge/atoms/training-resource-budget.training-memory-scheduling.json create mode 100644 src/inferrsi/knowledge/compositions/training-resource-budget.json create mode 100644 tests/knowledge/test_atomic_training_budget.py diff --git a/src/inferrsi/knowledge/atomic_build.py b/src/inferrsi/knowledge/atomic_build.py index 5b5e8be97..243da9298 100644 --- a/src/inferrsi/knowledge/atomic_build.py +++ b/src/inferrsi/knowledge/atomic_build.py @@ -9,7 +9,15 @@ from tempfile import TemporaryDirectory from .atomic_composition import AtomPin, applies, select_routes -from .atomic_generation import FORMAT, PUBLIC_TASKS, SEAL, InstalledGeneration, digest, owned_path +from .atomic_generation import ( + FORMAT, + PUBLIC_TASKS, + SEAL, + InstalledGeneration, + digest, + filesystem_root, + owned_path, +) from .atomic_json import matches_span, member_spans from .atomic_reader import atom_material, permits_operations from .atomic_skill_directory import directory_content, export_directory_skill, skill_spans @@ -378,13 +386,14 @@ def _prepare(source: Path, permits: Callable[[AtomPin, str], bool], roots: Mappi def build_generation(source: Path, target: Path, *, permits: Callable[[AtomPin, str], bool], source_roots: Mapping[str, Path] | None = None) -> str: """Stage and verify a complete new generation; repeat installs must have identical bytes.""" - source = Path(source).resolve(strict=True) - target = Path(target).absolute() + source = filesystem_root(source).resolve(strict=True) + target = filesystem_root(target) if target.is_symlink() or target.resolve() != target: raise ValueError("Generation target must be a physical directory") if target.is_relative_to(source) or source.is_relative_to(target): raise ValueError("Separate the authored and installed generation roots") - roots = {key: Path(path).resolve(strict=True) for key, path in (source_roots or {}).items()} + roots = {key: filesystem_root(path).resolve(strict=True) + for key, path in (source_roots or {}).items()} generation, files = _prepare(source, permits, roots) if target.exists(): return InstalledGeneration(target, expected=generation).generation diff --git a/src/inferrsi/knowledge/atomic_generation.py b/src/inferrsi/knowledge/atomic_generation.py index d840b6b4e..0bd08f20c 100644 --- a/src/inferrsi/knowledge/atomic_generation.py +++ b/src/inferrsi/knowledge/atomic_generation.py @@ -4,6 +4,7 @@ import hashlib import json +import os from pathlib import Path, PurePosixPath from .atomic_composition import AtomPin @@ -21,6 +22,19 @@ def digest(data: bytes) -> str: return hashlib.sha256(data).hexdigest() +def filesystem_root(root: Path) -> Path: + """Use absolute filesystem paths that accommodate deep installed resources on Windows.""" + absolute = Path(root).absolute() + if os.name != "nt": + return absolute + name = str(absolute) + if name.startswith(("\\\\?\\", "\\\\.\\")): + return absolute + if name.startswith("\\\\"): + return Path("\\\\?\\UNC\\" + name[2:]) + return Path("\\\\?\\" + name) + + def directory_skill_path(metadata: dict, name: str) -> str: entry = PurePosixPath(safe_path(metadata["entrypoint"])) relative = PurePosixPath(safe_path(name)).relative_to(entry.parent) @@ -55,7 +69,7 @@ class InstalledGeneration: """An internally consistent snapshot, optionally pinned by its caller's release record.""" def __init__(self, root: Path, *, expected: str | None = None): - root = Path(root).resolve(strict=True) + root = filesystem_root(root).resolve(strict=True) seal = json.loads(owned_path(root, SEAL).read_bytes()) generation = seal.pop("generation") if seal.get("format") != FORMAT or generation != "sha256:" + digest(_json(seal)): diff --git a/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget.md b/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget.md new file mode 100644 index 000000000..b31c7ee1c --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget.md @@ -0,0 +1,177 @@ +--- +name: training-resource-budget +description: 'Choose training offload and resource-budget changes using pinned DeepSpeed configuration, attributed expert diagnosis and a historical MindSpeed case. Balance accelerator capacity, CPU work, pinned RAM and local storage; keep host/device transfer exposure distinct from collective network bottlenecks. + + ' +metadata: + inferrsi: | + { + "tags": [ + "training", + "offload", + "resource-budget", + "memory", + "cpu", + "numa" + ], + "status": "candidate", + "profile": "local-skill-v1", + "schema_version": 1, + "kind": "skill", + "origin": [ + "external" + ], + "empirical_validation": "not_run", + "applicability": { + "scope": "Choosing training offload and resource-budget changes from pinned DeepSpeed configuration, attributed expert diagnosis and a historical MindSpeed case, balancing accelerator capacity, CPU work, pinned RAM and local storage while keeping host/device transfer exposure distinct from collective network bottlenecks", + "prerequisites": "The source boundaries are read; garbage-collection or affinity changes, privileged memlock changes and delayed parameter updates each need separate approval, and the skill authorizes no newest-wheel installation, scheduler-priority change, benchmark or failure injection; historical MindSpeed reuse requires compatible allocator symbols, tracked swappable storage, sufficient host capacity and verified device/NUMA/CPU mapping, not merely the presence of npu-smi and lspci", + "input_contract": "State attributed to parameters, optimizer state, gradients or activations with its current memory tier, lifetime and next consumer; whether the failure is allocation capacity or throughput; a per-host budget for input buffers, checkpoint snapshots, offloaded state, OS cache and CPU workers with the actual ranks sharing the host; the host/device link recorded apart from collective traffic; the exact source version and enabled execution mode", + "produced_artifact": "A candidate decision record per proposal: the observed limiting interval and owning state or resource, source version and execution mode, capacity released and resources consumed with units and uncertainty, overlap readiness and mutation boundaries with expected contention, and the fixed-workload step and correctness evidence required for later validation", + "failure_modes": [ + "A change that lets the model fit is presented as a speedup, although it can slow each step", + "A tensor copied to CPU is taken as an InfiniBand/RoCE bottleneck, or CPU/NVMe offload is counted as network evidence", + "Parameter max_in_cpu is read as a byte or total-host-memory cap instead of an element count", + "NVMe optimizer placement is assumed to remove CPU optimizer demand", + "The parameter buffer-pool count is transplanted to the optimizer, or all optimizers are assumed to hold identical states", + "Configuration presence or schema documentation is taken as evidence that a knob or overlap actually ran", + "Ordinary overlap is taken as permission for delayed, stale parameter updates" + ], + "refusal_point": "Claims no hardware validation, measured gain or current NPU compatibility, keeps source support and extracted coverage separate from measured improvement, and does not reuse the MindSpeed headline gain; historical source observations do not establish current-stack compatibility, whole-model correctness or measured benefit" + }, + "recommendations": [ + "Attribute the state and separate a capacity failure from a throughput bottleneck before choosing an offload surface.", + "Verify the consumer of buffer_size before calculating bytes or tuning it, and measure the executing path before claiming a knob ran.", + "Compare the whole step's critical path, not host capacity alone.", + "Use plan-activation-residency, choose-parallel-training-plan and assess-split-backward-schedule for live-range, parallel-plan and backward-ordering questions." + ], + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Original typed source inventory is not normalized; retain source identities and limits in the procedure/readsets." + ], + "provenance_readsets": [ + "references/mindspeed-historical.md", + "references/mindspeed-source-readset.md", + "references/papers-20261015/cases/paper-grounded-cases.md", + "references/papers-20261015/INTEGRATION_NOTES.md", + "references/papers-20261015/knowledge/offload-delta.md", + "references/papers-20261015/notes/training-memory-scheduling.md", + "references/papers-20261015/references/source-readset.md", + "references/sources.md", + "references/stas-decision-notes.md" + ], + "consumption_mode": "packaged" + } +--- + +# Training Cross-Resource Budget Decisions + +Status: candidate. No hardware validation, measured gain or current NPU +compatibility claim. [Source boundaries](references/sources.md) identify exactly +what was inspected; no checkpoint implementations are mined by this skill. + +## Start with ownership and one bottleneck + +Attribute state to parameters, optimizer state, gradients or activations; +record its current memory tier, lifetime and next consumer. Distinguish an +allocation-capacity failure from a throughput bottleneck. A change that enables +a model to fit can still slow each training step. + +Keep a per-host budget for input buffers, checkpoint snapshots, offloaded state, +OS cache and CPU workers. Count the actual ranks sharing that host. Record the +host/device link separately from inter-device/inter-node collective traffic. +A tensor copied to CPU does not establish an InfiniBand/RoCE bottleneck. + +SearchSpace: Accelerator and RAM / Host → Diagnose, Configure, Optimize; +SSD / Storage → Configure, Optimize (DeepSpeed NVMe state); OS / System → +Diagnose, Configure (CPU share/locality/garbage-collection attribution). +Network → Observe, Diagnose, Verify only through the scoped expert collective +measurement principles, not through CPU/NVMe offload itself. + +## CR1 — DeepSpeed offload decision surfaces + +| Surface | Inspected contract | Decision consequence | +|---|---|---| +| Parameter offload `device=cpu/nvme` | ZeRO stage 3 only | Establish parameter state residency before spending buffers or CPU RAM | +| Optimizer offload `device=cpu/nvme` | Stages 1/2/3; computation remains on CPU for either target | NVMe placement does not remove CPU optimizer demand | +| Parameter `max_in_cpu` | Parameter **elements** retained in CPU when NVMe is enabled | Convert using actual dtype/storage; this is not a byte or total-host-memory cap | +| Parameter `buffer_count`, `buffer_size` | NVMe buffer-pool count and size | The approved config/doc excerpt does not explicitly define `buffer_size` units; verify its consumer before calculating bytes or tuning it | +| Optimizer `buffer_count` | At least the number of optimizer states per parameter; source illustrates Adam's four | Do not transplant the parameter-pool count or assume all optimizers have identical states | +| `pin_memory` | Defaults True at this pin; page-locked CPU memory supports async transfers/overlap | Budget resident memory and existing memlock allowance; no privileged limit change authorized | +| `pipeline_read` / `pipeline_write` | Next-tile read / previous-tile write overlap with current optimizer tile compute | Applicable to tiled ZeRO-Infinity execution; configuration presence does not prove actual overlap | +| `ratio` | Fraction in [0,1] for CPU Adam, stage 3 only | Not a general placement ratio for parameters or activations | +| `super_offload`, `cpuadam_cores_perc` | Superchip CPU offload; core fraction valid with stage 3 plus `super_offload=True` | Not a universal CPU throttle or generic recommendation on every host | +| `fast_init` | NVMe optimizer initialization | Startup cost and steady-state step time have different denominators | + +A justified overlap proposal needs evidence that compute can hide the relevant +read/write segment, sufficient CPU/pinned-RAM/storage capacity and unchanged +state semantics. Measure the executing path before claiming a knob ran. The +config schema and live documentation are not dispatch/performance evidence. + +## CR6 — Attributed expert diagnosis + +Read [the scoped Stas Bekman note](references/stas-decision-notes.md) for +MFU/HFU denominator checks, transient-versus-sustained compute, collective +measurement semantics, NUMA locality and garbage-collection stragglers. This +note explicitly retains CC BY-SA 4.0 attribution and share-alike conditions; +no upstream runbook commands or automatic-update instructions are adopted. + +Use these principles to form a hypothesis, not to import a platform tuning +constant. Garbage-collection or affinity changes require separate task +approval and memory/correctness evidence; this extraction changes neither. + +## CR5 — Historical NPU case + +[MindSpeed adaptive memory](references/mindspeed-historical.md) illustrates +spending spare NPU memory versus CPU swapping/recomputation. Preserve the +`core_r0.8.0` exclusions and distinguish its validation assertions from the +separate feature-selection guard. The [pinned source readset](references/mindspeed-source-readset.md) +recovers the historical full revision and license, allocator-to-swap callback +and 910A/910B affinity branch. Check compatible allocator symbols, tracked +swappable storage, host capacity and actual device/NUMA/CPU mapping before +separately authorized reuse; `npu-smi` and `lspci` presence alone is insufficient. +One reported comparison changes layer count; its headline gain is not reused. +Current-stack compatibility, whole-model correctness and measured benefit remain +unverified. These historical source observations do not establish current Ascend +support. + +## Paper-derived training decisions + +[ZeRO-Offload ownership and semantics](references/papers-20261015/knowledge/offload-delta.md) +extends the configuration evidence above with CPU optimizer state/compute +colocation, shard ownership and tiled update/return costs. Compare the whole +step's critical path, not host capacity alone. Delayed parameter updates change +training semantics and require explicit approval and quality evidence; ordinary +overlap does not imply permission for staleness. + +Use [activation residency](../plan-activation-residency/SKILL.md) for live-range, +address-packing and rematerialization choices; +[parallel training plans](../choose-parallel-training-plan/SKILL.md) for stage, +mesh and sharding choices; and +[split backward](../assess-split-backward-schedule/SKILL.md) for input-gradient +versus weight-gradient ordering and optimizer post-validation. These are distinct +contracts: activation checkpoints are not restart snapshots, Alpa's conditional +plans are not unrestricted global optima, and Zero Bubble's rollback preserves +semantics rather than authorizing ZeRO-Offload's stale updates. + +The [mechanism comparison](references/papers-20261015/notes/training-memory-scheduling.md), +[readset](references/papers-20261015/references/source-readset.md) and +[hypothetical cases](references/papers-20261015/cases/paper-grounded-cases.md) +retain resource costs, counter-signals and unresolved table discrepancies. +Paper versions are separate from the DeepSpeed implementation pin. No current +runtime, NPU support or measured application outcome follows from these notes. + +## Candidate decision record + +For each proposal, retain: + +1. The observed limiting interval and owning state/resource. +2. The exact source version and enabled execution mode. +3. Capacity released and resources consumed, with units and uncertainty. +4. Overlap readiness/mutation boundaries and expected contention with input, + checkpoint and network activity. +5. Fixed-workload training step/throughput and correctness evidence required + for later validation; initialization and auxiliary metrics separately. + +No broad source expansion, newest-wheel installation, scheduler-priority +changes, benchmarks or failure injection follow from this skill. Source +support and extracted coverage remain separate from measured improvement. diff --git a/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/mindspeed-historical.md b/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/mindspeed-historical.md new file mode 100644 index 000000000..70bc0da5f --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/mindspeed-historical.md @@ -0,0 +1,112 @@ +# Historical MindSpeed adaptive-memory case + +Reference entry CR5. Initial documentation inspection: 2026-10-15. Historical +source follow-up: 2026-10-30. This remains a source-derived candidate with no +current runtime or compatibility qualification. + +## Provenance and permitted reuse + +[Original document](https://gitcode.com/Ascend/MindSpeed/blob/core_r0.8.0/docs/features/adaptive-memory.md), +branch `core_r0.8.0`; the 2026-10-15 inspection recorded page history +`53193db8`, 2025-06-04. Full revision, license and implementation were unresolved +at that inspection. Retrieved HTML SHA-256: +`773d702b932534f96d037c07156604d7dd9e4c3b82f4a0a6e6e8ff70e5365eef`. +The document body was readable then; its named implementation was not retrieved. + +The 2026-10-30 follow-up resolved the original page's commit link to +[`53193db8bf5def407c4041a9beb3f4c9e9773daf`](https://gitcode.com/Ascend/MindSpeed/commit/53193db8bf5def407c4041a9beb3f4c9e9773daf). +The official Ascend/MindSpeed [GitHub commit](https://github.com/Ascend/MindSpeed/commit/53193db8bf5def407c4041a9beb3f4c9e9773daf) +has the same identity, the `!2378` README-update message and commit timestamp +`2025-06-04T04:43:14Z`. The pinned document and bounded implementation were read +at that revision; the [source readset](mindspeed-source-readset.md) distinguishes +those new observations from the original HTML snapshot. The snapshot hash is +retained as historical evidence, not claimed to hash the fetched Markdown. + +Historical license evidence is the same pin's [root LICENSE](https://github.com/Ascend/MindSpeed/blob/53193db8bf5def407c4041a9beb3f4c9e9773daf/LICENSE): +BSD-3-Clause terms apply by default unless otherwise noted, with separate +third-party terms for identified files. The adaptive-memory document has no +separate license notice; `docs/LICENSE` is absent at this pin. The README's MIT +badge does not replace the root terms, and a later branch's documentation license +does not resolve historical rights. Attribution remains Ascend/MindSpeed, with +Bytedance, Huawei and NVIDIA copyright notices retained in the linked license. +This note independently paraphrases mechanisms; no upstream code or prose is +copied or adapted into an executable helper. + +## Incremental decision + +The documented trigger is **unused NPU memory under full recomputation**. +The document describes lossless tensor swapping, strategy generation/search, +SwapManager and allocator integration to choose how much state to retain versus +move to CPU. The document describes intercepting out-of-memory conditions via +PTA's `NPUPluggableAllocator`, allowing SwapManager to intervene. This is a +source design claim. The bounded source observations below confirm the allocator +callback path, not the complete search algorithm or whole-model losslessness. + +Derived decision: assess retained activation capacity, recomputation work and +NPU↔CPU transfer exposure together. Less recomputation can spend host RAM and +host/device bandwidth. This does not demonstrate a network optimization, nor +a guarantee that OOM interception makes arbitrary workloads safe. + +## Historical configuration boundary + +| Surface documented at this branch | Constraint | +|---|---| +| `--adaptive-memory-optimization` | Historical opt-in flag, not a recommendation for current releases | +| Full recomputation; adaptive selective recomputation; `swap-attention`; `recompute-in-bubble` | Documented incompatible combinations; do not combine policies merely because their memory objectives overlap | +| Memory-fragmentation optimization | Both modify PyTorch memory management; document says an assertion rejects simultaneous enablement | +| CPU affinity | Document names `npu-smi` and `lspci`; the source has additional topology/tool and SoC conditions below | +| Custom `torch.autograd.Function` integration | The document names `adapt_mem_func_wrapper`; its pinned implementation accepts a `torch.autograd.Function` subclass and selects profiling, recomputation, swap or the original `.apply` by phase/action | + +## Pinned implementation decisions + +Use the [exact paths and line ranges](mindspeed-source-readset.md) for these +observations, all inspected 2026-10-30 at the historical revision above. + +1. **Check effective selection before allocator assumptions.** `arguments.py` + rejects adaptive recomputation, configured `recompute_granularity` or + `recompute_method`, `recompute_activation_function`, `swap_attention`, + `recompute_in_bubble`, memory fragmentation and `ampipe_degree > 1`. + Separately, `megatron_adaptor.py` only installs the adaptive-memory wrappers + and allocator when the flag is true and adaptive recomputation, fragmentation, + swap-attention and `smart_swap` are false. The `smart_swap` exclusion is a + dispatch guard, not the same validation assertion. A present flag alone does + not establish that this policy was selected. +2. **Treat the allocator as a process runtime dependency.** That dispatch branch + invokes `change_allocator()`, whose builder loads the historical C++ extension. + It supplies `my_malloc`/`my_free` to TorchNPU's `NPUPluggableAllocator`, changes + the current allocator and installs init/reset/stat callbacks. The builder + depends on PyTorch/TorchNPU headers and links `torch_npu`; API names alone do + not establish compatibility with another wheel or CANN stack. +3. **Bound OOM rescue to its captured state.** After ordinary allocation/cache + attempts fail, the C++ allocator calls `common.swap_out_by_size(size)` and + retries. `common.py` routes to the adaptive-memory manager under this flag. + Its saved-tensor hooks track eligible tensors; rescue moves shared storage + through pinned CPU memory and restores it for unpack. The manager returns + false when no tracked tensor is eligible, and the allocator retains an OOM + error path. This mechanism does not promise recovery for arbitrary allocations + or unlimited host capacity. Charge shared storage once and account for its + return before the backward consumer, rather than counting tensor views as + independent savings. +4. **Check the historical affinity branch and topology.** Setup calls `bind_cpus` + only when `acl.get_soc_name()` contains `910A` or `910B`. The helper queries + `npu-smi`, `lspci` and `lscpu`, then sets process affinity through `psutil`. + It derives NUMA CPU ranges from `lscpu`, uses a contiguous device-ID range, + and assigns CPUs per device from a historical `ratio=0.5` default or + `CPU_BINDING_NUM`. These are source assumptions, not a recommended CPU share. + Before separate authorized reuse, reconcile visible device numbering, parsed + topology and granted CPU affinity; command presence alone is insufficient. + Reading this case authorizes no package installation or affinity change. + +## Evidence quality + +The document reports cropped GPT-175B experiments on eight NPUs. One comparison +uses `NL=8` for adaptive memory and `NL=3` for full recomputation. Its headline +percentage is not a controlled fixed-workload gain and is deliberately not +carried into coverage or performance claims. Other tables remain author reports; +no raw traces, correctness outputs or matched reruns were inspected. + +Still open: current torch/TorchNPU/CANN/MindSpeed compatibility, complete strategy +search and cache behavior, actual transfer exposure, whole-model correctness and +measured end-to-end benefit. The historical full revision and default license +terms are now recoverable; the selected allocator, wrapper and affinity paths +are source observations only. No hardware run or failure injection was performed. diff --git a/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/mindspeed-source-readset.md b/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/mindspeed-source-readset.md new file mode 100644 index 000000000..4ddf367ab --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/mindspeed-source-readset.md @@ -0,0 +1,55 @@ +# MindSpeed historical source readset + +Source: [Ascend/MindSpeed](https://github.com/Ascend/MindSpeed), historical +`core_r0.8.0` document commit +`53193db8bf5def407c4041a9beb3f4c9e9773daf`. Inspected 2026-10-30. +The [historical case](mindspeed-historical.md) retains the separate 2026-10-15 +documentation inspection and original HTML hash. + +## Identity and rights + +- The [original GitCode page](https://gitcode.com/Ascend/MindSpeed/blob/core_r0.8.0/docs/features/adaptive-memory.md) + links its abbreviated history entry to the [full commit](https://gitcode.com/Ascend/MindSpeed/commit/53193db8bf5def407c4041a9beb3f4c9e9773daf). + The official [GitHub commit API](https://api.github.com/repos/Ascend/MindSpeed/commits/53193db8bf5def407c4041a9beb3f4c9e9773daf) + reports that SHA, `!2378` README-update message and timestamp + `2025-06-04T04:43:14Z`. The branch name remains a moving reference; every source + link below uses the recovered full revision. +- [Root LICENSE, lines 1–34](https://github.com/Ascend/MindSpeed/blob/53193db8bf5def407c4041a9beb3f4c9e9773daf/LICENSE#L1-L34): + default BSD-3-Clause terms unless otherwise noted, including Bytedance, Huawei + and NVIDIA attribution. The rest of the file supplies identified third-party + exceptions; do not relabel the entire repository with a single guessed license. + No separate license notice appears in the selected adaptive-memory document. + The [historical `docs/LICENSE` path](https://github.com/Ascend/MindSpeed/blob/53193db8bf5def407c4041a9beb3f4c9e9773daf/docs/LICENSE) + returned 404. No later license is substituted for this pin. +- [README](https://github.com/Ascend/MindSpeed/blob/53193db8bf5def407c4041a9beb3f4c9e9773daf/README.md#L901-L917), + version table only: historical Core/PyTorch and in-development stack entries, + not a complete frozen runtime stack. Its MIT badge near the beginning is not + the inspected root license text. [Package version](https://github.com/Ascend/MindSpeed/blob/53193db8bf5def407c4041a9beb3f4c9e9773daf/setup.py#L11-L16) + is `0.8.0`; `setup.py` was read, not executed. + +## Bounded implementation reads + +Paths are relative to that repository. Listed sections support the stated +decision only; surrounding framework internals and the full solver are not +audited. + +| Pinned source | Inspected section | Observation used by the owner | +|---|---|---| +| [docs/features/adaptive-memory.md](https://github.com/Ascend/MindSpeed/blob/53193db8bf5def407c4041a9beb3f4c9e9773daf/docs/features/adaptive-memory.md) | Whole short document | Trigger, mechanism attribution, exclusions, wrapper requirement, affinity prerequisites and mismatched-layer performance table | +| [mindspeed/arguments.py](https://github.com/Ascend/MindSpeed/blob/53193db8bf5def407c4041a9beb3f4c9e9773daf/mindspeed/arguments.py#L353-L354) | Flag 353–354; [validation 839–849](https://github.com/Ascend/MindSpeed/blob/53193db8bf5def407c4041a9beb3f4c9e9773daf/mindspeed/arguments.py#L839-L849) | Default-off flag; explicit rejection of conflicting configurations, including ampipe and activation recomputation | +| [mindspeed/megatron_adaptor.py](https://github.com/Ascend/MindSpeed/blob/53193db8bf5def407c4041a9beb3f4c9e9773daf/mindspeed/megatron_adaptor.py#L639-L656) | 639–656; adaptation call 1077 | Effective selection guard, including `smart_swap`; allowed layer and setup-wrapper registration; allocator replacement | +| [mindspeed/core/memory/adaptive_recomputing/pluggable_allocator_adpator.py](https://github.com/Ascend/MindSpeed/blob/53193db8bf5def407c4041a9beb3f4c9e9773daf/mindspeed/core/memory/adaptive_recomputing/pluggable_allocator_adpator.py) | Whole 24-line adapter | Shared historical allocator builder, allocation/free symbols and current-allocator/stat callback setup | +| [mindspeed/op_builder/adaptive_recomputing_builder.py](https://github.com/Ascend/MindSpeed/blob/53193db8bf5def407c4041a9beb3f4c9e9773daf/mindspeed/op_builder/adaptive_recomputing_builder.py) | Whole short builder; `op_builder/__init__.py` import mapping | Extension source, PyTorch/TorchNPU includes and `torch_npu` link dependency | +| [mindspeed/ops/csrc/pluggable_allocator/adaptive_recomputing/NpuCachingCustomAllocator.cpp](https://github.com/Ascend/MindSpeed/blob/53193db8bf5def407c4041a9beb3f4c9e9773daf/mindspeed/ops/csrc/pluggable_allocator/adaptive_recomputing/NpuCachingCustomAllocator.cpp#L44-L53) | Allocation forwarding 44–53 | Exported allocator reaches the device allocator defined in the header | +| [mindspeed/ops/csrc/pluggable_allocator/adaptive_recomputing/NpuCachingCustomAllocator.h](https://github.com/Ascend/MindSpeed/blob/53193db8bf5def407c4041a9beb3f4c9e9773daf/mindspeed/ops/csrc/pluggable_allocator/adaptive_recomputing/NpuCachingCustomAllocator.h#L548-L678) | Allocation/retry/callback/OOM 548–678; exports 1572–1592 | Failed cache/allocation attempts reach Python `common.swap_out_by_size`; false ends rescue; OOM remains possible | +| [mindspeed/core/memory/common.py](https://github.com/Ascend/MindSpeed/blob/53193db8bf5def407c4041a9beb3f4c9e9773daf/mindspeed/core/memory/common.py) | Whole 11-line router | Adaptive flag selects adaptive-memory rather than adaptive-recomputation SwapManager | +| [mindspeed/core/memory/adaptive_memory/adaptive_memory_swap_manager.py](https://github.com/Ascend/MindSpeed/blob/53193db8bf5def407c4041a9beb3f4c9e9773daf/mindspeed/core/memory/adaptive_memory/adaptive_memory_swap_manager.py#L231-L378) | Copy state 25–84; eligibility 120–141; rescue pack/unpack, shared storage and selection 231–378; layer hooks 375–415 | Rescue concerns tracked eligible saved tensors; shared-storage CPU move/restore, pinned allocation and false result when none is eligible | +| [mindspeed/core/memory/adaptive_memory/adaptive_memory_opt.py](https://github.com/Ascend/MindSpeed/blob/53193db8bf5def407c4041a9beb3f4c9e9773daf/mindspeed/core/memory/adaptive_memory/adaptive_memory_opt.py#L189-L213) | Setup 189–213 | Optimizer/profiling hooks; CPU binding conditional on 910A/910B SoC; cache loader identified only | +| [mindspeed/core/memory/adaptive_memory/cpu_binder.py](https://github.com/Ascend/MindSpeed/blob/53193db8bf5def407c4041a9beb3f4c9e9773daf/mindspeed/core/memory/adaptive_memory/cpu_binder.py) | Whole 110-line helper | `npu-smi` → PCIe → `lspci` NUMA → `lscpu` CPU ranges; contiguous-device assumption, historical ratio/env selection and process-affinity mutation | +| [mindspeed/core/memory/adaptive_memory/adaptive_memory_function.py](https://github.com/Ascend/MindSpeed/blob/53193db8bf5def407c4041a9beb3f4c9e9773daf/mindspeed/core/memory/adaptive_memory/adaptive_memory_function.py#L99-L136) | Saved-tensor wrapper and action dispatch 99–136 | Explicit autograd-subclass integration; phase/action-specific profiling, swap, checkpoint or original `.apply` | + +The solver, policy cache, complete prefetch schedule, framework allocator ABI, +device kernels and model training results remain outside this bounded extraction. +The builder and binder are referenced for their prerequisites; neither is copied, +imported or executed by this skill. No current-stack or numerical qualification +follows from source inspection. diff --git a/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/papers-20261015/INTEGRATION_NOTES.md b/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/papers-20261015/INTEGRATION_NOTES.md new file mode 100644 index 000000000..69b17c8ba --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/papers-20261015/INTEGRATION_NOTES.md @@ -0,0 +1,60 @@ +> Supplier integration proposal, preserved as historical source context (2026-10-15). The local owner review and current two matrices govern acceptance; suggested follow-ups and permission statements below do not authorize work or describe the current inventory. + +# Pack C integration proposals + +Status: candidate; empirical_validation: not_run. Independent five-paper, fulltext-derived expansion. F = source facts/models/results; P = proposed operational rules. No empirical validation, install, reproduction, framework run, hardware work, InferRSI modification, matrix edit or PR has occurred. Source PDFs/text/render caches are outside this deliverable tree and are not redistributed. + +## Deliverable routes + +- [Compact mechanism notes](notes/training-memory-scheduling.md): twelve mechanism cards with objective, assumptions, variables/constraints, action, benefit/cost, evidence, limits/counter-signals and candidate rule. +- [Exact readset and metric audit](references/source-readset.md): all five version pins, actual sections/equations/figures/tables read, rendered-page checks, author-reported workload/baseline/hardware/denominator and missing evidence. +- [Offload extension](knowledge/offload-delta.md): incremental ZO1–ZO3 knowledge for the existing skill. +- [Review cases](cases/paper-grounded-cases.md): hypothetical failure/decision cases, not executed evaluations. +- [plan-activation-residency](../../../plan-activation-residency/SKILL.md), [choose-parallel-training-plan](../../../choose-parallel-training-plan/SKILL.md), [assess-split-backward-schedule](../../../assess-split-backward-schedule/SKILL.md): three candidate skills, selected by distinct decision boundaries rather than one skill per paper. + +P, grouping rationale: Checkmate and OLLA jointly inform retain/recompute/order/address choices and need one shared feasibility check. Alpa changes partition/mapping/resharding choices, so it remains separate from fixed-pipeline scheduling. Zero Bubble introduces an independent backward-order and optimizer-validation gate. ZeRO-Offload belongs in the earlier training-offload skill instead of duplicating its tensor-tier accounting. None is promoted or empirically validated. + +## Existing artifacts inspected first + +- Offload synthesis (prior archive `omnirsi-paper-intelligence-2026-10-15.zip`, semantic path `notes/offload.md`) +- Offload source audit (prior archive `omnirsi-paper-intelligence-2026-10-15.zip`, semantic path `notes/references/offload-source-notes.md`) +- Training-offload skill (prior archive `omnirsi-paper-intelligence-2026-10-15.zip`, semantic path `diagnose-training-offload/SKILL.md`) +- Training-offload references (prior archive `omnirsi-paper-intelligence-2026-10-15.zip`, semantic path `diagnose-training-offload/references/source-notes.md`) +- Previous integration notes (prior archive `omnirsi-paper-intelligence-2026-10-15.zip`, semantic path `INTEGRATION_NOTES.md`) + +These are semantic paths in the identified prior archive, not local hyperlinks or files bundled again. Resolve them to the approved repository inventory during integration. Existing ZeRO-Infinity coverage is retained: phase/class/tier budgets, prefetch/buffer pipelines, tiling, initialization and tied/external parameters. New evidence concerns CPU optimizer ownership/staleness, legal lifetime shortening, event-level rematerialization, static address packing, heterogeneous parallel plans and split-backward scheduling. + +## P: Only the two official matrix destinations + +The following are repository-relative link proposals, not local matrix edits or invented row IDs. Official paths are docs/reference-matrix.md and docs/searchspace-matrix.md. Any older matrix-path suggestion is superseded by these two official destinations. Live rows/anchors were not inspected. There is no third matrix. + +For docs/reference-matrix.md: +- Add ZeRO-Offload 2101.06840v1 → ZO1–ZO3 → offload extension and readset; mark the old next-gate lead as read only when integration is approved. +- Add Checkmate 1910.02653v3 → CM1–CM2 and OLLA 2210.12924v2 → OL1–OL2 → activation-residency skill/readset. OLLA likewise advances from the earlier unread lead after approved integration. +- Add Alpa 2201.12023v3 → AL1–AL2 → parallel-plan skill/readset. +- Add Zero Bubble 2401.10241v1 → ZB1–ZB3 → split-backward skill/readset. + +For docs/searchspace-matrix.md, propose semantic cross-links using existing taxonomy/row IDs after local reconciliation: +- Accelerator × Observe/Diagnose/Optimize/Verify: live ranges, per-event capacity, rematerialization, reserved-address packing, shard/mesh feasibility, pipeline passes and total device memory. +- RAM/host-compute evidence × Observe/Diagnose/Optimize/Verify: optimizer residency/update/copy and host-resource ownership, extending the existing offload entry. This is not an additional SSD technique. +- Communication/Network × Observe/Diagnose/Optimize/Verify only for actual inter-node reduce-scatter/allgather, cross-mesh resharding or pipeline transfers. Local GPU collectives remain Accelerator topology. H2D/D2H and same-host IPC do not become Network entries. +- Configure, where the existing matrix uses it, must point to a later separately authorized current-implementation gate. These paper plans do not prove current framework/NPU support. No generic OS/VM-tuning or persistent recovery-checkpoint rule follows from this pack. + +## Evidence boundaries that must survive integration + +- Checkmate's headline batch-capacity increase is constrained model evidence; OLLA's runtime saving is estimated over an assumed million iterations. Neither should become a measured end-to-end speed claim. +- Alpa is hierarchical and approximate in important respects: zero compute-cost simplification inside intra-op search, omitted inter-stage transfer, external microbatch count, static shapes/schedules. Do not advertise globally optimal mixed-parallel execution. +- Zero Bubble's calculated bubble rates, ideal formulas and measured throughput are distinct. Similar activation caps do not mean identical total memory. Table 6's fixed-global-batch comparison is preferable to Table 11's ambiguous/changing-batch rows. +- ZeRO-Offload DPU changes update semantics; Zero Bubble post-validation intends to preserve them through validation/rollback. Keep separate gates. +- Source inconsistencies are flagged rather than repaired: ZeRO-Offload Table 1; Alpa Wide-ResNet size rounding; Zero Bubble Table 11 microbatch labels and missing Table 9 time units. + +## Unread next-gate leads + +These are leads named in the five papers' references, not additional reviewed evidence. Stop the current batch at five papers. + +- AutoTM (ZeRO-Offload reference 8): joint tensor movement with heterogeneous memory could address transfer decisions absent from Checkmate/OLLA; no mechanism imported here. +- Capuchin (ZeRO-Offload reference 17): a possible recomputation-plus-movement comparison; not read. +- Reducing Activation Recomputation in Large Transformer Models (Zero Bubble reference list): a possible check on Transformer-specific saved-tensor assumptions; not read. +- Piper (Alpa related work): an alternate mixed-parallel search boundary; not read. + +A later gate may also review author-linked implementation at an explicit revision for compatibility. No such source inspection or validation is implied by this delivery. diff --git a/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/papers-20261015/cases/paper-grounded-cases.md b/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/papers-20261015/cases/paper-grounded-cases.md new file mode 100644 index 000000000..15449ba32 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/papers-20261015/cases/paper-grounded-cases.md @@ -0,0 +1,51 @@ +# Paper-grounded review cases + +Status: candidate; empirical_validation: not_run. All scenarios and proposed decisions below are P, hypothetical review cases. Their F evidence is historical and linked. These were not executed as tests and are not claims about an actual user workload. + +## C1. OOM with low live-byte demand but high reserved memory + +Signal: a stable graph's phase-aligned live tensor total is well below the allocator peak, and the requested large allocation cannot fit an available range. + +Decision: distinguish reserved-byte fragmentation from unavoidable live data. Consider legal address reuse after lifetime proof before buying transfer/recomputation overhead. Keep size/alignment/workspace and asynchronous overlap in the accounting. Do not assume a reserved/live difference alone proves external fragmentation; cached free blocks and unaccounted workspaces must be resolved. + +F basis: OLLA §§3.3–3.5, §5.4/Fig. 8. Its fragmentation percentage is (reserved−resident)/reserved at the reserved-memory peak, not a universal multiplier. Acceptance idea: later evidence shows the same graph's peak reserved memory falls without illegal overlapping aliases or a latency regression. Stop if shapes/lifetimes are unstable. [OL2](../notes/training-memory-scheduling.md) + +## C2. Large forward activations remain live across a nearly linear graph + +Signal: activations dominate at large batch, few independent operators can be reordered, and CPU offload would expose transfer waits. + +Decision: propose selective retain/recompute alternatives with event-level peak memory, adding recompute cost to the same critical-path ledger. Do not expect OLLA's small-batch gradient-order savings to carry over. Do not change global batch merely because more input could fit. + +F basis: OLLA §5.3 limits; Checkmate §4/Eqs. 1–9 and Fig. 5. Acceptance idea: same-model/batch/precision proposal preserves dependencies, fits worst-case memory including output-before-release, and has a justified step-time benefit versus supplied offload costs. Missing transfer/operator timing leaves the performance choice unresolved. [CM1/OL1](../notes/training-memory-scheduling.md) + +## C3. Approximate rematerialization has low objective cost but exceeds memory + +Signal: rounded retention plan has dependency-valid recomputations and a favorable FLOP estimate, yet its replayed lifetime ledger exceeds the actual budget. + +Decision: reject feasibility, regardless of closeness to an LP/ILP objective. Record dependency validity and capacity violation separately. A different margin, policy or exact incumbent may be considered on paper; a solver timeout does not establish no feasible plan exists. + +F basis: Checkmate §5.3 explicitly does not preserve capacity under rounding; Table 2 averages ratios only across feasible budgets. Acceptance idea: an actual feasible schedule/capacity proof under the chosen accounting, not a 1.06 mean-cost claim. [CM2](../notes/training-memory-scheduling.md) + +## C4. One pipeline stage is weight-heavy while earlier stages are activation-heavy + +Signal: uniform layer counts create per-rank OOM or a bottleneck despite spare memory elsewhere; the cluster has fast local links and slower inter-node links. + +Decision: compare uneven stages/mesh sizes and varying operator shard axes. Include layout conversion and in-flight activations; prefer a simple uniform fallback if the model is homogeneous or planning cannot amortize. Do not substitute weak-scaling PFLOP/s for fixed-work speed. + +F basis: Alpa §5/Eqs. 2–5, §8.3, §8.6/Fig. 12; 16-GPU Wide-ResNet uses 4/4/8-GPU stages. Acceptance idea: same global batch and total hardware, actual cross-node transfer included, all rank peaks feasible, and useful whole-step improvement. [AL1/AL2](../notes/training-memory-scheduling.md) + +## C5. Lower modeled pipeline bubbles require smaller microbatches + +Signal: a larger activation cap allows ZB-2p-like scheduling only by reducing microbatch size; small kernels lose utilization. + +Decision: compare 1F1B, capped split backward, V placement and b/2 plus 2m at fixed global batch and similar total memory. Choose useful throughput, not zero-idle theory. Do not splice Table 4's different memory budgets with Table 11's changing global batches. + +F basis: Zero Bubble §6.1/Table 6; 6.2B favors ZB-2p* over V while 28.3B's listed base b2,m96 favors V slightly. Table 7 demonstrates microbatch sensitivity but changes global batch. Acceptance idea: matched-workload latency/throughput, per-pass timing and actual peaks; computed bubble rate is supporting model evidence only. [ZB1/ZB2](../notes/training-memory-scheduling.md) + +## C6. "Overlap the optimizer" hides two different semantic choices + +Signal: a plan proposes overlapping next-step forward work with optimizer processing and labels the change a harmless schedule optimization. + +Decision: ask which mechanism is intended. ZeRO-Offload DPU deliberately accepts one-step stale updates; Zero Bubble post-validation intends synchronous semantics with complete global validation and rollback/redo. Neither permits dropping clipping/NaN decisions. Keep ordinary synchronized execution as the fallback until the selected mechanism's semantics and implementation evidence are explicit. + +F basis: ZeRO-Offload §5.2/§6.2.4 versus Zero Bubble §4/Appendix C and Table 10. Acceptance idea: DPU requires separately approved training-semantics/quality criteria; post-validation requires numerical rollback, validation and dependent-work coverage. Historical BERT F1 or fixed-seed loss matching is insufficient for universal approval. [ZO3/ZB3](../notes/training-memory-scheduling.md) diff --git a/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/papers-20261015/knowledge/offload-delta.md b/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/papers-20261015/knowledge/offload-delta.md new file mode 100644 index 000000000..76ad3fb1a --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/papers-20261015/knowledge/offload-delta.md @@ -0,0 +1,15 @@ +# Incremental extension to training-offload knowledge + +Status: candidate; empirical_validation: not_run. F = source fact; P = proposal. Local ownership is training-resource-budget. The supplier's earlier diagnose-training-offload archive is unavailable in this integration; its prior coverage is a carried supplier claim, not a locally imported capability. [Exact ZeRO-Offload v1 evidence](../references/source-readset.md), [ZO1–ZO3 cards](../notes/training-memory-scheduling.md). + +## Retain existing coverage + +The previous offload notes (prior archive `omnirsi-paper-intelligence-2026-10-15.zip`, semantic path `notes/offload.md`) and source audit (prior archive `omnirsi-paper-intelligence-2026-10-15.zip`, semantic path `notes/references/offload-source-notes.md`) already explain phase memory, slow-tier pipelines, collective reconstruction, tiling, initialization and external/tied parameters. Do not duplicate these as new discoveries. + +## P: Proposed additions + +- Before choosing tensor offload alone, inspect whether moving the optimizer computation with its FP32 state reduces required traffic. Record CPU/update ownership and avoid redundant per-rank host work. F source: ZO §§3–4. +- Distinguish optimizing CPU update from enabling delayed updates. CPU-Adam vectorization/threading/tile-copy is a system optimization; DPU changes training semantics. F source: ZO §§5.1–5.2 and §6.2.4. +- Include an offload-free fallback when all ranks can fit adequate microbatches. F counterexample: ZeRO-2 surpasses ZeRO-Offload at 64/128 GPUs in the 10B experiment (§6.2.3/Fig. 11). +- Do not carry the Table 1 printed memory figure into a universal byte ledger: its final 4M/8× row conflicts with a 16M baseline. Re-derive actual optimizer/precision/buffer accounting as the existing skill already requires. +- If exact execution is required, leave one-step DPU out. If a user separately accepts changed semantics, propose representative convergence/quality checks; the historical GPT-2/BERT tests do not authorize it. diff --git a/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/papers-20261015/notes/training-memory-scheduling.md b/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/papers-20261015/notes/training-memory-scheduling.md new file mode 100644 index 000000000..dd485bd4d --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/papers-20261015/notes/training-memory-scheduling.md @@ -0,0 +1,115 @@ +# Training memory and scheduling: incremental mechanisms + +Status: candidate; empirical_validation: not_run. F = pinned-source fact/model/measurement; P = proposed procedure. This is paper-derived planning, not a tested recipe. [Pins, exact readset, metrics and caveats](../references/source-readset.md). The labels ZO/CM/OL/AL/ZB refer to the five source entries there. + +## P: Joint decision boundary + +Start with the existing ZeRO-Infinity offload notes (prior archive `omnirsi-paper-intelligence-2026-10-15.zip`, semantic path `notes/offload.md`) and training-offload procedure (prior archive `omnirsi-paper-intelligence-2026-10-15.zip`, semantic path `diagnose-training-offload/SKILL.md`). They already cover tensor-class/tier accounting, retrieval pipelines, tiling, initialization and nonlocal ownership. This pack adds a decision among changing optimizer residency, tensor lifetimes, recomputation, operator partitions and fine-grained execution order. None of these papers supplies one globally optimal solver for all five choices together. + +Use one phase-aware capacity/critical-path record: model states; live activations and gradients; operator/workspace peaks; simultaneous transfer buffers; host/device capacity; shape/batch/precision; dependency graph; CPU, accelerator, transfer and collective time. Distinguish useful synchronous-step completion from modeled FLOPs or reduced idle fraction. A memory-saving candidate is valuable only if the remaining compute/transfer schedule remains feasible. Do not add separately reported speedups or memory-saving percentages. + +Activation checkpointing is rematerialization within training, not persistent restart/recovery checkpointing. H2D/D2H and same-host IPC are not Network; inter-node transfers and collectives may be. No NPU kernel, collective, compiler or asynchronous-execution compatibility has been established. + +## ZO1. Move the optimizer computation with its state + +- F, objective/assumptions: ZO §§3.1–3.5 seek maximal model-state relief at minimal host/device traffic while excluding compute-heavy CPU forward/backward work. Model: mixed-precision Adam, known parameter count, relatively slow CPU and PCIe; activation offload excluded. +- F, variables/constraints/mechanism: choose placement of data/compute graph nodes; colocate FP32 master weights/moments and update/cast on CPU, keep FP16 weights and F/B on GPU, stream gradients to CPU. Whole-state graph-cut minimum is 4M bytes/iteration in the restricted model. §4.2 first shards gradients/optimizer ownership, then offloads; CPU work and traffic are not duplicated by every data-parallel rank. +- F, benefit/cost/evidence: Table 4's CPU-Adam reduces CPU update latency; Fig. 8 reports 14% average TFLOP/s gain over L2L with matched batch and no DPU. CPU memory bandwidth, thread contention, transfer and updated-weight collective remain costs. +- F, limits/counter-signals: Table 1 has inconsistent memory accounting; the optimality claim excludes activations, different optimizers and partial heterogeneous plans. Fig. 11 shows ZeRO-2 overtaking offload at 64/128 GPUs once capacity no longer forces smaller batches. +- P, rule: extend the existing offload diagnosis with an ownership-and-compute ledger. Compare CPU-update-plus-return against GPU-update-plus-state-transfer under the actual optimizer. Prefer an offload-free candidate when both fit and exposed transfer dominates; never infer benefit from CPU capacity alone. + +## ZO2. Optimize CPU update and copy as one pipeline + +- F, objective/assumptions: ZO §5.1 accelerates O(M) updates where CPU work or weight return delays GPU progress; assumes vectorizable Adam and usable host memory bandwidth. +- F, variables/constraints/mechanism: SIMD width, loop unroll, threads, tile size; fuse vector arithmetic and pipeline tile updates with prior-tile H2D parameter copy. Historical AVX512 and unroll 8 are implementation choices, not portable constants. +- F, benefit/cost/evidence: Table 4 gives 0.22 vs 1.39 s at 1B parameters and 2.57 vs 14.76 s at 10B for CPU-Adam vs PyTorch CPU; GPU Adam is still faster. Tiling/threads/copies can compete for memory bandwidth; isolated component ablations are unreported. +- F, limits/counter-signals: host saturation and small GPU compute windows; adding threads does not create bandwidth. Historical CPU improvements do not establish present optimizer speed. +- P, rule: use supplied per-stage CPU/transfer evidence to identify whether optimizing update, return copy, or neither could affect the step critical path. Keep bounded buffers and pinned-memory accounting from the existing skill; do not prescribe ISA/thread counts from the paper. + +## ZO3. Delayed update is a separate training-semantics branch + +- F, objective/assumptions: ZO §5.2 hides CPU optimizer work at small batch by allowing one-step staleness after a stable warmup. +- F, variables/constraints/mechanism: DPU start iteration and delayed-gradient schedule; one iteration skips update, then CPU updates overlap next GPU F/B using older parameters. +- F, benefit/cost/evidence: §6.2.4/Fig. 9 reports 1.12–1.59× throughput at microbatch 8. Figs. 12–13 check GPT-2 loss and BERT-large/SQuAD F1 92.8, with DPU after 40 iterations. +- F, limits/counter-signals: training dynamics change; the GPT loss initially lags. Two workloads do not bound behavior for other optimizers/models, nor prove a universal warmup length. +- P, rule: do not silently include DPU in an exact-execution offload plan. Mark it a separate consequential proposal requiring explicit acceptance of changed training semantics and representative quality/convergence evidence. Prefer ordinary overlap if exact updates are required. + +## CM1. Pay recomputation cost selectively under event-level memory limits + +- F, objective/assumptions: CM §§4.1–4.10 minimize summed operator-evaluation cost for a static known-size DAG with deterministic/replayable operations and supplied cost estimates. +- F, variables/constraints/mechanism: binary compute R and retention S, FREE and U memory variables; ensure every dependency exists, compute each frontier, and count newly allocated output before freeing consumed inputs. Retain valuable values and rematerialize others. Inputs/parameters and a gradient reserve remain resident. A fixed frontier order bounds the search. +- F, benefit/cost/evidence: §6.3/Fig. 5's U-Net/16-GB profile model improves modeled time 1.20× over linearized greedy; recomputation spends extra compute to avoid memory/transfer pressure. §6.4's 5.1× MobileNet batch-capacity ratio is model-based with a one-extra-forward FLOP constraint. +- F, limits/counter-signals: no joint transfer/parallelism objective; additive layer cost can miss kernel fusion, concurrency and workspace behavior. Stateful/random operations and changed batches need correctness review. A timeout is not infeasibility proof. +- P, rule: compare a selective-rematerialization candidate to retention/offload using supplied costs and lifetime peaks; favor discarding values with low recomputation cost relative to sustained resident burden, while preserving all dependencies. Validate candidate peak memory and equivalent numerical semantics before claiming feasibility. + +## CM2. Approximation quality and memory feasibility are different checks + +- F, objective/assumptions: CM §5 seeks practical schedules when the exact MILP is costly. +- F, variables/constraints/mechanism: relax integrality, round only retention S, reconstruct minimally necessary R to repair dependency constraints, then derive releases. Their 10% budget allowance is empirical; rounding itself does not enforce the capacity cap. +- F, benefit/cost/evidence: §6.5/Table 2's geometric-mean FLOP-cost ratios are 1.00–1.06 across mutually feasible budgets, not a worst-case guarantee. Appendix D shows the allowance can waste capacity. DenseNet161 lacked a feasible ILP result within one day (§5). +- F, limits/counter-signals: computational validity can coexist with OOM; input-specific rounding margin and planning overhead matter. +- P, rule: treat an approximate schedule as a proposal until both dependency replay and exact peak-accounting pass. Record solver status, feasible incumbent, bound/gap and amortization separately; do not report near-optimal compute as memory-safe execution. + +## OL1. Shorten live ranges before buying more capacity + +- F, objective/assumptions: OL §§2–3 minimize memory of a static DAG without deleting/recomputing values. Tensor sizes and all dependencies must be represented. +- F, variables/constraints/mechanism: creation/preservation times select a legal topological order; exactly one tensor creation, shared-consumer lifetimes and multi-output creation are explicit. Reorder eligible work, including safe early weight updates, so large gradients need not remain live unnecessarily. §4.3 adds precedence controls to limit the search. +- F, benefit/cost/evidence: §5.3 measures requested-memory reduction excluding fragmentation: mean 22.5% at batch 1 and 10.1% at batch 32 versus PyTorch 1.11 ordering. No extra recomputation or offload traffic is introduced by the mechanism, but planning and changed execution concurrency can cost time. +- F, limits/counter-signals: activations retained for backward give little forward-pass leverage; large batches reduce gradient-relative savings. Distributed accumulation, global clipping, tied state and shared weights can restrict early updates; the paper does not establish those integrations. +- P, rule: investigate excessive live gradients/outputs before offload. Propose only reorderings proven legal by the full graph, including update/collective barriers. If activations dominate a largely linear order, route to selective rematerialization rather than promise OLLA's average saving. + +## OL2. Pack nonoverlapping lifetimes into reusable addresses + +- F, objective/assumptions: OL §§3.3–3.5 minimize reserved address extent given predictable tensor lifetimes; location means addresses in one memory space. +- F, variables/constraints/mechanism: integer base addresses and pairwise nonoverlap for simultaneously live tensors; reuse addresses across disjoint lifetimes. §4 bounds lifetimes, removes provably unnecessary pair constraints, splits ordering/packing, and preplaces nested activations. A preallocated buffer makes deallocation a no-op. +- F, benefit/cost/evidence: §5.4 removes measured fragmentation in evaluated cases; baseline ratios average 7.9%/26.1% at batch 1/32. §5.7 combined peak reduction is 30.4%/36.1% with two five-minute search caps. The estimated runtime saving is not direct end-to-end timing. +- F, limits/counter-signals: empirical fragmentation elimination does not prove all orderings can pack without loss. Dynamic shapes, overlapping executions, alignment/workspace and aliasing can invalidate fixed addresses. Low fragmentation means less scope. +- P, rule: separate live-byte excess from reserved-byte fragmentation, using the same phase/denominator. Propose address planning only when allocation/lifetime evidence is stable; do not misroute this mechanism as CPU/SSD placement or kernel-VM tuning. + +## AL1. Choose operator shards and pipeline stages together, within a declared search space + +- F, objective/assumptions: AL §§4–5 minimize pipeline latency for static shapes, homogeneous devices inside each logical mesh, a supplied operator order and synchronous 1F1B-style timing. +- F, variables/constraints/mechanism: select operator shardings/resharding edges; then stage boundaries and physical/logical meshes, using stage cost and memory feasibility. Eq. 5 retains multiple in-flight activation sets. Objective includes first-microbatch latency and bottleneck-stage repetition. Operator clustering/pruning reduce planning cost. +- F, benefit/cost/evidence: §8.3/Fig. 9: Wide-ResNet/32-GPU plan outperforms equal-operator/equal-layer restrictions 2.6×/1.6× in PFLOP/s. Fig. 12 uses unequal 4/4/8-GPU stages. Planning costs are material (Table 5: 2393.26 s for one GPT-39B search). +- F, limits/counter-signals: intra-op compute costs are simplified to zero; stage costs include a profiling/modeling path. Inter-stage transfer and overlap are omitted from the optimizer; microbatch count is external; no global optimum over all plans. Equal-layer is already as good on the tested homogeneous GPT case. +- P, rule: consider changing parallel plans when memory/work differs markedly by stage or collective cost dominates. Compare the proposed heterogeneous plan to a simple equal-stage baseline under fixed global batch, actual topology and explicit cross-stage-transfer cost. Report omitted costs and plan-generation amortization rather than adopting solver output uncritically. + +## AL2. Avoid repeated slow-link copies during resharding + +- F, objective/assumptions: AL §6 reduces communication between unequal meshes when receivers need replicated tiles and local bandwidth is better than cross-mesh bandwidth. +- F, variables/constraints/mechanism: tile source/destination correspondence, unique cross-mesh sends, local allgather; ensure all target shardings receive correct elements. Static per-mesh instructions coordinate execution. +- F, benefit/cost/evidence: §8.5/Fig. 11 reports 2.0× PFLOP/s throughput over send/recv-only for 32-GPU Wide-ResNet. Local collectives/staging replace duplicate slow-link traffic; they are not free. +- F, limits/counter-signals: topology may not provide the assumed asymmetry; optimal many-to-many mapping is not solved. One-byte signal baseline is only an upper-bound control. +- P, rule: derive actual required tensor intersections and replication before proposing multicast-like staging. Classify local allgather under Accelerator topology and only the cross-node segment under Network. Reject byte savings that overload local links or increase peak buffers beyond the common ledger. + +## ZB1. Split critical input-gradient work from deferrable weight-gradient work + +- F, objective/assumptions: ZB §§1–3 reduce synchronous pipeline idle time while respecting activation limits, dependencies and measured F/B/W/communication times. +- F, variables/constraints/mechanism: execution order/end times for F, B and W; prioritize B needed by the previous stage, schedule W in gaps or to reclaim memory. Delaying W extends retention of its inputs. The heuristic searches under memory caps; limited-scale ILP provides another route. +- F, benefit/cost/evidence: Table 4's 28.3B/32-GPU/m96 row gives 0.87 versus 0.76 samples/s/GPU for ZB-1p vs 1F1B at 44 vs 43 GB. ZB-2p reaches 0.99 at 74 GB. Table 5's lower bubble rates are calculated from timing inputs; Fig. 6 shows extra real gaps. +- F, limits/counter-signals: equal F/B/W theory does not match actual kernels; fused backward splitting may add overhead; memory is not free. Appendix A's tail parameter grouping for DP overlap has no isolated measured ablation. +- P, rule: require a trace or supplied equivalent showing B blocked behind deferrable W. Propose split schedules only with measured pass costs, retained-byte lifetimes and collective ordering. A smaller bubble fraction alone is not higher useful-step throughput. + +## ZB2. Compare memory-equivalent schedule/microbatch choices + +- F, objective/assumptions: ZB §§5.4–6 trade bubble reduction against activation memory and microbatch kernel efficiency. +- F, variables/constraints/mechanism: activation cap, microbatch size/count, two-chunk V placement. ZB-V starts F/B locally sooner and balances memory; its ideal zero-bubble claim assumes equal pass times. ZB-2p* trades half-size microbatches for twice their count at fixed global batch. +- F, benefit/cost/evidence: Table 6's 28.3B/32-GPU/base b2,m96: V 1.01 at 71 GB, 2p* 1.00 at 72, 1F1B 0.82 at 69 samples/s/GPU. At 6.2B, 2p* instead beats V. Extra boundaries/communication and smaller kernels can offset reduced idle time. +- F, limits/counter-signals: theoretical pMB is activation memory, not total HBM. Tables 7 and 11 change global batch, and Table 11 has ambiguous m labels; do not use them as matched-global-batch proof. Performance can plateau before exact zero bubbles. +- P, rule: compare a small set at the same global batch, precision, model and total-device-memory margin. Include simpler 1F1B, memory-capped split backward, and V/2p* only when legal. Choose useful throughput over the lowest modeled idle fraction. + +## ZB3. Preserve optimizer validation when removing its global barrier + +- F, objective/assumptions: ZB §4 removes an optimizer synchronization bubble assuming numerical exceptions/clipping are uncommon and updates can be validated and repaired. +- F, variables/constraints/mechanism: partial global-state reduction, tentative update, later complete validation, rollback/re-update where required. Appendix C supplies an in-place AdamW inverse to avoid state copies; no stale-gradient semantics are intended. +- F, benefit/cost/evidence: Appendix E/Table 10: 28.3B/32 GPUs/m96 post-validation 0.99 versus synchronized 0.91 samples/s/GPU. Author per-iteration fixed-seed loss checks are bit-identical for tested schedules, not a broad rollback-stress or convergence study. Rollbacks cost work and can perturb scheduling. +- F, limits/counter-signals: frequent clipping/NaNs, noninvertible updates, finite-precision reversibility, stateful side effects, or unverified rollback coverage undermine the benefit/correctness. Failure-rate sensitivity and broad optimizer support are unreported. +- P, rule: treat barrier removal as a separate correctness gate. Retain global clipping/NaN semantics and require evidence of rollback, redo and dependent-work handling on the actual optimizer before proposing enablement. When absent, keep the synchronized fallback. Do not confuse this post-validation with ZeRO-Offload DPU. + +## Candidate destinations + +- [Activation-residency skill](../../../../plan-activation-residency/SKILL.md): CM1–CM2 and OL1–OL2 share one live-range/retain/recompute decision, with separate capacity and correctness checks. +- [Parallel-plan skill](../../../../choose-parallel-training-plan/SKILL.md): AL1–AL2 share one partition, mapping and resharding decision. +- [Split-backward skill](../../../../assess-split-backward-schedule/SKILL.md): ZB1–ZB3 share a pipeline schedule, memory and optimizer-semantics decision. +- ZO1–ZO3 are an [incremental knowledge extension](../knowledge/offload-delta.md) to the existing offload skill, avoiding a duplicate skill. +- [Cases](../cases/paper-grounded-cases.md) are review examples, not executed tests. [Integration proposals](../INTEGRATION_NOTES.md) target only docs/reference-matrix.md and docs/searchspace-matrix.md. diff --git a/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/papers-20261015/references/source-readset.md b/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/papers-20261015/references/source-readset.md new file mode 100644 index 000000000..4fdf21fec --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/papers-20261015/references/source-readset.md @@ -0,0 +1,98 @@ +# Pack C: pinned sources and actual readset + +Status: candidate; empirical_validation: not_run. F = source-reported design, analysis, or observation. P = proposed application. Research date: 2026-10-15 UTC. These are historical designs, not current implementation or NPU-compatibility claims. Only five assigned papers and their original arXiv records were researched. No implementation source was needed. No installation, benchmark, reproduction, hardware task, framework change, matrix edit, InferRSI change, or PR was performed. PDF extraction/rendering and artifact checks are document operations, not empirical validation. + +Activation checkpoints here retain intermediate tensors for recomputation inside training. They are not persistent recovery checkpoints or durability mechanisms. + +## ZO: ZeRO-Offload + +- Full title: ZeRO-Offload: Democratizing Billion-Scale Model Training. Jie Ren, Samyam Rajbhandari, Reza Yazdani Aminabadi, Olatunji Ruwase, Shuangyan Yang, Minjia Zhang, Dong Li, Yuxiong He. +- [Original metadata](https://arxiv.org/abs/2101.06840), [pinned v1 PDF](https://arxiv.org/pdf/2101.06840v1). Only v1 listed: 2021-01-18 02:11:25 UTC. 14 PDF pages. +- Actual relevant readset: §§2–3.5, including §3 footnotes 1–2 and Fig. 2/Table 1; §§4.1–4.2/Figs. 3–4 and associated schedule discussion; §§5.1–5.2 including displayed CPU-Adam algorithm and Fig. 6; §§6.1–6.2.4, Tables 2–4, Figs. 7–13 and associated prose. Visually checked PDF pp. 5 and 11, especially Table 1, Table 4 and Figs. 11–13. Figure 5's code screenshot was not independently transcribed or implementation-audited. +- SHA256 of downloaded pinned PDF: 361dd58aadd744a79b17268b985034de00b9cf7423c000f9aa1549bfa382146c. + +F, setup: GPT-2-like Transformer models; mixed FP16/FP32 Adam. Single-node capacity/throughput tests use DGX-2 with 16 V100 32-GB GPUs, two Xeon Platinum 8168 CPUs, 1.5-TB DDR4, reported bidirectional PCIe 32 GB/s. Scaling uses eight DGX-2 nodes and an InfiniBand switch. Table 3 changes depth, width, microbatch and model parallelism by model size. Fig. 8 uses total batch 512, matched microbatches and gradient accumulation, with delayed parameter update (DPU) disabled. Fig. 10 uses total batch 512 but the largest feasible microbatch for each system. These are different comparison controls. + +F, evidence ledger: +- §§3.1–3.5: graph cuts minimize host/device bytes after fixing O(MB) forward/backward compute and FP16 weights on GPU; O(M) optimizer operations and FP32 master weights/moments move to CPU, as do FP16 gradients. The stated minimum is 4M bytes per iteration for whole model-state offloads in this model. The analysis excludes activation offload and residual-state costs; it is not an arbitrary-hardware global optimum. +- Table 1 prints the final row as 4M device memory and 8× reduction versus 16M. These entries are mutually inconsistent; the surrounding placement prose leaves FP16 parameters plus transient gradient buffers on GPU. Do not silently replace the printed number or treat the table as a reliable total-peak formula. +- §4.2: reduce-scatter gradients before offloading each owned partition; parallel CPU updates; return updated parameter partitions and allgather. Partitioning prevents duplicated host updates/traffic across data-parallel replicas. Claims about increasing CPU resources apply across compute nodes, not indefinitely across more GPUs sharing a fixed host. +- §5.1/Table 4: CPU-Adam versus PyTorch CPU Adam latency in seconds for 1B/2B/4B/8B/10B parameters: 0.22/0.51/1.03/2.41/2.57 versus 1.39/2.75/5.71/11.93/14.76. PyTorch GPU (L2L) comparator: 0.10/0.26/0.64/0.87/1.00. SIMD/loop-unrolling/OpenMP and tiled copy are combined; isolated attribution for each is unreported. +- §6.2.1/Fig. 7: 13B fits one V100 versus 1.4B PyTorch; L2L fits 17B. Capacity leadership therefore does not imply throughput leadership. §6.2.2/Fig. 8: ZeRO-Offload is 14% faster on average, up to 22%, than L2L in reported TFLOP/s under the matched batch comparison. The paper models L2L traffic as 28M versus 4M bytes; this is historical baseline accounting. +- §6.2.2/Fig. 10: up to 70B on 16 GPUs with model parallelism, over 30 TFLOP/s/GPU; not a same-size speed ratio against a baseline that OOMs. §6.2.3/Fig. 11: 10B model aggregate throughput approximately scales through 128 GPUs, but ZeRO-2 becomes faster at 64/128 GPUs once both can use similar microbatches and offload retains a transfer cost. Do not label this fixed-total-work strong scaling without the missing batch/scaling controls. +- §5.2/§6.2.4/Figs. 9,12,13: one-step DPU intentionally uses stale updates after an initial ordinary-training period. At microbatch 8, throughput ratio with/without DPU is reported 1.12–1.59×. Convergence examples enable DPU after 40 iterations: GPT-2 pretraining for 100K iterations shows initially slower loss then catching up; BERT-large SQuAD fine-tuning reaches F1 92.8 in both variants. These two workloads do not establish universal convergence safety. + +## CM: Checkmate + +- Full title: Checkmate: Breaking the Memory Wall with Optimal Tensor Rematerialization. Paras Jain, Ajay Jain, Aniruddha Nrusimha, Amir Gholami, Pieter Abbeel, Kurt Keutzer, Ion Stoica, Joseph E. Gonzalez. +- [Original metadata](https://arxiv.org/abs/1910.02653), [pinned v3 PDF](https://arxiv.org/pdf/1910.02653v3). v1 2019-10-07; v2 2020-03-12; read v3 2020-05-14 17:46:43 UTC. 15 PDF pages. No revision mixing. +- Actual relevant readset: §§4.1–4.10, Eqs. 1–9, Theorem 4.1 and Lemmas 4.1–4.2; §§5.1–5.3 and Algorithms 1–2; §§6.1–6.5, Eq. 10, Tables 1–2, Figs. 5–6; Appendices A–D, Figs. 7–8. Visually checked PDF pp. 9–10 for Figs. 5–6/Table 2. PDF p. 2 contains a figure with embedded manuscript text; its obsolete equation/section snippets were not used in place of the body formulation. +- SHA256: 8355cc2ecac072863fde2542585f8da0be30924e6181d9b05a36a63b22a1f694. + +F, model and evidence: +- §§4.1–4.10: static DAG; each value has memory Mv and per-evaluation cost Cv. Binary R[t,i] selects evaluation, S[t,i] retention. U[t,k] accounts for memory just after an output exists and before dependencies are freed. Inputs/parameters and parameter-gradient reserve remain resident (Eq. 2). FREE variables require no later user and no retained checkpoint. Objective minimizes summed evaluation costs under per-event memory budget, not transfer time. +- §4.6/Eq. 8 restricts to a supplied topological order and frontier-advancing stages. This narrows the feasible set; optimality is within this formulation, not all possible reordered/parallel executions. Example: an eight-layer linear graph with unit costs and memory budget 4 solves in 0.23 seconds versus 9.4 hours unpartitioned, to the same objective. Appendix A's corresponding integrality-gap example is 1.18 versus 21.56. These are optimization examples, not training throughput. +- §4.10: additive timings from layer profiling on target hardware, shapes and batch; dense tensors use four-byte floats in the evaluated model. §6 implementation is TensorFlow 2.0/Keras/Gurobi. Most ordinary solves use 3600-second limit on at least 24 CPU cores. §5 reports no feasible solution for a DenseNet161 instance within one day; solver timeouts do not prove infeasibility. +- §6.3/Fig. 5: overhead is profile-model time relative to no-rematerialization ideal, using one NVIDIA V100. U-Net batch 32, 416×608 images, 16-GB budget: reported 1.20× speedup over linearized greedy and 1.38× over linearized sqrt(n). This is not directly measured whole-training speedup. VGG16 batch 256 and MobileNet batch 512 use 224×224. +- §6.4/Eq. 10/Fig. 6: maximize feasible batch subject to 16 GB and at most one extra forward pass in statically computed FLOPs. The nonlinear formulation gets a one-day limit; returned batch is a lower bound if optimality is unproved. MobileNet 224×224: 1105 versus 215 checkpoint-all and 640 linearized-greedy; author reports 5.1× and 1.73× respectively. U-Net 416×608: 61 versus 16 checkpoint-all and 35 best plotted heuristic. These are theoretical feasible-batch results, not observed time-to-quality or a guarantee that enlarged batch preserves training behavior. +- §§5.1–5.3/Algorithm 2: round S, then restore minimal necessary R to satisfy computation dependencies. Capacity is not guaranteed by this procedure. The authors empirically use 10% memory allowance; Appendix D says that allowance is overly conservative for MobileNet. +- §6.5/Table 2: two-phase approximation COSTapprox/COSTopt, geometric mean across mutually feasible budgets, in FLOPs: MobileNet 1.06, VGG16 1.01, VGG19 1.00, U-Net 1.03, ResNet50 1.05. It is neither a worst-case 1.06 approximation guarantee nor a whole-job speed ratio. Appendix D/Fig. 8 compares randomized versus deterministic two-phase rounding with profile-cost milliseconds. + +## OL: OLLA + +- Full title: OLLA: Optimizing the Lifetime and Location of Arrays to Reduce the Memory Usage of Neural Networks. Benoit Steiner, Mostafa Elhoushi, Jacob Kahn, James Hegarty. +- [Original metadata](https://arxiv.org/abs/2210.12924), [pinned v2 PDF](https://arxiv.org/pdf/2210.12924v2). v1 2022-10-24; read v2 2022-11-02 19:22:24 UTC. 14 PDF pages. +- Actual relevant readset: §§2.1–2.3/Figs. 3–4; §§3.1–3.5, Eqs. 1–9/Function 1; §§4.1–4.5, Eqs. 10–15/Functions 2–5/Figs. 5–6; §§5.1–5.7/Figs. 7–14; §6's placement/lifetime comparison. Visually checked PDF p. 10 (Figs. 11–14 and §5.7). Individual bar values were not digitized. +- SHA256: 69aebb2c874871e363ccec93e2ea15891e91c793153cde37004d17ea12ddef0b. + +F, model and evidence: +- §3: DAG tensors are edges (possibly multiple consumers), with known sizes. Binary creation C[e,t] and preservation P[e,t] enforce exactly one creation, availability of all inputs, contiguous retention and simultaneous sibling outputs. Integer A[e] is a base address in one preallocated buffer, not GPU/CPU/SSD tier placement. Concurrent live tensors cannot overlap addresses. Objective minimizes maximum A[e]+size[e]. It neither offloads nor recomputes tensors. +- §§4.1–4.5: bound variable ranges using earliest/latest schedules and useful lifetimes; drop pairwise constraints for proven nonoverlapping tensors; add control edges to force safe early weight updates; split lifetime optimization (Eq. 14) from address optimization (Eq. 15); preplace nested activation lifetimes. The split relies on their empirical ability to remove fragmentation, not a universal proof that independently optimized lifetimes always admit ideal packing. +- §§5.1–5.2: PyTorch 1.11, torchtext/torchvision 0.12, torch.FX and Gurobi 9.1.1; Xeon Gold 6138 at 2.0 GHz plus A100 40 GB. Eleven families: AlexNet, EfficientNet, GoogleNet, MNASNet, MobileNet, ResNet, ResNet3D, Transformer, VGG, ViT, XLM-R, at batches 1/32. Graph size ranges from AlexNet 118 to XLM-R 2007 operators. +- §5.3/Fig. 7: node-reordering comparison excludes fragmentation, measuring peak requested operator memory/resident demand rather than allocator-reserved bytes. Maximum reduction 38%; mean 22.5% at batch 1, 10.1% at batch 32. Less leverage at large batch is attributed to forward activations dominating gradients. +- §5.4/Fig. 8: fragmentation defined (MR−RS)/MR at peak reserved memory MR. PyTorch mean fragmentation 7.9% at batch 1, 26.1% at batch 32; OLLA fully removes it in evaluated scenarios. Do not add these percentages to lifetime percentages: denominators differ. +- §§5.5–5.6/Figs. 9–12: median ordering solve 1.4±0.2 s, address generation 5.7±0.6 s; difficult EfficientNet ordering takes 2 min for batch-1 optimum, 5 min to within 1% at batch 32. GoogleNet/EfficientNet packing reaches <1% fragmentation within 5 min. The text's uncertainty notation is retained; no unreported confidence interpretation is added. +- §5.7/Fig. 13: cap each of the two optimizations at five minutes; overall memory reduction averages 30.4% at batch 1 and 36.1% at batch 32 versus PyTorch. §5.7/Fig. 14 estimates about five minutes runtime saved over one million batch-32 iterations by comparing allocator costs with upfront optimization. Total training time under the two schemes was explicitly not directly measured; batch-1 runtime estimate is unreported. +- Isolated ablations of every pruning/early-update/preplacement optimization and distributed-training interactions are unreported. No conclusion about current PyTorch allocator behavior follows from the 1.11 comparison. + +## AL: Alpa + +- Full title: Alpa: Automating Inter- and Intra-Operator Parallelism for Distributed Deep Learning. Lianmin Zheng, Zhuohan Li, Hao Zhang, Yonghao Zhuang, Zhifeng Chen, Yanping Huang, Yida Wang, Yuanzhong Xu, Danyang Zhuo, Eric P. Xing, Joseph E. Gonzalez, Ion Stoica. +- [Original metadata](https://arxiv.org/abs/2201.12023), [pinned v3 PDF](https://arxiv.org/pdf/2201.12023v3). v1 2022-01-28; v2 2022-06-03; read v3 2022-06-28 19:36:44 UTC. 20 PDF pages. A v1 PDF was fetched before metadata resolution but not used as evidence. +- Actual relevant readset: §§2–8.6 including every method, limitation and evaluation subsection; Eqs. 1–6, Algorithm 1, Tables 1–5, Figs. 1–12 and associated prose; Appendix A/Theorem 1/Eq. 7, Appendix B/Tables 6–8, Appendix C/Fig. 13. Visually checked PDF p. 13/Table 5/Figs. 10–11. +- SHA256: cd1dea70769571a5e9298ba0610e04cc514a06ab12018dd7f19a457fd00cd474. + +F, model and evidence: +- §4/Eq. 1: choose one sharding algorithm per operator on a homogeneous 2-D logical device mesh, accounting for operator communication and edge resharding. The evaluated ILP estimates bytes/bandwidth and sets compute costs dv to zero, assuming equal arithmetic work among heavy-op shardings and negligible lightweight work. It does not show all equal-FLOP kernels run equally fast. Post-ILP reduce-scatter/allgather can reduce replicated optimizer work without changing total collective bytes. +- §5/Eqs. 2–5: stages are contiguous in a given operator ordering; corresponding forward/backward ops colocate. Objective sum(stage latency)+(B−1)×max(stage latency) for the chosen static GPipe/1F1B timing model. DP chooses stage boundaries and restricted physical submesh shapes; intra-op choices are evaluated per stage/mesh. 1F1B feasibility uses memstage+s×memact≤memdevice. Infeasible stage/mesh pairs get infinite cost. Shape restriction ensures device coverage, not global-optimal search over arbitrary partitions. +- §5.2 says compile/profile stage plans including fusion and memory planning; §8.4 describes accelerating profiling with a piecewise-linear XLA-operation cost model. Do not present all plan costs as directly timed full stages. Search also clusters operators and prunes DP choices. +- §6/Fig. 6: cross-mesh resharding sends each needed tile across slow links then locally allgathers replicated destinations, avoiding redundant slow transfers. Static per-mesh instruction lists avoid continuous driver coordination. Optimal cross-mesh resharding is left to future work. +- §7: no inter-stage communication cost in the plan objective; microbatch count is an external hyperparameter, not internally optimized; static shapes/graphs and linear schedules; no optimization of computation/communication overlap. Two-level solution is not guaranteed globally optimal. +- §8: eight AWS p3.16xlarge nodes, eight V100 16-GB GPUs/node, intra-node NVLink, 25-Gbps cross-node bandwidth; 64 vCPU and 488-GB host memory/node. Metric is aggregate PFLOP/s on warmed-up dummy-data batches; model size grows with GPU count (weak scaling). Global batches: GPT and MoE 1024/FP16; Wide-ResNet 1536/FP32. GPT/MoE sequence 1024; image input 224×224×3. Microbatch tuned per configuration. +- §8.1/Fig. 7: GPT roughly matches grid-searched Megatron-LM v2; MoE beats DeepSpeed 3.5× on 16 GPUs (10B model) and 9.7× on 32 GPUs (27B), where the historical DeepSpeed baseline has no inter-op pipeline and slow network communication dominates. Wide-ResNet achieves author-reported 80% linear-scaling efficiency on 32 GPUs. These are not time-to-quality or equal-model strong-scaling results. +- §8.2/Fig. 8: isolate intra-op search on one eight-GPU node, disabling pipeline and gradient accumulation, with altered model shapes/batches versus §8.1. ILP is compared with data parallel, ZeRO-2/3 and largest-axis sharding heuristic. It cannot be merged numerically with the end-to-end setup. +- §8.3/Fig. 9: at 32 GPUs, Wide-ResNet DP plan is 2.6×/1.6× faster in PFLOP/s than equal-operator/equal-layer restrictions; equal-layer equals DP on homogeneous GPT. §8.5/Fig. 11: local-allgather resharding gives 2.0× throughput over send/recv-only on 32-GPU Wide-ResNet. One-byte signal control is a synthetic upper bound, not executable model semantics. +- §8.4/Table 5: GPT-39B/64-GPU compilation 1582.66 s, profiling 804.48 s, stage DP 1.65 s, other 4.47 s, total 2393.26 s versus >40 h without optimizations. This is one supplied microbatch-count run, not cost of searching all B. +- §8.6/Fig. 12: Wide-ResNet/16 GPUs chooses three stages on 4/4/8 GPUs, with early activation-heavy layers preferring batch partitioning and later weight-heavy work different sharding. Table 4 rounds the 32-GPU Wide-ResNet model to 6.7B while Table 8 says 6.8B; do not silently reconcile. + +## ZB: Zero Bubble Pipeline Parallelism + +- Full title: Zero Bubble Pipeline Parallelism. Penghui Qi, Xinyi Wan, Guangxing Huang, Min Lin. +- [Original version record](https://arxiv.org/abs/2401.10241v1), [pinned v1 PDF](https://arxiv.org/pdf/2401.10241v1), [same-version HTML](https://arxiv.org/html/2401.10241v1). The original record and PDF both give v1 as 2023-11-30 10:40:34 UTC despite the 2401 identifier; retain that source metadata. 19 PDF pages. arXiv's link boilerplate says "and 2 other authors" while its author list and PDF contain four; use the actual list. +- Actual relevant readset: §§1–7 (all subsections), Tables 1–8/Figs. 1–9; Appendices A–H including Figs. 10–11, Appendix B Eqs. 1–2, Appendix C Algorithm 1 (AdamW rollback), Appendix G Eqs. 3–7, Tables 9–12. Visually checked PDF pp. 7, 11 and 18 for Tables 4,6–8,11 and associated plots/text. The v1 HTML served as an additional same-version methods check. +- SHA256: 0de7cd6efd52eaa3f216129cd186ab755b1045bca1f6ddc422216295a7e9fee9. + +F, model and evidence: +- §§1–2: split backward into B (input gradient, critical across stages) and W (parameter gradient, movable after B). Delaying W retains its needed activations/gradients. Table 2's ideal comparison: 1F1B bubble (p−1)(TF+TB+TW), ZB-H1 (p−1)(TF+TB−TW), both peak activations pMB; ZB-H2 bubble (p−1)(TF+TB−2TW), peak (2p−1)MB. Zero-bubble equality depends on timing assumptions and removing the optimizer barrier; it is not a universal empirical zero-idle guarantee. +- §3/Appendix G: schedule ordering/end times with inter-stage F/B dependencies, device sequencing and cumulative activation-memory limits; input p,m, memory cap, profiled TF/TB/TW/Tcomm. Heuristic schedules W into gaps or when memory needs release; ILP is feasible only at limited problem scale. Appendix A proposes parameter-grouped tail W work for overlapping data-parallel allreduce; an isolated measured ablation of that proposal is unreported. +- §4/Appendix C: partial reductions followed by post-update validation; invalid speculative updates roll back and redo using global clipping/NaN state. AdamW arithmetic inverse is supplied to avoid a full historical state copy. This is not permission to omit clipping or accept stale-gradient training. Finite-precision rollback stability, rare-event failure frequency and broad optimizer support are not established by the reported throughput table. +- §5.1: Megatron-LM-based GPT-like models, up to 32 A100 SXM 80-GB GPUs on four RoCE RDMA nodes; sequence 1024; end stages have one fewer Transformer layer to offset embedding/loss work. Hardware bandwidth value is unreported. Table 3: 1.5B/6.2B/14.6B/28.3B on 8/8/16/32 pipeline GPUs, microbatch size 6/3/1/1 and microbatch counts 3p,4p,8p. 1F1B-I uses each Transformer layer as a chunk. Author correctness check uses identical fixed-seed per-iteration losses, without training to convergence; the reported number of correctness-check iterations is unreported. +- §5.2/Table 4, representative measured row: 28.3B, 32 GPUs, b=1,m=96: ZB-2p 0.99 samples/s/GPU at 74 GB, ZB-1p 0.87 at 44 GB, 1F1B 0.76 at 43 GB, 1F1B-I 0.82 at 58 GB. Doubling an activation budget does not double total memory. Same-activation-cap ZB-1p still has modestly higher measured total memory than 1F1B. +- §5.3/Table 5: bubble rates are schedule calculations using measured timing inputs, not directly measured idle percentages. For the above row: 1F1B 0.2646; ZB-H2 0.0641; ZB-1p 0.1421; ZB-2p 0.0038. Fig. 6 contrasts generated and profiled timelines and acknowledges extra real bubbles. Appendix D/Table 9 supplies timing inputs; its table does not explicitly label time units, so no unit is invented here. +- §5.4/Fig. 7/Appendix B: memory/idle tradeoff plateaus near 2pMB when TF≈TB and Tcomm is small. More memory can have diminishing returns; communication and first-B dependency chains remain. +- §6/Fig. 8: ZB-V maps two chunks/device in a forward-and-reverse V order, enabling earlier local backward and balanced activation demand. Ideal TF=TB=TW permits zero bubble at pMB; actual profiled schedules remain nonzero. Additional chunk boundaries introduce communication and computation-granularity tradeoffs. +- §6.1/Table 6 is the stronger approximately matched-memory/global-batch comparison: ZB-2p* halves b and doubles m, keeping global batch. 28.3B, 32 GPUs, base b=2,m=96: ZB-V 1.01 samples/s/GPU at 71 GB; ZB-2p* 1.00 at 72; ZB-1p 0.94 at 73; 1F1B 0.82 at 69. 6.2B/16 GPUs/base b=6,m=48: ZB-2p* 4.36 at 63 GB versus ZB-V 4.15 at 64; V is not universally fastest. +- Table 7 varies b with fixed m, changing global batch; the b=1→2 14.6B ZB-V row is 1.75→1.88 samples/s/GPU (7.43%). Do not present it as matched-global-batch isolation. Table 8's V bubble rates are calculated, like Table 5. +- Appendix E/Table 10: optimizer post-validation versus allreduce synchronization, samples/s/GPU: 1.5B/8 GPUs/m24 14.5 vs 13.11; 6.2B/8/m24 4.32 vs 4.00; 14.6B/16/m48 1.81 vs 1.68; 28.3B/32/m96 0.99 vs 0.91. No measured rollback-rate sensitivity curve is reported. +- Appendix F/Table 11 keeps listed m while changing b, so global batch differs. It also prints middle m=32 for the 14.6B and 28.3B blocks, inconsistent with the main setup's 64/128. Preserve as a source ambiguity; use Table 6 for fixed-global-batch evidence. Table 11 includes cases where larger-b ZB-1p exceeds ZB-2p, a useful counter-signal. +- Appendix H/Table 12: at m≤p benefits persist but bubbles remain. Example 14.6B,p16,m4,b1: 0.39→0.52 samples/s/GPU, 19→20 GB, 1F1B→ZB-2p. This is throughput at small microbatch count, not elimination of all bubbles. diff --git a/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/sources.md b/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/sources.md new file mode 100644 index 000000000..2ef6f4e1c --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/sources.md @@ -0,0 +1,61 @@ +# Cross-resource reference evidence + +Initial scoped inspection: 2026-10-15. CR5 historical-source follow-up: +2026-10-30. No hardware, dependency installation, benchmark or checkpoint +implementation investigation was performed. + +## CR1 — DeepSpeed + +- Implementation: [offload_config.py](https://github.com/deepspeedai/DeepSpeed/blob/5f266e26d216a705d9c64cac88fb813cefdbac4b/deepspeed/runtime/zero/offload_config.py), + whole short configuration file (parameter config 20–51, optimizer config + 54–111). Revision `5f266e26d216a705d9c64cac88fb813cefdbac4b`. +- License: Apache-2.0, confirmed by file header and downloaded root LICENSE. + Mechanisms are paraphrased; no source code copied. +- [Official ZeRO-3 docs](https://deepspeed.readthedocs.io/en/latest/zero3.html), + offload overview and parameter/optimizer configuration fields only. Live + `latest` HTML SHA-256: + `56beb8cdf148ace7a279518e1abe8256fa767038b471b273aa8650e55b295f46`. + Retrieved fields match the inspected config, including `pin_memory=True`; + this is not a claim that the entire docs build matches the source SHA. +- `max_in_cpu` is explicitly parameter elements. `buffer_size` units are not + defined in this approved config excerpt or its live field description; + no runtime consumer was inspected, so no byte-budget formula or unsupported + element-unit assertion is supplied for that field. +- `pipeline_read/write` descriptions establish intended tiled optimizer overlap, + not dispatch or measured overlap. CPU Adam core share is gated by stage 3 and + super-offload. No NVMe/pinned-memory support is inferred for NPU hardware. + +## CR6 — Stas ML Engineering + +Revision `ee7517e0f562ff0e7d56c3e88c619d0c0c496ba7`; approved skill and targeted +performance sections only. Exact citations, adaptation license and limitations +are in the sibling Stas decision note linked directly from SKILL.md. +The source skill declares CC BY-SA 4.0; root `LICENSE` URL returned 404, so +that declaration, not a guessed root file, supplies attribution evidence. +Compute/network scripts were identified but not fetched or executed. + +## CR5 — MindSpeed + +The 2026-10-15 inspection was historical GitCode documentation only, with short +history ID `53193db8` and unresolved full pin/license. The 2026-10-30 follow-up +resolved `53193db8bf5def407c4041a9beb3f4c9e9773daf` through the original commit +link and official Ascend/MindSpeed GitHub source. Its root LICENSE supplies +default BSD-3-Clause terms with identified third-party exceptions; no later +documentation license replaces that historical evidence. + +The [historical case](mindspeed-historical.md) preserves the original date and +HTML hash. The [new bounded readset](mindspeed-source-readset.md) supports +selection versus validation, allocator/callback ownership, eligible shared-storage +rescue, explicit autograd-wrapper integration and conditional CPU-affinity +prerequisites. Complete search/cache behavior, current compatibility, numerical +correctness and measured benefit remain unqualified. Only independent mechanism +paraphrases are included; no upstream implementation or headline percentage is +copied. + +## Evidence distinctions + +DeepSpeed configuration is source code plus matched field documentation. +Stas material is attributed expert methodology. MindSpeed combines a historical +author-described case with bounded source observations at the recovered pin. +None is a measured InferRSI gain, a runtime qualification or an automatic +authorization to execute the original runbooks. diff --git a/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/stas-decision-notes.md b/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/stas-decision-notes.md new file mode 100644 index 000000000..d23929590 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/training-resource-budget/references/stas-decision-notes.md @@ -0,0 +1,41 @@ +# Stas Bekman scoped decision notes + +**Attribution:** Stas Bekman, *Machine Learning Engineering Open Book*, +[stas00/ml-engineering](https://github.com/stas00/ml-engineering/tree/ee7517e0f562ff0e7d56c3e88c619d0c0c496ba7), +revision `ee7517e0f562ff0e7d56c3e88c619d0c0c496ba7`. +The source skill explicitly declares **CC BY-SA 4.0**. This file is a shortened, +reorganized, paraphrased adaptation and is distributed under +[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/). Retain attribution, +the license link and change indication in downstream adaptations; apply +share-alike to adapted material. This notice does not relicense independent +DeepSpeed/MindSpeed materials or the repository as a whole. No endorsement by +Stas Bekman is implied. + +Inspected 2026-10-15. No source commands were executed and no numerical gains +were transferred. These are practitioner decision principles, not local tests. + +## Incremental rules and their limits + +| Signal or choice | Decision principle | Evidence boundary | +|---|---|---| +| MFU/HFU changed after recomputation or precision changes | Retain the FLOP-count convention, theoretical denominator and timed interval. HFU can count recomputation that MFU excludes. Pair ratios with useful workload throughput. | Different operation counts or forward/backward-only versus full-step timing invalidate direct comparison; mixed precision complicates a single peak denominator. | +| High short-burst matmul result | Separate a transient attainable ceiling from sustained compute under the node's shared power/cooling load. | Maximum-achievable and maximum-sustainable concepts are source methodology; no ceiling benchmark was run here. | +| Slow collective or confusing bandwidth figure | Retain collective kind, payload size, participating ranks and intra-node versus inter-node path. Keep algorithm bandwidth and bus bandwidth distinct. | The benchmark script is only a source entry point, not an audited or executed implementation. Host/device copies and shared-memory IPC do not qualify this network cell. | +| CPU-heavy offload slows a rank | Relate process and memory locality to the actual accelerator/NUMA topology; rank-local CPU work can expose cross-socket cost. | Source notes small effect for CPU-light work. Never copy example CPU IDs or claim universal improvement. No affinity was changed. | +| Intermittent synchronized-step stalls | Correlate per-rank garbage-collection events with collective arrival/step spikes before attributing them to the fabric. | Source proposes scheduled manual collection when automatic collection creates stragglers. That is an experiment lead, not permission to disable collection or proof of cause; track memory if later authorized. | + +## Exact readset + +- [skills/ml-engineering/SKILL.md](https://github.com/stas00/ml-engineering/blob/ee7517e0f562ff0e7d56c3e88c619d0c0c496ba7/skills/ml-engineering/SKILL.md#L21-L79): + attribution, bottleneck-first principles, compute/memory/network/NUMA/GC routing. +- [skills/evaluate-cluster/SKILL.md, first 100 lines](https://github.com/stas00/ml-engineering/blob/ee7517e0f562ff0e7d56c3e88c619d0c0c496ba7/skills/evaluate-cluster/SKILL.md#L1-L100): + compute ceiling and collective-bandwidth definitions only. Ignore its + instructions to update to latest, install tools or run a cluster campaign. +- [training/performance/README.md, 129–180](https://github.com/stas00/ml-engineering/blob/ee7517e0f562ff0e7d56c3e88c619d0c0c496ba7/training/performance/README.md#L129-L180): + MFU/HFU and comparison caveats. +- [NUMA, 748–789](https://github.com/stas00/ml-engineering/blob/ee7517e0f562ff0e7d56c3e88c619d0c0c496ba7/training/performance/README.md#L748-L789) + and [garbage collection, 1030–1047](https://github.com/stas00/ml-engineering/blob/ee7517e0f562ff0e7d56c3e88c619d0c0c496ba7/training/performance/README.md#L1030-L1047). + +Source fio, input-pipeline, recovery and other runbook sections were not mined. +No original benchmark script, raw experiment or historical model result was +validated. Concepts transfer only after workload/mode-specific qualification. diff --git a/src/inferrsi/knowledge/atoms/training-resource-budget.integration-notes.json b/src/inferrsi/knowledge/atoms/training-resource-budget.integration-notes.json new file mode 100644 index 000000000..e87eaed7d --- /dev/null +++ b/src/inferrsi/knowledge/atoms/training-resource-budget.integration-notes.json @@ -0,0 +1,75 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Choosing training offload and resource-budget changes from pinned DeepSpeed configuration, attributed expert diagnosis and a historical MindSpeed case, balancing accelerator capacity, CPU work, pinned RAM and local storage while keeping host/device transfer exposure distinct from collective network bottlenecks", + "prerequisites": "The source boundaries are read; garbage-collection or affinity changes, privileged memlock changes and delayed parameter updates each need separate approval, and the skill authorizes no newest-wheel installation, scheduler-priority change, benchmark or failure injection; historical MindSpeed reuse requires compatible allocator symbols, tracked swappable storage, sufficient host capacity and verified device/NUMA/CPU mapping, not merely the presence of npu-smi and lspci", + "input_contract": "State attributed to parameters, optimizer state, gradients or activations with its current memory tier, lifetime and next consumer; whether the failure is allocation capacity or throughput; a per-host budget for input buffers, checkpoint snapshots, offloaded state, OS cache and CPU workers with the actual ranks sharing the host; the host/device link recorded apart from collective traffic; the exact source version and enabled execution mode", + "produced_artifact": "A candidate decision record per proposal: the observed limiting interval and owning state or resource, source version and execution mode, capacity released and resources consumed with units and uncertainty, overlap readiness and mutation boundaries with expected contention, and the fixed-workload step and correctness evidence required for later validation", + "failure_modes": [ + "A change that lets the model fit is presented as a speedup, although it can slow each step", + "A tensor copied to CPU is taken as an InfiniBand/RoCE bottleneck, or CPU/NVMe offload is counted as network evidence", + "Parameter max_in_cpu is read as a byte or total-host-memory cap instead of an element count", + "NVMe optimizer placement is assumed to remove CPU optimizer demand", + "The parameter buffer-pool count is transplanted to the optimizer, or all optimizers are assumed to hold identical states", + "Configuration presence or schema documentation is taken as evidence that a knob or overlap actually ran", + "Ordinary overlap is taken as permission for delayed, stale parameter updates" + ], + "refusal_point": "Claims no hardware validation, measured gain or current NPU compatibility, keeps source support and extracted coverage separate from measured improvement, and does not reuse the MindSpeed headline gain; historical source observations do not establish current-stack compatibility, whole-model correctness or measured benefit" + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Original typed source inventory is not normalized; retain source identities and limits in the procedure/readsets.", + "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": "Pack C integration proposals", + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/planning/training-resource-budget/references/papers-20261015/INTEGRATION_NOTES.md", + "sha256": "c55c6ad2131ef788866411dcc7056f221420ebff30c95c6bc919b09a4818cb73" + }, + { + "type": "unknown", + "note": "Legacy provenance remains in procedure/readsets" + } + ], + "id": "training-resource-budget.integration-notes", + "kind": "knowledge", + "entrypoint": "INTEGRATION_NOTES.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/planning/training-resource-budget/references/papers-20261015/INTEGRATION_NOTES.md", + "byte_range": [ + 0, + 7368 + ], + "sha256": "c55c6ad2131ef788866411dcc7056f221420ebff30c95c6bc919b09a4818cb73" + } + } + }, + "content": { + "INTEGRATION_NOTES.md": { + "path": "playbooks/training-resource-budget/references/papers-20261015/INTEGRATION_NOTES.md" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/training-resource-budget.mindspeed-historical.json b/src/inferrsi/knowledge/atoms/training-resource-budget.mindspeed-historical.json new file mode 100644 index 000000000..b9d1f9c4a --- /dev/null +++ b/src/inferrsi/knowledge/atoms/training-resource-budget.mindspeed-historical.json @@ -0,0 +1,75 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Choosing training offload and resource-budget changes from pinned DeepSpeed configuration, attributed expert diagnosis and a historical MindSpeed case, balancing accelerator capacity, CPU work, pinned RAM and local storage while keeping host/device transfer exposure distinct from collective network bottlenecks", + "prerequisites": "The source boundaries are read; garbage-collection or affinity changes, privileged memlock changes and delayed parameter updates each need separate approval, and the skill authorizes no newest-wheel installation, scheduler-priority change, benchmark or failure injection; historical MindSpeed reuse requires compatible allocator symbols, tracked swappable storage, sufficient host capacity and verified device/NUMA/CPU mapping, not merely the presence of npu-smi and lspci", + "input_contract": "State attributed to parameters, optimizer state, gradients or activations with its current memory tier, lifetime and next consumer; whether the failure is allocation capacity or throughput; a per-host budget for input buffers, checkpoint snapshots, offloaded state, OS cache and CPU workers with the actual ranks sharing the host; the host/device link recorded apart from collective traffic; the exact source version and enabled execution mode", + "produced_artifact": "A candidate decision record per proposal: the observed limiting interval and owning state or resource, source version and execution mode, capacity released and resources consumed with units and uncertainty, overlap readiness and mutation boundaries with expected contention, and the fixed-workload step and correctness evidence required for later validation", + "failure_modes": [ + "A change that lets the model fit is presented as a speedup, although it can slow each step", + "A tensor copied to CPU is taken as an InfiniBand/RoCE bottleneck, or CPU/NVMe offload is counted as network evidence", + "Parameter max_in_cpu is read as a byte or total-host-memory cap instead of an element count", + "NVMe optimizer placement is assumed to remove CPU optimizer demand", + "The parameter buffer-pool count is transplanted to the optimizer, or all optimizers are assumed to hold identical states", + "Configuration presence or schema documentation is taken as evidence that a knob or overlap actually ran", + "Ordinary overlap is taken as permission for delayed, stale parameter updates" + ], + "refusal_point": "Claims no hardware validation, measured gain or current NPU compatibility, keeps source support and extracted coverage separate from measured improvement, and does not reuse the MindSpeed headline gain; historical source observations do not establish current-stack compatibility, whole-model correctness or measured benefit" + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Original typed source inventory is not normalized; retain source identities and limits in the procedure/readsets.", + "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": "Historical MindSpeed adaptive-memory case", + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/planning/training-resource-budget/references/mindspeed-historical.md", + "sha256": "ad65c27f278c3d0ca3599a7630c02d3e529477a05b71b7703bd2d75f0d8fdd2c" + }, + { + "type": "unknown", + "note": "Legacy provenance remains in procedure/readsets" + } + ], + "id": "training-resource-budget.mindspeed-historical", + "kind": "knowledge", + "entrypoint": "mindspeed-historical.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/planning/training-resource-budget/references/mindspeed-historical.md", + "byte_range": [ + 0, + 7580 + ], + "sha256": "ad65c27f278c3d0ca3599a7630c02d3e529477a05b71b7703bd2d75f0d8fdd2c" + } + } + }, + "content": { + "mindspeed-historical.md": { + "path": "playbooks/training-resource-budget/references/mindspeed-historical.md" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/training-resource-budget.mindspeed-source-readset.json b/src/inferrsi/knowledge/atoms/training-resource-budget.mindspeed-source-readset.json new file mode 100644 index 000000000..5279be998 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/training-resource-budget.mindspeed-source-readset.json @@ -0,0 +1,75 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Choosing training offload and resource-budget changes from pinned DeepSpeed configuration, attributed expert diagnosis and a historical MindSpeed case, balancing accelerator capacity, CPU work, pinned RAM and local storage while keeping host/device transfer exposure distinct from collective network bottlenecks", + "prerequisites": "The source boundaries are read; garbage-collection or affinity changes, privileged memlock changes and delayed parameter updates each need separate approval, and the skill authorizes no newest-wheel installation, scheduler-priority change, benchmark or failure injection; historical MindSpeed reuse requires compatible allocator symbols, tracked swappable storage, sufficient host capacity and verified device/NUMA/CPU mapping, not merely the presence of npu-smi and lspci", + "input_contract": "State attributed to parameters, optimizer state, gradients or activations with its current memory tier, lifetime and next consumer; whether the failure is allocation capacity or throughput; a per-host budget for input buffers, checkpoint snapshots, offloaded state, OS cache and CPU workers with the actual ranks sharing the host; the host/device link recorded apart from collective traffic; the exact source version and enabled execution mode", + "produced_artifact": "A candidate decision record per proposal: the observed limiting interval and owning state or resource, source version and execution mode, capacity released and resources consumed with units and uncertainty, overlap readiness and mutation boundaries with expected contention, and the fixed-workload step and correctness evidence required for later validation", + "failure_modes": [ + "A change that lets the model fit is presented as a speedup, although it can slow each step", + "A tensor copied to CPU is taken as an InfiniBand/RoCE bottleneck, or CPU/NVMe offload is counted as network evidence", + "Parameter max_in_cpu is read as a byte or total-host-memory cap instead of an element count", + "NVMe optimizer placement is assumed to remove CPU optimizer demand", + "The parameter buffer-pool count is transplanted to the optimizer, or all optimizers are assumed to hold identical states", + "Configuration presence or schema documentation is taken as evidence that a knob or overlap actually ran", + "Ordinary overlap is taken as permission for delayed, stale parameter updates" + ], + "refusal_point": "Claims no hardware validation, measured gain or current NPU compatibility, keeps source support and extracted coverage separate from measured improvement, and does not reuse the MindSpeed headline gain; historical source observations do not establish current-stack compatibility, whole-model correctness or measured benefit" + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Original typed source inventory is not normalized; retain source identities and limits in the procedure/readsets.", + "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": "MindSpeed historical source readset", + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/planning/training-resource-budget/references/mindspeed-source-readset.md", + "sha256": "4462d69ed6a941a03639c756968be3ce54f947e51f6ca618f4fb1cd43b643b35" + }, + { + "type": "unknown", + "note": "Legacy provenance remains in procedure/readsets" + } + ], + "id": "training-resource-budget.mindspeed-source-readset", + "kind": "knowledge", + "entrypoint": "mindspeed-source-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/planning/training-resource-budget/references/mindspeed-source-readset.md", + "byte_range": [ + 0, + 7158 + ], + "sha256": "4462d69ed6a941a03639c756968be3ce54f947e51f6ca618f4fb1cd43b643b35" + } + } + }, + "content": { + "mindspeed-source-readset.md": { + "path": "playbooks/training-resource-budget/references/mindspeed-source-readset.md" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/training-resource-budget.offload-delta.json b/src/inferrsi/knowledge/atoms/training-resource-budget.offload-delta.json new file mode 100644 index 000000000..3d25c44d6 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/training-resource-budget.offload-delta.json @@ -0,0 +1,75 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Choosing training offload and resource-budget changes from pinned DeepSpeed configuration, attributed expert diagnosis and a historical MindSpeed case, balancing accelerator capacity, CPU work, pinned RAM and local storage while keeping host/device transfer exposure distinct from collective network bottlenecks", + "prerequisites": "The source boundaries are read; garbage-collection or affinity changes, privileged memlock changes and delayed parameter updates each need separate approval, and the skill authorizes no newest-wheel installation, scheduler-priority change, benchmark or failure injection; historical MindSpeed reuse requires compatible allocator symbols, tracked swappable storage, sufficient host capacity and verified device/NUMA/CPU mapping, not merely the presence of npu-smi and lspci", + "input_contract": "State attributed to parameters, optimizer state, gradients or activations with its current memory tier, lifetime and next consumer; whether the failure is allocation capacity or throughput; a per-host budget for input buffers, checkpoint snapshots, offloaded state, OS cache and CPU workers with the actual ranks sharing the host; the host/device link recorded apart from collective traffic; the exact source version and enabled execution mode", + "produced_artifact": "A candidate decision record per proposal: the observed limiting interval and owning state or resource, source version and execution mode, capacity released and resources consumed with units and uncertainty, overlap readiness and mutation boundaries with expected contention, and the fixed-workload step and correctness evidence required for later validation", + "failure_modes": [ + "A change that lets the model fit is presented as a speedup, although it can slow each step", + "A tensor copied to CPU is taken as an InfiniBand/RoCE bottleneck, or CPU/NVMe offload is counted as network evidence", + "Parameter max_in_cpu is read as a byte or total-host-memory cap instead of an element count", + "NVMe optimizer placement is assumed to remove CPU optimizer demand", + "The parameter buffer-pool count is transplanted to the optimizer, or all optimizers are assumed to hold identical states", + "Configuration presence or schema documentation is taken as evidence that a knob or overlap actually ran", + "Ordinary overlap is taken as permission for delayed, stale parameter updates" + ], + "refusal_point": "Claims no hardware validation, measured gain or current NPU compatibility, keeps source support and extracted coverage separate from measured improvement, and does not reuse the MindSpeed headline gain; historical source observations do not establish current-stack compatibility, whole-model correctness or measured benefit" + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Original typed source inventory is not normalized; retain source identities and limits in the procedure/readsets.", + "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": "Incremental extension to training-offload knowledge", + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/planning/training-resource-budget/references/papers-20261015/knowledge/offload-delta.md", + "sha256": "f8740fc5c8bbbe5ac13ff1cfec7ca499569d0b46e8cd56cf1f5a44c3a5e72242" + }, + { + "type": "unknown", + "note": "Legacy provenance remains in procedure/readsets" + } + ], + "id": "training-resource-budget.offload-delta", + "kind": "knowledge", + "entrypoint": "offload-delta.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/planning/training-resource-budget/references/papers-20261015/knowledge/offload-delta.md", + "byte_range": [ + 0, + 2026 + ], + "sha256": "f8740fc5c8bbbe5ac13ff1cfec7ca499569d0b46e8cd56cf1f5a44c3a5e72242" + } + } + }, + "content": { + "offload-delta.md": { + "path": "playbooks/training-resource-budget/references/papers-20261015/knowledge/offload-delta.md" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/training-resource-budget.original.json b/src/inferrsi/knowledge/atoms/training-resource-budget.original.json new file mode 100644 index 000000000..9c0d226b2 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/training-resource-budget.original.json @@ -0,0 +1,104 @@ +{ + "authority": "checkout", + "metadata": { + "id": "training-resource-budget.original", + "kind": "knowledge", + "entrypoint": "guide.md", + "title": "Choose training offload and resource-budget changes using pinned DeepSpeed configuration, attributed expert diagnosis and a historical MindSpeed case. Balance accelerator capacity, CPU work, pinned RAM and local storage; keep host/device transfer exposure distinct from collective network bottlenecks.\n", + "origin": [ + "external" + ], + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/planning/training-resource-budget/SKILL.md", + "sha256": "e8adf9d115975844d6c7a1b1809c1cbc2baeabc1318198a777050f159a0fe8e2" + }, + { + "type": "unknown", + "note": "Legacy provenance remains in procedure/readsets" + } + ], + "applicability": { + "scope": "Choosing training offload and resource-budget changes from pinned DeepSpeed configuration, attributed expert diagnosis and a historical MindSpeed case, balancing accelerator capacity, CPU work, pinned RAM and local storage while keeping host/device transfer exposure distinct from collective network bottlenecks", + "prerequisites": "The source boundaries are read; garbage-collection or affinity changes, privileged memlock changes and delayed parameter updates each need separate approval, and the skill authorizes no newest-wheel installation, scheduler-priority change, benchmark or failure injection; historical MindSpeed reuse requires compatible allocator symbols, tracked swappable storage, sufficient host capacity and verified device/NUMA/CPU mapping, not merely the presence of npu-smi and lspci", + "input_contract": "State attributed to parameters, optimizer state, gradients or activations with its current memory tier, lifetime and next consumer; whether the failure is allocation capacity or throughput; a per-host budget for input buffers, checkpoint snapshots, offloaded state, OS cache and CPU workers with the actual ranks sharing the host; the host/device link recorded apart from collective traffic; the exact source version and enabled execution mode", + "produced_artifact": "A candidate decision record per proposal: the observed limiting interval and owning state or resource, source version and execution mode, capacity released and resources consumed with units and uncertainty, overlap readiness and mutation boundaries with expected contention, and the fixed-workload step and correctness evidence required for later validation", + "failure_modes": [ + "A change that lets the model fit is presented as a speedup, although it can slow each step", + "A tensor copied to CPU is taken as an InfiniBand/RoCE bottleneck, or CPU/NVMe offload is counted as network evidence", + "Parameter max_in_cpu is read as a byte or total-host-memory cap instead of an element count", + "NVMe optimizer placement is assumed to remove CPU optimizer demand", + "The parameter buffer-pool count is transplanted to the optimizer, or all optimizers are assumed to hold identical states", + "Configuration presence or schema documentation is taken as evidence that a knob or overlap actually ran", + "Ordinary overlap is taken as permission for delayed, stale parameter updates" + ], + "refusal_point": "Claims no hardware validation, measured gain or current NPU compatibility, keeps source support and extracted coverage separate from measured improvement, and does not reuse the MindSpeed headline gain; historical source observations do not establish current-stack compatibility, whole-model correctness or measured benefit" + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Original typed source inventory is not normalized; retain source identities and limits in the procedure/readsets.", + "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/planning/training-resource-budget/SKILL.md", + "byte_range": [ + 0, + 12306 + ], + "sha256": "e8adf9d115975844d6c7a1b1809c1cbc2baeabc1318198a777050f159a0fe8e2" + } + } + }, + "content": { + "guide.md": { + "path": "playbooks/training-resource-budget.md" + } + }, + "parts": { + "navigation": { + "skill_section": "navigation", + "layer": "L0", + "byte_range": [ + 0, + 356 + ], + "sha256": "9c1682e170d92bea942cf3e7dcd886634df374d36a96a795b85be90e2deefd4b" + }, + "decision": { + "skill_section": "decision", + "layer": "L1", + "byte_range": [ + 0, + 4973 + ], + "sha256": "c430e1e846bb7aec1a91b42a4588f05cc44816233cb1832c9c3fa106c2848dc4" + }, + "procedure": { + "skill_section": "procedure", + "layer": "L2", + "byte_range": [ + 4973, + 12306 + ], + "sha256": "7a7316954032fb9cd4b6506f9f7b63ef72afc2a34ac5d55448850d18e020097a" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/training-resource-budget.paper-grounded-cases.json b/src/inferrsi/knowledge/atoms/training-resource-budget.paper-grounded-cases.json new file mode 100644 index 000000000..7e70b19a2 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/training-resource-budget.paper-grounded-cases.json @@ -0,0 +1,75 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Choosing training offload and resource-budget changes from pinned DeepSpeed configuration, attributed expert diagnosis and a historical MindSpeed case, balancing accelerator capacity, CPU work, pinned RAM and local storage while keeping host/device transfer exposure distinct from collective network bottlenecks", + "prerequisites": "The source boundaries are read; garbage-collection or affinity changes, privileged memlock changes and delayed parameter updates each need separate approval, and the skill authorizes no newest-wheel installation, scheduler-priority change, benchmark or failure injection; historical MindSpeed reuse requires compatible allocator symbols, tracked swappable storage, sufficient host capacity and verified device/NUMA/CPU mapping, not merely the presence of npu-smi and lspci", + "input_contract": "State attributed to parameters, optimizer state, gradients or activations with its current memory tier, lifetime and next consumer; whether the failure is allocation capacity or throughput; a per-host budget for input buffers, checkpoint snapshots, offloaded state, OS cache and CPU workers with the actual ranks sharing the host; the host/device link recorded apart from collective traffic; the exact source version and enabled execution mode", + "produced_artifact": "A candidate decision record per proposal: the observed limiting interval and owning state or resource, source version and execution mode, capacity released and resources consumed with units and uncertainty, overlap readiness and mutation boundaries with expected contention, and the fixed-workload step and correctness evidence required for later validation", + "failure_modes": [ + "A change that lets the model fit is presented as a speedup, although it can slow each step", + "A tensor copied to CPU is taken as an InfiniBand/RoCE bottleneck, or CPU/NVMe offload is counted as network evidence", + "Parameter max_in_cpu is read as a byte or total-host-memory cap instead of an element count", + "NVMe optimizer placement is assumed to remove CPU optimizer demand", + "The parameter buffer-pool count is transplanted to the optimizer, or all optimizers are assumed to hold identical states", + "Configuration presence or schema documentation is taken as evidence that a knob or overlap actually ran", + "Ordinary overlap is taken as permission for delayed, stale parameter updates" + ], + "refusal_point": "Claims no hardware validation, measured gain or current NPU compatibility, keeps source support and extracted coverage separate from measured improvement, and does not reuse the MindSpeed headline gain; historical source observations do not establish current-stack compatibility, whole-model correctness or measured benefit" + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Original typed source inventory is not normalized; retain source identities and limits in the procedure/readsets.", + "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": "Paper-grounded review cases", + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/planning/training-resource-budget/references/papers-20261015/cases/paper-grounded-cases.md", + "sha256": "19bd25b1a944adb2351ebc6b1d795150ea033041a44f6cc261e881677812a101" + }, + { + "type": "unknown", + "note": "Legacy provenance remains in procedure/readsets" + } + ], + "id": "training-resource-budget.paper-grounded-cases", + "kind": "knowledge", + "entrypoint": "paper-grounded-cases.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/planning/training-resource-budget/references/papers-20261015/cases/paper-grounded-cases.md", + "byte_range": [ + 0, + 5649 + ], + "sha256": "19bd25b1a944adb2351ebc6b1d795150ea033041a44f6cc261e881677812a101" + } + } + }, + "content": { + "paper-grounded-cases.md": { + "path": "playbooks/training-resource-budget/references/papers-20261015/cases/paper-grounded-cases.md" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/training-resource-budget.source-readset.json b/src/inferrsi/knowledge/atoms/training-resource-budget.source-readset.json new file mode 100644 index 000000000..d02496ce0 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/training-resource-budget.source-readset.json @@ -0,0 +1,75 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Choosing training offload and resource-budget changes from pinned DeepSpeed configuration, attributed expert diagnosis and a historical MindSpeed case, balancing accelerator capacity, CPU work, pinned RAM and local storage while keeping host/device transfer exposure distinct from collective network bottlenecks", + "prerequisites": "The source boundaries are read; garbage-collection or affinity changes, privileged memlock changes and delayed parameter updates each need separate approval, and the skill authorizes no newest-wheel installation, scheduler-priority change, benchmark or failure injection; historical MindSpeed reuse requires compatible allocator symbols, tracked swappable storage, sufficient host capacity and verified device/NUMA/CPU mapping, not merely the presence of npu-smi and lspci", + "input_contract": "State attributed to parameters, optimizer state, gradients or activations with its current memory tier, lifetime and next consumer; whether the failure is allocation capacity or throughput; a per-host budget for input buffers, checkpoint snapshots, offloaded state, OS cache and CPU workers with the actual ranks sharing the host; the host/device link recorded apart from collective traffic; the exact source version and enabled execution mode", + "produced_artifact": "A candidate decision record per proposal: the observed limiting interval and owning state or resource, source version and execution mode, capacity released and resources consumed with units and uncertainty, overlap readiness and mutation boundaries with expected contention, and the fixed-workload step and correctness evidence required for later validation", + "failure_modes": [ + "A change that lets the model fit is presented as a speedup, although it can slow each step", + "A tensor copied to CPU is taken as an InfiniBand/RoCE bottleneck, or CPU/NVMe offload is counted as network evidence", + "Parameter max_in_cpu is read as a byte or total-host-memory cap instead of an element count", + "NVMe optimizer placement is assumed to remove CPU optimizer demand", + "The parameter buffer-pool count is transplanted to the optimizer, or all optimizers are assumed to hold identical states", + "Configuration presence or schema documentation is taken as evidence that a knob or overlap actually ran", + "Ordinary overlap is taken as permission for delayed, stale parameter updates" + ], + "refusal_point": "Claims no hardware validation, measured gain or current NPU compatibility, keeps source support and extracted coverage separate from measured improvement, and does not reuse the MindSpeed headline gain; historical source observations do not establish current-stack compatibility, whole-model correctness or measured benefit" + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Original typed source inventory is not normalized; retain source identities and limits in the procedure/readsets.", + "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": "Pack C: pinned sources and actual readset", + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/planning/training-resource-budget/references/papers-20261015/references/source-readset.md", + "sha256": "2a5c166767f56fa47e7eba7386f1f36da8cb73702e5b5bbe14d6a456ca9ebfae" + }, + { + "type": "unknown", + "note": "Legacy provenance remains in procedure/readsets" + } + ], + "id": "training-resource-budget.source-readset", + "kind": "knowledge", + "entrypoint": "source-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/planning/training-resource-budget/references/papers-20261015/references/source-readset.md", + "byte_range": [ + 0, + 22946 + ], + "sha256": "2a5c166767f56fa47e7eba7386f1f36da8cb73702e5b5bbe14d6a456ca9ebfae" + } + } + }, + "content": { + "source-readset.md": { + "path": "playbooks/training-resource-budget/references/papers-20261015/references/source-readset.md" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/training-resource-budget.sources.json b/src/inferrsi/knowledge/atoms/training-resource-budget.sources.json new file mode 100644 index 000000000..c730102a7 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/training-resource-budget.sources.json @@ -0,0 +1,75 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Choosing training offload and resource-budget changes from pinned DeepSpeed configuration, attributed expert diagnosis and a historical MindSpeed case, balancing accelerator capacity, CPU work, pinned RAM and local storage while keeping host/device transfer exposure distinct from collective network bottlenecks", + "prerequisites": "The source boundaries are read; garbage-collection or affinity changes, privileged memlock changes and delayed parameter updates each need separate approval, and the skill authorizes no newest-wheel installation, scheduler-priority change, benchmark or failure injection; historical MindSpeed reuse requires compatible allocator symbols, tracked swappable storage, sufficient host capacity and verified device/NUMA/CPU mapping, not merely the presence of npu-smi and lspci", + "input_contract": "State attributed to parameters, optimizer state, gradients or activations with its current memory tier, lifetime and next consumer; whether the failure is allocation capacity or throughput; a per-host budget for input buffers, checkpoint snapshots, offloaded state, OS cache and CPU workers with the actual ranks sharing the host; the host/device link recorded apart from collective traffic; the exact source version and enabled execution mode", + "produced_artifact": "A candidate decision record per proposal: the observed limiting interval and owning state or resource, source version and execution mode, capacity released and resources consumed with units and uncertainty, overlap readiness and mutation boundaries with expected contention, and the fixed-workload step and correctness evidence required for later validation", + "failure_modes": [ + "A change that lets the model fit is presented as a speedup, although it can slow each step", + "A tensor copied to CPU is taken as an InfiniBand/RoCE bottleneck, or CPU/NVMe offload is counted as network evidence", + "Parameter max_in_cpu is read as a byte or total-host-memory cap instead of an element count", + "NVMe optimizer placement is assumed to remove CPU optimizer demand", + "The parameter buffer-pool count is transplanted to the optimizer, or all optimizers are assumed to hold identical states", + "Configuration presence or schema documentation is taken as evidence that a knob or overlap actually ran", + "Ordinary overlap is taken as permission for delayed, stale parameter updates" + ], + "refusal_point": "Claims no hardware validation, measured gain or current NPU compatibility, keeps source support and extracted coverage separate from measured improvement, and does not reuse the MindSpeed headline gain; historical source observations do not establish current-stack compatibility, whole-model correctness or measured benefit" + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Original typed source inventory is not normalized; retain source identities and limits in the procedure/readsets.", + "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": "Cross-resource reference evidence", + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/planning/training-resource-budget/references/sources.md", + "sha256": "53d70671a183de4aaa3369f9caf2383a23b6f8a0a7b04464a8d8a639150afc6a" + }, + { + "type": "unknown", + "note": "Legacy provenance remains in procedure/readsets" + } + ], + "id": "training-resource-budget.sources", + "kind": "knowledge", + "entrypoint": "sources.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/planning/training-resource-budget/references/sources.md", + "byte_range": [ + 0, + 3502 + ], + "sha256": "53d70671a183de4aaa3369f9caf2383a23b6f8a0a7b04464a8d8a639150afc6a" + } + } + }, + "content": { + "sources.md": { + "path": "playbooks/training-resource-budget/references/sources.md" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/training-resource-budget.stas-decision-notes.json b/src/inferrsi/knowledge/atoms/training-resource-budget.stas-decision-notes.json new file mode 100644 index 000000000..c6ff0a6ae --- /dev/null +++ b/src/inferrsi/knowledge/atoms/training-resource-budget.stas-decision-notes.json @@ -0,0 +1,94 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Choosing training offload and resource-budget changes from pinned DeepSpeed configuration, attributed expert diagnosis and a historical MindSpeed case, balancing accelerator capacity, CPU work, pinned RAM and local storage while keeping host/device transfer exposure distinct from collective network bottlenecks", + "prerequisites": "The source boundaries are read; garbage-collection or affinity changes, privileged memlock changes and delayed parameter updates each need separate approval, and the skill authorizes no newest-wheel installation, scheduler-priority change, benchmark or failure injection; historical MindSpeed reuse requires compatible allocator symbols, tracked swappable storage, sufficient host capacity and verified device/NUMA/CPU mapping, not merely the presence of npu-smi and lspci", + "input_contract": "State attributed to parameters, optimizer state, gradients or activations with its current memory tier, lifetime and next consumer; whether the failure is allocation capacity or throughput; a per-host budget for input buffers, checkpoint snapshots, offloaded state, OS cache and CPU workers with the actual ranks sharing the host; the host/device link recorded apart from collective traffic; the exact source version and enabled execution mode", + "produced_artifact": "A candidate decision record per proposal: the observed limiting interval and owning state or resource, source version and execution mode, capacity released and resources consumed with units and uncertainty, overlap readiness and mutation boundaries with expected contention, and the fixed-workload step and correctness evidence required for later validation", + "failure_modes": [ + "A change that lets the model fit is presented as a speedup, although it can slow each step", + "A tensor copied to CPU is taken as an InfiniBand/RoCE bottleneck, or CPU/NVMe offload is counted as network evidence", + "Parameter max_in_cpu is read as a byte or total-host-memory cap instead of an element count", + "NVMe optimizer placement is assumed to remove CPU optimizer demand", + "The parameter buffer-pool count is transplanted to the optimizer, or all optimizers are assumed to hold identical states", + "Configuration presence or schema documentation is taken as evidence that a knob or overlap actually ran", + "Ordinary overlap is taken as permission for delayed, stale parameter updates" + ], + "refusal_point": "Claims no hardware validation, measured gain or current NPU compatibility, keeps source support and extracted coverage separate from measured improvement, and does not reuse the MindSpeed headline gain; historical source observations do not establish current-stack compatibility, whole-model correctness or measured benefit" + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Original typed source inventory is not normalized; retain source identities and limits in the procedure/readsets.", + "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", + "repo": "https://github.com/stas00/ml-engineering", + "commit": "ee7517e0f562ff0e7d56c3e88c619d0c0c496ba7", + "author": "Stas Bekman", + "title": "Machine Learning Engineering Open Book", + "license": "CC-BY-SA-4.0", + "license_url": "https://creativecommons.org/licenses/by-sa/4.0/" + } + ], + "empirical_validation": "not_run", + "title": "Stas Bekman scoped decision notes", + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/planning/training-resource-budget/references/stas-decision-notes.md", + "sha256": "f1a993e6c4ca9a035a2effcaf5500081f227b0cc56cc885a6b22fda0041fc744" + }, + { + "type": "unknown", + "note": "Legacy provenance remains in procedure/readsets" + }, + { + "type": "git", + "repo": "https://github.com/stas00/ml-engineering", + "commit": "ee7517e0f562ff0e7d56c3e88c619d0c0c496ba7", + "author": "Stas Bekman", + "title": "Machine Learning Engineering Open Book", + "license": "CC-BY-SA-4.0", + "license_url": "https://creativecommons.org/licenses/by-sa/4.0/" + } + ], + "id": "training-resource-budget.stas-decision-notes", + "kind": "knowledge", + "entrypoint": "stas-decision-notes.md", + "atom": { + "when": {}, + "license": "CC-BY-SA-4.0", + "permissions": { + "read": true, + "retain": true, + "redistribute": true + }, + "layer": "L3", + "source_span": { + "source_index": 0, + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/planning/training-resource-budget/references/stas-decision-notes.md", + "byte_range": [ + 0, + 4086 + ], + "sha256": "f1a993e6c4ca9a035a2effcaf5500081f227b0cc56cc885a6b22fda0041fc744" + } + } + }, + "content": { + "stas-decision-notes.md": { + "path": "playbooks/training-resource-budget/references/stas-decision-notes.md" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/training-resource-budget.training-memory-scheduling.json b/src/inferrsi/knowledge/atoms/training-resource-budget.training-memory-scheduling.json new file mode 100644 index 000000000..ce2084d13 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/training-resource-budget.training-memory-scheduling.json @@ -0,0 +1,75 @@ +{ + "authority": "checkout", + "metadata": { + "origin": [ + "external" + ], + "applicability": { + "scope": "Choosing training offload and resource-budget changes from pinned DeepSpeed configuration, attributed expert diagnosis and a historical MindSpeed case, balancing accelerator capacity, CPU work, pinned RAM and local storage while keeping host/device transfer exposure distinct from collective network bottlenecks", + "prerequisites": "The source boundaries are read; garbage-collection or affinity changes, privileged memlock changes and delayed parameter updates each need separate approval, and the skill authorizes no newest-wheel installation, scheduler-priority change, benchmark or failure injection; historical MindSpeed reuse requires compatible allocator symbols, tracked swappable storage, sufficient host capacity and verified device/NUMA/CPU mapping, not merely the presence of npu-smi and lspci", + "input_contract": "State attributed to parameters, optimizer state, gradients or activations with its current memory tier, lifetime and next consumer; whether the failure is allocation capacity or throughput; a per-host budget for input buffers, checkpoint snapshots, offloaded state, OS cache and CPU workers with the actual ranks sharing the host; the host/device link recorded apart from collective traffic; the exact source version and enabled execution mode", + "produced_artifact": "A candidate decision record per proposal: the observed limiting interval and owning state or resource, source version and execution mode, capacity released and resources consumed with units and uncertainty, overlap readiness and mutation boundaries with expected contention, and the fixed-workload step and correctness evidence required for later validation", + "failure_modes": [ + "A change that lets the model fit is presented as a speedup, although it can slow each step", + "A tensor copied to CPU is taken as an InfiniBand/RoCE bottleneck, or CPU/NVMe offload is counted as network evidence", + "Parameter max_in_cpu is read as a byte or total-host-memory cap instead of an element count", + "NVMe optimizer placement is assumed to remove CPU optimizer demand", + "The parameter buffer-pool count is transplanted to the optimizer, or all optimizers are assumed to hold identical states", + "Configuration presence or schema documentation is taken as evidence that a knob or overlap actually ran", + "Ordinary overlap is taken as permission for delayed, stale parameter updates" + ], + "refusal_point": "Claims no hardware validation, measured gain or current NPU compatibility, keeps source support and extracted coverage separate from measured improvement, and does not reuse the MindSpeed headline gain; historical source observations do not establish current-stack compatibility, whole-model correctness or measured benefit" + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Original typed source inventory is not normalized; retain source identities and limits in the procedure/readsets.", + "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": "Training memory and scheduling: incremental mechanisms", + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/planning/training-resource-budget/references/papers-20261015/notes/training-memory-scheduling.md", + "sha256": "9aa6d3e01452dff95c8a8940ff62ead8c146ce215c9175b78c9f2ef508a7b2de" + }, + { + "type": "unknown", + "note": "Legacy provenance remains in procedure/readsets" + } + ], + "id": "training-resource-budget.training-memory-scheduling", + "kind": "knowledge", + "entrypoint": "training-memory-scheduling.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/planning/training-resource-budget/references/papers-20261015/notes/training-memory-scheduling.md", + "byte_range": [ + 0, + 18660 + ], + "sha256": "9aa6d3e01452dff95c8a8940ff62ead8c146ce215c9175b78c9f2ef508a7b2de" + } + } + }, + "content": { + "training-memory-scheduling.md": { + "path": "playbooks/training-resource-budget/references/papers-20261015/notes/training-memory-scheduling.md" + } + } +} diff --git a/src/inferrsi/knowledge/compositions/training-resource-budget.json b/src/inferrsi/knowledge/compositions/training-resource-budget.json new file mode 100644 index 000000000..e6a405480 --- /dev/null +++ b/src/inferrsi/knowledge/compositions/training-resource-budget.json @@ -0,0 +1,176 @@ +{ + "authority": "checkout", + "metadata": { + "id": "training-resource-budget", + "kind": "skill", + "entrypoint": "playbooks/planning/training-resource-budget/SKILL.md", + "title": "Choose training offload and resource-budget changes using pinned DeepSpeed configuration, attributed expert diagnosis and a historical MindSpeed case. Balance accelerator capacity, CPU work, pinned RAM and local storage; keep host/device transfer exposure distinct from collective network bottlenecks.\n", + "origin": [ + "external" + ], + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/planning/training-resource-budget/SKILL.md", + "sha256": "e8adf9d115975844d6c7a1b1809c1cbc2baeabc1318198a777050f159a0fe8e2" + }, + { + "type": "unknown", + "note": "Legacy provenance remains in procedure/readsets" + } + ], + "applicability": { + "scope": "Choosing training offload and resource-budget changes from pinned DeepSpeed configuration, attributed expert diagnosis and a historical MindSpeed case, balancing accelerator capacity, CPU work, pinned RAM and local storage while keeping host/device transfer exposure distinct from collective network bottlenecks", + "prerequisites": "The source boundaries are read; garbage-collection or affinity changes, privileged memlock changes and delayed parameter updates each need separate approval, and the skill authorizes no newest-wheel installation, scheduler-priority change, benchmark or failure injection; historical MindSpeed reuse requires compatible allocator symbols, tracked swappable storage, sufficient host capacity and verified device/NUMA/CPU mapping, not merely the presence of npu-smi and lspci", + "input_contract": "State attributed to parameters, optimizer state, gradients or activations with its current memory tier, lifetime and next consumer; whether the failure is allocation capacity or throughput; a per-host budget for input buffers, checkpoint snapshots, offloaded state, OS cache and CPU workers with the actual ranks sharing the host; the host/device link recorded apart from collective traffic; the exact source version and enabled execution mode", + "produced_artifact": "A candidate decision record per proposal: the observed limiting interval and owning state or resource, source version and execution mode, capacity released and resources consumed with units and uncertainty, overlap readiness and mutation boundaries with expected contention, and the fixed-workload step and correctness evidence required for later validation", + "failure_modes": [ + "A change that lets the model fit is presented as a speedup, although it can slow each step", + "A tensor copied to CPU is taken as an InfiniBand/RoCE bottleneck, or CPU/NVMe offload is counted as network evidence", + "Parameter max_in_cpu is read as a byte or total-host-memory cap instead of an element count", + "NVMe optimizer placement is assumed to remove CPU optimizer demand", + "The parameter buffer-pool count is transplanted to the optimizer, or all optimizers are assumed to hold identical states", + "Configuration presence or schema documentation is taken as evidence that a knob or overlap actually ran", + "Ordinary overlap is taken as permission for delayed, stale parameter updates" + ], + "refusal_point": "Claims no hardware validation, measured gain or current NPU compatibility, keeps source support and extracted coverage separate from measured improvement, and does not reuse the MindSpeed headline gain; historical source observations do not establish current-stack compatibility, whole-model correctness or measured benefit" + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Original typed source inventory is not normalized; retain source identities and limits in the procedure/readsets.", + "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/planning/training-resource-budget/SKILL.md", + "playbooks/planning/training-resource-budget/references/mindspeed-historical.md", + "playbooks/planning/training-resource-budget/references/mindspeed-source-readset.md", + "playbooks/planning/training-resource-budget/references/papers-20261015/INTEGRATION_NOTES.md", + "playbooks/planning/training-resource-budget/references/papers-20261015/cases/paper-grounded-cases.md", + "playbooks/planning/training-resource-budget/references/papers-20261015/knowledge/offload-delta.md", + "playbooks/planning/training-resource-budget/references/papers-20261015/notes/training-memory-scheduling.md", + "playbooks/planning/training-resource-budget/references/papers-20261015/references/source-readset.md", + "playbooks/planning/training-resource-budget/references/sources.md", + "playbooks/planning/training-resource-budget/references/stas-decision-notes.md" + ], + "composition": { + "when": {}, + "license": "Apache-2.0 AND CC-BY-SA-4.0", + "permissions": { + "read": true, + "retain": true, + "redistribute": true + }, + "nodes": { + "navigation": { + "ref": "checkout:training-resource-budget.original.navigation", + "revision": "sha256:b19739c8fc004b2c5170730dfad73e4f32c697491e9947a22b4fd2ccb1e4d265" + }, + "decision": { + "ref": "checkout:training-resource-budget.original.decision", + "revision": "sha256:9dcd3a132d7fa803876101fc771706ccfae58b8568a675f52993e8901687eb2c" + }, + "procedure": { + "ref": "checkout:training-resource-budget.original.procedure", + "revision": "sha256:bd56a9c7dbea94aef2f8da5f72f0a3621c83dcfdb2dd8fc2db6d34b8a33d9f89", + "requires": [ + "decision" + ] + }, + "original": { + "ref": "checkout:training-resource-budget.original", + "revision": "sha256:80065e316fe72be5795829d0d546f44d76fcc261578d0415558855ec74b0adbd" + }, + "mindspeed-historical": { + "ref": "checkout:training-resource-budget.mindspeed-historical", + "revision": "sha256:cd1389e4ce3954c068cbcd5426708af3a9bed2eab4a4d7bf3239c52941ecfd2d" + }, + "mindspeed-source-readset": { + "ref": "checkout:training-resource-budget.mindspeed-source-readset", + "revision": "sha256:e4ffe8d249d225e1f046d75ad67e168b78fb3b162f2f5dc035832e7ba94b9952" + }, + "integration-notes": { + "ref": "checkout:training-resource-budget.integration-notes", + "revision": "sha256:d83fd6a95cfd1642b772e995f0a2159d7f0f83a6b88be87440975f8eef2d6dbb" + }, + "paper-grounded-cases": { + "ref": "checkout:training-resource-budget.paper-grounded-cases", + "revision": "sha256:0f0247406022d43c95211471192fb477eb013c1cff273786f922b704793ac5ca" + }, + "offload-delta": { + "ref": "checkout:training-resource-budget.offload-delta", + "revision": "sha256:312d1730ff10ddd44bc2d9842fbbcc6cc7bd52317f382ee546a07cdb6d37e8be" + }, + "training-memory-scheduling": { + "ref": "checkout:training-resource-budget.training-memory-scheduling", + "revision": "sha256:b4ba8e0b8788c2b7a597202a4549653c64fcc9c09963912e2774e10672e9dcc6" + }, + "source-readset": { + "ref": "checkout:training-resource-budget.source-readset", + "revision": "sha256:7b406d2bce50493d9f1b06de5414b074f648c3219661c226e50954c29dc25920" + }, + "sources": { + "ref": "checkout:training-resource-budget.sources", + "revision": "sha256:9dc6255caf9dda0108ad1f64211e45d9213f8957a6e721e5fb19c60c6ed9570a" + }, + "stas-decision-notes": { + "ref": "checkout:training-resource-budget.stas-decision-notes", + "revision": "sha256:2e9f528f520f9d6c4aefcd503d74f9fa57f580ee8e39ae98661afcab36cf9a72" + } + }, + "routes": { + "navigation": { + "layer": "L0", + "required": [ + "navigation" + ] + }, + "decision": { + "layer": "L1", + "required": [ + "decision" + ] + }, + "procedure": { + "layer": "L2", + "required": [ + "procedure" + ] + }, + "originals": { + "layer": "L3", + "required": [ + "original", + "mindspeed-historical", + "mindspeed-source-readset", + "integration-notes", + "paper-grounded-cases", + "offload-delta", + "training-memory-scheduling", + "source-readset", + "sources", + "stas-decision-notes" + ] + } + } + } + }, + "directory_resources": { + "playbooks/planning/training-resource-budget/SKILL.md": "original", + "playbooks/planning/training-resource-budget/references/mindspeed-historical.md": "mindspeed-historical", + "playbooks/planning/training-resource-budget/references/mindspeed-source-readset.md": "mindspeed-source-readset", + "playbooks/planning/training-resource-budget/references/papers-20261015/INTEGRATION_NOTES.md": "integration-notes", + "playbooks/planning/training-resource-budget/references/papers-20261015/cases/paper-grounded-cases.md": "paper-grounded-cases", + "playbooks/planning/training-resource-budget/references/papers-20261015/knowledge/offload-delta.md": "offload-delta", + "playbooks/planning/training-resource-budget/references/papers-20261015/notes/training-memory-scheduling.md": "training-memory-scheduling", + "playbooks/planning/training-resource-budget/references/papers-20261015/references/source-readset.md": "source-readset", + "playbooks/planning/training-resource-budget/references/sources.md": "sources", + "playbooks/planning/training-resource-budget/references/stas-decision-notes.md": "stas-decision-notes" + } +} diff --git a/tests/knowledge/test_atomic_training_budget.py b/tests/knowledge/test_atomic_training_budget.py new file mode 100644 index 000000000..1b3fb8b73 --- /dev/null +++ b/tests/knowledge/test_atomic_training_budget.py @@ -0,0 +1,118 @@ +"""Replay the released training resource-budget guide, its references and adaptation terms.""" + +import json +import shutil + +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 + +NAME = "training-resource-budget" +REF = "checkout:" + NAME +RELEASE = json.loads((FIXTURES / "playbook-domain-v0.3.4.json").read_bytes())["refs"][REF] +LIBRARY = "src/inferrsi/knowledge/data/skill_library/" + + +@pytest.fixture(scope="module") +def installed_budget(tmp_path_factory): + root = tmp_path_factory.mktemp("training-budget") + author = make_author_root(root) + release = root / "release" + shutil.copytree(RELEASE_ROOT, release) + composition = ATOMS.parent / "compositions" / (NAME + ".json") + shutil.copyfile(composition, author / "compositions" / composition.name) + declaration = json.loads(composition.read_bytes()) + nodes = declaration["metadata"]["composition"]["nodes"] + bindings = declaration["directory_resources"] + assert bindings.keys() == RELEASE["required_resources"].keys() + 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["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) + # Keep the deepest published resource above the legacy Windows path limit on a short drive. + target = root / ("installed-" + "nested-" * 12) / ("tenant-" * 8) / "release" + generation = build_generation(author, target, permits=allow, + source_roots={RELEASE_COMMIT: release}) + return InstalledGeneration(target, expected=generation) + + +def test_training_budget_preserves_released_layers_and_navigation_scope(installed_budget): + reader = installed_budget + _, bundle = reader.read_resolved(REF, revision=reader.catalog[REF]["revision"]) + assert bundle.view()["resources"] == RELEASE["required_resources"] + assert bundle.dependencies == RELEASE["dependencies"] == {} + entry = RELEASE["entrypoint"] + navigation = [link for link in RELEASE["relative_guide_links"].values() + if not link["in_directory"]] + assert len(navigation) == 3 + assert all(link["path"] not in bundle.content for link in navigation) + layers = {} + for level in ("L0", "L1", "L2", "L3"): + delivery = select(reader, REF, level, 1_000_000) + assert delivery.receipt["status"] == "delivered" + size = sum(map(len, delivery.bodies)) + assert select(reader, REF, level, size) == delivery + assert_empty(select(reader, REF, level, size - 1), "over_budget") + stale = select(reader, REF, level, size, revision=RELEASE["revision"]) + assert_empty(stale, "unavailable_revision") + for item, body in zip(delivery.receipt["delivered"], delivery.bodies, strict=True): + start, end = item["source_byte_range"] + path = item["source_path"].removeprefix(LIBRARY) + assert body == bundle.content[path][start:end] + assert item["source_range_verification"] == "verified_at_build" + assert item["source"]["commit"] == RELEASE_COMMIT + denied_ref = item["ref"] + assert_empty(select(reader, REF, level, size, + permits=lambda pin, op: pin.ref != denied_ref), "permission_denied") + layers[level] = delivery.bodies + + assert bundle.content[entry].startswith(layers["L0"][0]) + (decision,) = layers["L1"] + _, fields = _skill_search_source(decision.decode()) + card = DecisionSource(REF, RELEASE["revision"], "skill", entry, entry, fields).project()["card"] + assert card["status"] == "partial" and card["missing_fields"] == ["validation"] + assert digest(canonical(card)) == RELEASE["card_sha256"] + assert len(canonical(card)) == RELEASE["card_bytes"] + 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)) + + +def test_training_budget_keeps_share_alike_on_the_adapted_note(installed_budget): + reader = installed_budget + _, bundle = reader.read_resolved(REF, revision=reader.catalog[REF]["revision"]) + nodes = bundle.metadata["composition"]["nodes"] + note = nodes["stas-decision-notes"] + _, atom = reader.read_resolved(note["ref"], revision=note["revision"]) + credit, = atom.metadata["attribution"] + assert atom.metadata["atom"]["license"] == credit["license"] == "CC-BY-SA-4.0" + assert credit["author"] == "Stas Bekman" and credit in atom.metadata["sources"] + content = atom.content["stas-decision-notes.md"] + assert credit["commit"].encode() in content and credit["license_url"].encode() in content + assert b"paraphrased adaptation" in content + for node in ("mindspeed-historical", "mindspeed-source-readset", "sources"): + pin = nodes[node] + _, independent = reader.read_resolved(pin["ref"], revision=pin["revision"]) + assert independent.metadata["atom"]["license"] == "Apache-2.0" + assert bundle.metadata["empirical_validation"] == "not_run" + denied = select(reader, REF, "L3", 1_000_000, operations={"redistribute"}, + permits=lambda pin, op: (pin.ref, op) != (note["ref"], "redistribute")) + assert_empty(denied, "permission_denied") From 321b2ef2bd2d261109cd1c828edde4a53debd982 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:11:51 +0800 Subject: [PATCH 2/2] Migrate video diffusion and weight loading Playbooks to the atomic Reader Preserve the two released decisions, evaluator and source-specific attribution. Keep cross-directory navigation under each target identity. Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (implementation) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- .../playbooks/video-diffusion-optimization.md | 219 ++++++ .../assets/campaign.template.json | 40 ++ .../scripts/evaluate_target.py | 242 +++++++ .../playbooks/weight-loading-optimization.md | 624 ++++++++++++++++++ .../deepseek-expert-cache-oracles.md | 132 ++++ .../deepseek-expert-cache-source.json | 361 ++++++++++ .../fastsafetensors-transfer-readset.md | 61 ++ .../references/flare-preparation-boundary.md | 75 +++ .../references/llama-loading-readset.md | 26 + ...fusion-optimization.campaign-template.json | 65 ++ ...iffusion-optimization.evaluate-target.json | 65 ++ ...video-diffusion-optimization.original.json | 94 +++ ...ization.deepseek-expert-cache-oracles.json | 130 ++++ ...mization.deepseek-expert-cache-source.json | 130 ++++ ...tion.fastsafetensors-transfer-readset.json | 120 ++++ ...timization.flare-preparation-boundary.json | 118 ++++ ...ng-optimization.llama-loading-readset.json | 116 ++++ .../weight-loading-optimization.original.json | 270 ++++++++ .../video-diffusion-optimization.json | 117 ++++ .../weight-loading-optimization.json | 314 +++++++++ .../test_atomic_optimization_playbooks.py | 172 +++++ 21 files changed, 3491 insertions(+) create mode 100644 src/inferrsi/knowledge/atoms/playbooks/video-diffusion-optimization.md create mode 100644 src/inferrsi/knowledge/atoms/playbooks/video-diffusion-optimization/assets/campaign.template.json create mode 100644 src/inferrsi/knowledge/atoms/playbooks/video-diffusion-optimization/scripts/evaluate_target.py create mode 100644 src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization.md create mode 100644 src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization/references/deepseek-expert-cache-oracles.md create mode 100644 src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization/references/deepseek-expert-cache-source.json create mode 100644 src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization/references/fastsafetensors-transfer-readset.md create mode 100644 src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization/references/flare-preparation-boundary.md create mode 100644 src/inferrsi/knowledge/atoms/playbooks/weight-loading-optimization/references/llama-loading-readset.md create mode 100644 src/inferrsi/knowledge/atoms/video-diffusion-optimization.campaign-template.json create mode 100644 src/inferrsi/knowledge/atoms/video-diffusion-optimization.evaluate-target.json create mode 100644 src/inferrsi/knowledge/atoms/video-diffusion-optimization.original.json create mode 100644 src/inferrsi/knowledge/atoms/weight-loading-optimization.deepseek-expert-cache-oracles.json create mode 100644 src/inferrsi/knowledge/atoms/weight-loading-optimization.deepseek-expert-cache-source.json create mode 100644 src/inferrsi/knowledge/atoms/weight-loading-optimization.fastsafetensors-transfer-readset.json create mode 100644 src/inferrsi/knowledge/atoms/weight-loading-optimization.flare-preparation-boundary.json create mode 100644 src/inferrsi/knowledge/atoms/weight-loading-optimization.llama-loading-readset.json create mode 100644 src/inferrsi/knowledge/atoms/weight-loading-optimization.original.json create mode 100644 src/inferrsi/knowledge/compositions/video-diffusion-optimization.json create mode 100644 src/inferrsi/knowledge/compositions/weight-loading-optimization.json create mode 100644 tests/knowledge/test_atomic_optimization_playbooks.py 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