From d5d12eab59712b61514cabd69658fd343d4364a5 Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Thu, 3 Dec 2026 22:20:58 -0800 Subject: [PATCH] helios,heliopause,selene,ignition: fleet-wide 2-way codec green contexts, R580/VMM fallbacks, packed dedup, graph SM bounds, and ScratchArena reserve_sms floor 1. Why this change is needed and why this approach Five structural defects blocked safe Green Context GPU KV-codec isolation, CUDA 13.0/R580 compatibility, and cooperative SM budgeting across exported cores: - Helios set `reserve_codec_partition = true` for `--lossless-kv-compression gpu` in `helios/src/runtime_core/model.rs`, but `NativeResources::initialize` and `prepare_kernels` in `helios/src/runtime_core/mod.rs` only retained a primary CUDA context and created a `GreenContextPartition` when `persistent_workers` was non-empty. Standard cores without persistent workers therefore shared SMs between GPU KV-codec kernels and full-grid cooperative graphs, risking scheduler contention and replay stalls. - Exported graph manifests did not record per-graph minimum compute SM counts (`min_compute_sms`) or kernel cluster dimensions (`max_cluster_size`), so Green Context SM splitting could neither enforce co-residency floors nor reject cluster dimensions exceeding the compute partition's SM count or driver-reported co-scheduled alignment. - CUDA 13.0 / R580 drivers (such as GB10 SM121 driver 580.173.02) export `cuDevSmResourceSplitByCount` and the other seven Green Context driver symbols without CUDA 13.1's `cuDevSmResourceSplit`, causing Green Context initialization to fail on R580. In addition, R580 segfaults inside `cuMemcpyBatchAsync_v2` when copying from `cuMemHostGetDevicePointer` into a `cuMemMap` VMM range on a `cuCtxFromGreenCtx` stream, whereas `cuMemcpyAsync` succeeds on identical pointers and streams. - On multi-rank deployments with `--lossless-kv-compression gpu` or `cpu`, Selene pre-populated `location.packed` per rank and skipped `pack_shares` deduplication, storing N identical compressed copies of replicated MLA pages across DRAM slabs, disk records, and pool exports instead of using v4 `PackedUnit.replicas`. - During Python preparation, `ScratchArena` tracked overlapping plans via `register_parallel` for disjoint workspace sizing only, without enforcing a cooperative SM reservation floor against concurrent auxiliary-stream collectives. Generalizing `GreenContextPartition` via a typed `PartitionRequest` enum to support 2-way `(worker, compute)`, 2-way `(codec, compute)`, and 3-way `(worker, codec, compute)` topologies isolates GPU KV-codec execution fleet-wide via shared runtime policy without model-identity branches. Falling back to `cuDevSmResourceSplitByCount` (with compute in `result[0]` and three-way remainder refresh through a temporary green context) and routing Green Context streams through `cuMemcpyAsync` in `Stream::copy_batch` restores CUDA 13.0 / R580 support while keeping driver-reported co-scheduled alignment uninflated. Deduplicating byte-identical per-rank `PackedUnit` payloads into `PackedUnit.replicas` reuses Selene's existing v4 wire and decode contract to eliminate multi-rank storage inflation across DRAM, disk, and pool tiers. Recording `min_compute_sms` and `max_cluster_size` as zero-default Protobuf fields preserves compatibility with existing cores while enforcing SM and cluster bounds at load time, and bidirectional `reserve_sms` checks on `ScratchArena` fail closed during preparation when cooperative plans lack required SM headroom. 2. What changed - Per-graph SM-budget manifest fields (`helios/proto/{runtime_core,core}.proto`, `ignition/preparation/{runtime_core_pb2,capture,runtime_core}.py`, `heliopause/src/export/{mod,capture,core}.rs`, `helios/src/runtime_core/{format,protobuf,metadata,describe,protection,selection}.rs`, `helios/src/core/{cache,conversion,export,protection,schema}.rs`): - Before: `GraphIndex` and `Graph` carried no SM-floor or cluster-dimension metadata; capture did not record co-resident SM floors or parse `CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION` (attribute id 4). - After: added optional `uint32 min_compute_sms = 7` and `uint32 max_cluster_size = 8` (`0` = unspecified for backward compatibility with existing cores), regenerated `runtime_core_pb2.py`, wrapped graph capture in `b12x._lib.utils.device.track_capture_min_compute_sms()` (pinned via `pyproject.toml` rev `3c5c7b1488`, failing closed without a silent `ImportError` fallback), exposed shared `CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION` and `kernel_cluster_size_from_bytes` in `helios/src/runtime_core/format.rs` for both export and load, and preserved `(0, 0)` for unclustered graphs without folding `max_cluster_size` into `min_compute_sms`. - Fleet-wide Green Context partitioning, R580 fallback, and honest alignment checks (`helios/src/runtime_core/{driver,persistent_worker,mod,model}.rs`, `helios/src/cuda.rs`): - Before: `GreenCtxDriver` required `cuDevSmResourceSplit`; `plan_sm_split` and `GreenContextPartition::create` required a persistent worker; `NativeResources::initialize` only retained a primary context for persistent-worker cores; `Stream::copy_batch` always invoked `cuMemcpyBatchAsync_v2` when present. - After: replaced `(Option, bool)` with `PartitionRequest` supporting 2-way `(worker, compute)`, 2-way `(codec, compute)`, and 3-way `(worker, codec, compute)` splits; invoked `NativeResources::initialize_with_options` from `model.rs` whenever `--lossless-kv-compression gpu` is active; added optional `cuDevSmResourceSplitByCount` fallback in `GreenCtxDriver` and `GreenContextPartition::create` placing compute in structured `result[0]` and refreshing three-way remainders via a temporary `CUgreenCtx`; recorded driver-reported `actual_compute_sm.sm_coscheduled_alignment` directly without `.max(...)` inflation and validated it against `required_compute_coscheduled` (structured split) or `max_cluster_size` (count-based split); enforced `min_compute_sms`, `max_cluster_size`, and per-node cluster attributes in `prepare_graphs` with a shared `CPU_CODEC_HINT`; queried `cuStreamGetGreenCtx` once in `Stream::open` and `Stream::open_lowest_priority` so `Stream::copy_batch` uses `cuMemcpyAsync` on Green Context streams. - Multi-rank packed unit deduplication (`selene/src/{codec_copy,memory,disk_store}.rs`): - Before: `DirectSlabTarget::take_direct`, `AsyncCompressor`, and `build_packed_write` stored one copy of every rank's compressed packet even when per-rank bytes were identical, and `complete_record` skipped `pack_shares` for packed records. - After: deduplicated byte-identical per-rank `PackedUnit` entries sorted by `(kind, logical_index, stored_rank)` across all three paths, recording dropped ranks in `PackedUnit.replicas`, compacting DRAM slabs tightly when duplicates are eliminated to release trailing slabs, and counting deduplicated packed records under `stats.packed_records[0]` while keeping raw `record.replication` unset for pool compatibility. - Structural `ScratchArena` cooperative SM floor (`ignition/preparation/scratch.py`) and normative documentation (`docs/{runtime-core-design,core-format-design,prefix-cache-offload,core-design,preparation-development}.md`, `helios/manifest.md`): - Before: `ScratchArena.register_parallel` tracked byte overlap only and `docs/runtime-core-design.md` scoped Green Contexts to single-rank persistent-worker cores. - After: added `min_reserve_sms=0`, `reserve_sms_floor`, `require_reserve_sms`, `resolve_reserve_sms`, `register_cooperative_plan`, and `register_parallel(*plans, reserve_sms=0)` with bidirectional validation, shared `_validate_reserve_sms`, weakest-link headroom tracking, and full reset in `release_preparation()`; updated all six normative documents to reflect the three Green Context topologies, R580/VMM fallbacks, graph SM bounds, packed cross-rank deduplication, and `ScratchArena` SM-floor enforcement. 3. Claimed benefit and result - Isolates `--lossless-kv-compression gpu` in a disjoint Green Context across non-worker and persistent-worker cores on both CUDA 13.1+ and CUDA 13.0/R580 drivers, avoids R580 `cuMemcpyBatchAsync_v2` VMM faults on Green Context streams, and rejects under-provisioned compute partitions or driver-downgraded cluster alignment at load time. - Preserves backward compatibility with existing exported cores (`min_compute_sms == 0`, `max_cluster_size == 0`, verified by wire-decode tests and per-node cluster validation). - Eliminates multi-rank duplicate storage for identical compressed KV units (e.g. 4:1 on TP4 MLA and 2:1 on pairwise GQA) across DRAM slabs, disk records, and `selene-manager` exports without changing the v4 wire format. - Fails closed at preparation time when cooperative plans overlap concurrent collectives without sufficient `reserve_sms` headroom. 4. Supporting evidence and limitations Validated on Linux x86_64 with NVIDIA RTX PRO 6000 Blackwell Max-Q (SM120, 188 SMs, driver 620.73.04), rebased on `origin/main` (`be4092d7`): - `cargo test --locked --release --manifest-path eos/Cargo.toml --target-dir flare-cli/target`: 12 passed, 0 failed. - `cargo test --locked --release --manifest-path selene/Cargo.toml --features test-support --target-dir flare-cli/target`: 643 unit + 1 integration passed, 0 failed (including new 4-rank MLA/GQA `direct_slab_capture_deduplicates_identical_and_pairwise_rank_packets`, `dedup_capture_slots_merges_identical_ranks_and_validates_layout`, and `packed_multi_rank_mla_capture_deduplicates_slabs_stats_and_pool_export`). - `cargo test --locked --release --manifest-path selene-manager/Cargo.toml --features test-support --target-dir flare-cli/target`: 448 passed, 0 failed, 1 ignored. - `cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --target-dir flare-cli/target --lib -- runtime_core:: core:: cuda:: offload::`: 561 passed, 0 failed, 33 ignored (including new `PartitionRequest`, `plan_split_by_count`, `validate_actual_compute_partition` downgrade and R580 TPC-2 tests, and `legacy_graph_wire_bytes_omitting_sm_bounds_decode_to_zero`). Full `helios --lib` suite with `FLARE_TEST_TEMPLATE_DIR`: 1,956 passed, 51 ignored, 6 failed solely due to absent Hugging Face model template fixtures in `/tmp/flare-test-templates`. - `CUDA_VISIBLE_DEVICES=3 cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --target-dir flare-cli/target --lib -- --ignored --nocapture --test-threads=1 codec_compute_partition three_way_gpu_codec cuda_split_by_count_fallback_partitions_two_way_and_three_way`: 3 passed, 0 failed on SM120: - 3-way: `worker=8 SMs, codec=8 SMs, compute=172 SMs | baseline_coop=7.5 us | concurrent_coop=137962 (137750.5/s) | gpu_codec_rounds=247 (encode+decode 262.0 MiB/s, ratio 5.98x)` - 2-way: `codec=8 SMs, compute=180 SMs (cosched=16) | concurrent_coop=73148 | gpu_codec_rounds=125` - `SplitByCount` fallback: 2-way `(codec, compute)` and 3-way `(worker, codec, compute)` partitions plus Green Context `Stream::copy_batch` from registered host memory into a `cuMemMap` VMM allocation passed. - `cargo test --locked --release --manifest-path flare/Cargo.toml --target-dir flare-cli/target`: 255 passed, 0 failed, 4 ignored. - `cargo test --locked --release --manifest-path flare-cli/Cargo.toml` and `cargo build --locked --release --manifest-path flare-cli/Cargo.toml`: 254 passed, 0 failed, 3 ignored; release binary built cleanly. - `cargo test --locked --release --manifest-path heliopause/Cargo.toml --target-dir flare-cli/target --lib`: 251 passed, 0 failed, 6 ignored (including `graph_sm_requirements_extracts_cluster_dimension_and_preserves_unspecified_zero`). - `CUDA_VISIBLE_DEVICES=3 FLARE_RUN_CUDA_TESTS=1 pytest tests/preparation/{test_scratch,test_capture_graph_metadata,test_core_boundary,test_codec_layout,test_persistent_worker}.py tests/test_kv_codec.py tests/cli -q` (with `PYTHONPATH` supplying the worktree `ignition` and `flashinfer#217` `b12x`): 314 passed, 0 failed. Limitations: - Live SM103 and GB10 SM121 (R580 driver `580.173.02`) hardware execution, multi-GPU `ignition export` + `flare run --lossless-kv-compression gpu`, and the 6 gated Hugging Face chat-template tests were not run on this host. - DeepSeek-V4.1 `DSAFusedIndexerKernel` (`flashinfer/experimental/b12x/attention/dsa_indexer/fused_indexer.py`) launches full-GPU non-cooperative software-barrier waves in the separate `local-inference-lab/flashinfer` repository; fixing that kernel (cooperative clamping or SM-budget reservation) requires a companion PR in `local-inference-lab/flashinfer` followed by a `pyproject.toml` pin bump. Design-Signed-Off-By: Antigravity (Gemini); design-review=2e5b Signed-off-by: Luke Alonso --- docs/core-design.md | 6 +- docs/core-format-design.md | 2 +- docs/prefix-cache-offload.md | 19 +- docs/preparation-development.md | 4 +- docs/runtime-core-design.md | 79 +- heliopause/src/export/capture.rs | 76 + heliopause/src/export/core.rs | 2 + heliopause/src/export/mod.rs | 2 + helios/manifest.md | 43 +- helios/proto/core.proto | 4 + helios/proto/runtime_core.proto | 4 + helios/src/core/cache.rs | 2 + helios/src/core/conversion.rs | 2 + helios/src/core/export.rs | 6 + helios/src/core/protection.rs | 2 + helios/src/core/schema.rs | 2 + helios/src/cuda.rs | 33 +- helios/src/runtime_core/describe.rs | 4 + helios/src/runtime_core/driver.rs | 47 +- helios/src/runtime_core/format.rs | 27 + helios/src/runtime_core/metadata.rs | 2 + helios/src/runtime_core/mod.rs | 136 +- helios/src/runtime_core/model.rs | 12 +- helios/src/runtime_core/persistent_worker.rs | 1574 +++++++++++++++-- helios/src/runtime_core/protection.rs | 6 + helios/src/runtime_core/protobuf.rs | 77 + helios/src/runtime_core/selection.rs | 15 +- ignition/preparation/capture.py | 14 +- ignition/preparation/runtime_core.py | 11 +- ignition/preparation/runtime_core_pb2.py | 190 +- ignition/preparation/scratch.py | 79 +- selene/src/codec_copy.rs | 318 +++- selene/src/disk_store.rs | 1 + selene/src/memory.rs | 236 ++- .../test_capture_graph_metadata.py | 57 + tests/preparation/test_scratch.py | 69 + 36 files changed, 2768 insertions(+), 395 deletions(-) diff --git a/docs/core-design.md b/docs/core-design.md index 3803ab21e..b1d13260e 100644 --- a/docs/core-design.md +++ b/docs/core-design.md @@ -818,7 +818,11 @@ normalization and projection examples. Autotuning uses private seeded fixtures. `ignition.preparation.scratch.ScratchArena` supplies byte storage for kernel preparation and candidate measurement. `arena.views(*shapes_and_dtypes)` returns contiguous typed views with 256-byte-aligned, nonoverlapping regions. -`register_parallel(*plans)` declares preparation workspaces that must coexist. +`register_parallel(*plans, reserve_sms=0)` declares preparation workspaces that +must coexist and optionally enforces a cooperative SM reservation floor alongside +`register_cooperative_plan(plan, reserve_sms=...)`, `require_reserve_sms`, and +`resolve_reserve_sms` so overlapping cooperative plans leave headroom for +concurrent auxiliary-stream collectives. The arena reserves the maximum requirement across sequential operations and concurrent groups in the complete candidate envelope. After selection and CUDA synchronization, `trim(nbytes)` sizes that storage from the selected plans, and diff --git a/docs/core-format-design.md b/docs/core-format-design.md index 06dcfc1b1..7efb6c427 100644 --- a/docs/core-format-design.md +++ b/docs/core-format-design.md @@ -219,7 +219,7 @@ not substitutes for identifiers. | `Initializer` | Allocation name, destination offset, source `PayloadUse`. | | `ExecutableResource` | Preassigned resource ID, kind, stored compressed `PayloadSlice`, signed decoded length, 4 MiB chunk metadata, and compressed chunk commitments. | | `Module` / `Function` | Cubin resource reference; module reference, symbol, parameter layout and launch attributes. | -| `Graph` | Graph name, instantiation flags, compressed graph resource reference, node and edge counts, and function dependencies. Graph bytes encode nodes, edges, parameters, and dependencies. The rank's `flare.runtime.Execution` record carries each graph's operation kind, capacities, and input bindings. | +| `Graph` | Graph name, instantiation flags, compressed graph resource reference, node and edge counts, function dependencies, and optional per-graph SM bounds (`min_compute_sms`, `max_cluster_size`, with `0` meaning unspecified). Graph bytes encode nodes, edges, parameters, and dependencies. The rank's `flare.runtime.Execution` record carries each graph's operation kind, capacities, and input bindings. | | `PreparedWeightView` | Semantic tensor name, stable group, dtype, shape, strides, allocation/view binding, source tensor identities and logical ranges, concatenation order, padding/fills, typed packing parameters and locality tile, and quantization statistic domain. | | `ExternalExtentTable` | Channel name matching an `Execution.async_transfers` entry, one `Weights`-role `PayloadUse` directory, and ordered `Weights`-role `PayloadUse` segment slices entering the rank's authenticated payload set. Each directory entry is 24 little-endian bytes (`segment_index: u32`, `reserved: u32` which must be zero, `offset: u64`, `length: u64`), validated at export and load for channel direct-I/O alignment and segment bounds. | diff --git a/docs/prefix-cache-offload.md b/docs/prefix-cache-offload.md index 68136f371..fa9ae4f98 100644 --- a/docs/prefix-cache-offload.md +++ b/docs/prefix-cache-offload.md @@ -56,11 +56,14 @@ tier: `--prefix-cache-memory`, `--prefix-cache-disk`, or `--prefix-cache-pool`): predictor, 4-lane bit packing, 32-way warp-interleaved 12-bit static rANS, on-GPU packet assembly, and parallel GPU CRC32 directly on each rank's lowest-priority CUDA transfer stream using a compact 3-buffer aliased - per-rank GPU workspace budgeted before KV cache sizing. On cores that declare - a persistent worker, Helios reserves a third disjoint CUDA Green Context SM - partition for GPU codec execution so codec kernels never share SMs with - cooperative compute graphs, and opens the host prefix store (calling - `cuModuleLoadData`) before starting the persistent worker graph. Only + per-rank GPU workspace budgeted before KV cache sizing. Helios reserves a + disjoint CUDA Green Context SM partition for GPU codec execution—a 2-way + `(codec, compute)` split on standard cores or a 3-way + `(worker, codec, compute)` split on cores declaring a persistent worker—so + codec kernels never share SMs with cooperative compute graphs, validates each + graph's `min_compute_sms` and `max_cluster_size` bounds against the compute + partition, and opens the host prefix store (calling `cuModuleLoadData`) + before starting any persistent worker graph. Only compressed bytes cross PCIe during capture and GPU-decoded restores, while small non-matrix restores (< 256 KiB) or mutex-contended restores decode on the bounded CPU worker pool over async HtoD DMA, with zero external runtime @@ -70,7 +73,11 @@ Both modes compress at the VRAM-to-DRAM boundary and keep compressed bytes across local DRAM (`MemoryStore`), local disk (`DiskStore`, standalone or composite `--prefix-cache-memory` + `--prefix-cache-disk`), manager DRAM (`selene-manager` arena), NVMe record files, shared-memory windows, TCP -streams, and RDMA claims. After capturing a packed record into local DRAM +streams, and RDMA claims. On multi-rank deployments, byte-identical per-rank +packed units (such as replicated MLA pages) are deduplicated across ranks into +one stored payload with `PackedUnit.replicas` populated before compacting DRAM +slabs, spilling to disk, or exporting to `selene-manager`. After capturing a +packed record into local DRAM slabs, `MemoryStore` compacts the compressed payloads and releases unused trailing slabs; `CompositeStore` spills those compressed units verbatim into v4 `.ckpt` files on `--prefix-cache-disk` and promotes v4 `.ckpt` files back into diff --git a/docs/preparation-development.md b/docs/preparation-development.md index 0da40a7bd..51acfc04c 100644 --- a/docs/preparation-development.md +++ b/docs/preparation-development.md @@ -256,7 +256,9 @@ workspace through an explicit pending record. The fork waits for input production. The join receives the pending operands and the main-stream result that must precede it, then waits for the auxiliary stream. Custom operators declare these dependencies so Inductor keeps storage live through the join. -`ScratchArena.register_parallel` sizes simultaneous preparation workspaces. +`ScratchArena.register_parallel` sizes simultaneous preparation workspaces and +enforces cooperative SM reservation floors (`reserve_sms`) against plans +registered with `register_cooperative_plan`. Serving overlap uses invocation-local tensors. Capture serialized graph variants with the same CUDA graph pool through diff --git a/docs/runtime-core-design.md b/docs/runtime-core-design.md index 70144657e..c59a626d6 100644 --- a/docs/runtime-core-design.md +++ b/docs/runtime-core-design.md @@ -657,32 +657,47 @@ then rebased onto the live addresses and validated, and the server starts from this reconstructed contract. `flare run CORE` in `flare-cli/src/main.rs` starts the shared server directly from the typed contract. -When a single-rank core declares an entry in `Execution.persistent_workers` -(repeated field 8; at most one entry is currently accepted, and multi-rank or -multi-host cluster cores declaring a persistent worker are rejected), -`NativeResources` resolves the CUDA driver Green Context entrypoints optionally -at driver load (failing load explicitly only when a core requires them on an -unsupported driver), retains the device's primary context, and partitions device -SMs with `cuDevSmResourceSplit` into disjoint structured SM resource groups: -two groups (a `worker` green context aligned to the device's co-scheduled SM -alignment and a `compute` backfill green context preserving co-scheduled SM -alignment for multi-CTA cluster launches) when prefix-cache offload does not use -GPU compression, or three groups (`worker`, one minimal aligned `codec` green -context, and `compute` backfill) when prefix-cache offload is enabled with -`--lossless-kv-compression gpu` (failing load explicitly if remaining SMs cannot -form a structured compute partition). Helios applies the core's recorded CUDA -context limits and cache configuration to the primary context and every created -green context (`worker`, `compute`, and `codec` when present), and opens -non-blocking streams for the worker and compute contexts. Offload transfers and -GPU KV-codec kernels bind the `codec` green context when present and the rank's -base context otherwise, while host slab registration remains portable -(`CU_MEMHOSTREGISTER_PORTABLE`) on the base context. All modules, kernels, graph -executables, and host prefix-store GPU codec modules are loaded, instantiated -under their partition's green context (clamping cooperative grids to that -partition's SM count), and uploaded on their partition's non-blocking stream -before the persistent worker starts; `ModelRuntime` opens the host prefix store -before constructing `RankExecutor` so `cuModuleLoadData` for embedded GPU codec -kernels finishes before any worker graph launches. The executor launches the +When a core declares an entry in `Execution.persistent_workers` (repeated field +8; at most one entry is accepted on single-rank cores, and multi-rank or +multi-host cluster cores declaring a persistent worker are rejected) or when +prefix-cache offload enables `--lossless-kv-compression gpu` on any single-rank +or multi-rank core, `NativeResources` resolves the CUDA driver Green Context +entrypoints optionally at driver load (failing load explicitly only when a core +or offload configuration requires them on an unsupported driver), retains the +device's primary context, and partitions device SMs into disjoint green +contexts: two groups `(worker, compute)` for persistent-worker cores without +GPU compression, two groups `(codec, compute)` for standard cores with +`--lossless-kv-compression gpu`, or three groups `(worker, codec, compute)` when +both are active. On CUDA 13.1+ drivers Helios partitions SMs with +`cuDevSmResourceSplit` (giving the compute group backfill discovery and +co-scheduled SM alignment); on CUDA 13.0 drivers lacking +`cuDevSmResourceSplit`, Helios falls back to `cuDevSmResourceSplitByCount`, +placing the compute partition in the structured `result[0]` group and, for +three-way splits, refreshing the remainder through a temporary green context to +split `worker` and `codec`. Helios validates the compute partition's +driver-reported SM count and co-scheduled alignment against the maximum +`min_compute_sms` and `max_cluster_size` across non-worker graphs (failing load +explicitly with `--lossless-kv-compression cpu` guidance when remaining SMs or +cluster alignment cannot satisfy the core's graphs), applies the core's recorded +CUDA context limits and cache configuration to the primary context and every +created green context (`compute`, plus `worker` and `codec` when present), and +opens non-blocking streams for the created worker and compute contexts. Offload +transfers and GPU KV-codec kernels bind the `codec` green context when present +and the rank's base context otherwise, while host slab registration remains +portable (`CU_MEMHOSTREGISTER_PORTABLE`) on the base context. `Stream::open` +and `Stream::open_lowest_priority` query `cuStreamGetGreenCtx` once and route +Green Context streams through `cuMemcpyAsync` inside `Stream::copy_batch` to +avoid R580 driver faults on `cuMemcpyBatchAsync_v2` against `cuMemMap` VMM +ranges. All modules, kernels, graph executables, and host prefix-store GPU codec +modules are loaded, instantiated under their partition's green context (clamping +cooperative grids to that partition's SM count and validating each graph's +`min_compute_sms`, `max_cluster_size`, and per-node +`CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION` attributes against the partition's SM +count and driver-reported co-scheduled alignment), and uploaded on their +partition's non-blocking stream before any persistent worker starts; +`ModelRuntime` opens the host prefix store before constructing `RankExecutor` so +`cuModuleLoadData` for embedded GPU codec kernels finishes before any worker +graph launches. When a persistent worker is declared, the executor launches the worker graph once on its worker stream only after startup completes, while compute graphs replay on the compute green context. When the entry also declares an optional mapped-host `metrics` reference with positive `metrics_count`, @@ -700,12 +715,12 @@ context before any rank frees shared memory; second, while `Memory::MappedHost` mailboxes and CUDA contexts remain live, Engram background workers and prefix offload workers join, after which every rank destroys its streams, executables, modules, and allocations (draining active telemetry counter readers before -unmapping); third, every rank destroys all created green contexts (worker, -compute, and optional codec, clearing rather than restoring the caller's current -context if it referred to any destroyed green context), virtual-address -reservations, and primary CUDA contexts in reverse rank order. If any rank fails -drain, all ranks retain their CUDA and host resources until process -exit. +unmapping); third, every rank destroys all created green contexts (`compute`, +plus `worker` and `codec` when present, clearing rather than restoring the +caller's current context if it referred to any destroyed green context), +virtual-address reservations, and primary CUDA contexts in reverse rank order. +If any rank fails drain, all ranks retain their CUDA and host resources until +process exit. Before CUDA initialization or serving worker threads, Flare restricts `CUDA_VISIBLE_DEVICES` to `--gpus`, resolving indices within an inherited mask. diff --git a/heliopause/src/export/capture.rs b/heliopause/src/export/capture.rs index 2768ecc2d..7f0f843d0 100644 --- a/heliopause/src/export/capture.rs +++ b/heliopause/src/export/capture.rs @@ -461,6 +461,34 @@ fn function_layout(cuda: &Cuda, function: usize) -> ExportResult ExportResult { + let Some(attribute) = kernel + .attributes + .iter() + .find(|attr| attr.id == helios_core::runtime_core::CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION) + else { + return Ok(0); + }; + let Some(blob) = attribute.value.as_ref() else { + return Ok(0); + }; + helios_core::runtime_core::kernel_cluster_size_from_bytes(&blob.data) + .map_err(|error| invalid(error.to_string())) +} + +fn graph_sm_requirements( + nodes: &[wire::Node], + declared_min_compute_sms: u32, +) -> ExportResult<(u32, u32)> { + let mut max_cluster_size = 0u32; + for node in nodes { + if let Some(wire::node::Operation::Kernel(kernel)) = &node.operation { + max_cluster_size = max_cluster_size.max(kernel_cluster_size(kernel)?); + } + } + Ok((declared_min_compute_sms, max_cluster_size)) +} + #[derive(Debug)] struct RecordedKernel { function: usize, @@ -3397,6 +3425,8 @@ pub(crate) fn capture_rank( _ => None, }) .collect(); + let (min_compute_sms, max_cluster_size) = + graph_sm_requirements(&nodes, graph.min_compute_sms)?; output.index.ranks[0].graphs.push(wire::GraphIndex { name: graph.name.clone(), flags, @@ -3404,6 +3434,8 @@ pub(crate) fn capture_rank( node_count: nodes.len() as u64, edge_count: edges.len() as u64, functions: functions.into_iter().collect(), + min_compute_sms, + max_cluster_size, }); let source = file_source(path)?; graph_bytes += source.nbytes; @@ -5589,4 +5621,48 @@ mod tests { assert!(err.contains("is empty"), "{err}"); Ok(()) } + + #[test] + fn graph_sm_requirements_extracts_cluster_dimension_and_preserves_unspecified_zero() -> ExportResult<()> + { + let mut cluster_bytes = vec![0u8; 64]; + cluster_bytes[0..4].copy_from_slice(&4u32.to_ne_bytes()); + cluster_bytes[4..8].copy_from_slice(&2u32.to_ne_bytes()); + cluster_bytes[8..12].copy_from_slice(&1u32.to_ne_bytes()); + + let nodes = vec![ + wire::Node { + operation: Some(wire::node::Operation::Kernel(wire::Kernel { + function: 0, + grid: vec![8, 1, 1], + block: vec![128, 1, 1], + shared: 0, + arguments: vec![], + attributes: vec![], + })), + }, + wire::Node { + operation: Some(wire::node::Operation::Kernel(wire::Kernel { + function: 1, + grid: vec![8, 16, 1], + block: vec![128, 1, 1], + shared: 0, + arguments: vec![], + attributes: vec![wire::Attribute { + id: helios_core::runtime_core::CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION, + value: Some(wire::Blob { + data: cluster_bytes, + relocations: vec![], + }), + }], + })), + }, + ]; + + assert_eq!(graph_sm_requirements(&nodes, 0)?, (0, 8)); + assert_eq!(graph_sm_requirements(&nodes, 128)?, (128, 8)); + assert_eq!(graph_sm_requirements(&nodes[..1], 0)?, (0, 0)); + assert_eq!(graph_sm_requirements(&[], 0)?, (0, 0)); + Ok(()) + } } diff --git a/heliopause/src/export/core.rs b/heliopause/src/export/core.rs index 745874187..59e00cea8 100644 --- a/heliopause/src/export/core.rs +++ b/heliopause/src/export/core.rs @@ -2128,6 +2128,8 @@ fn rank_plan( node_count: graph.node_count, edge_count: graph.edge_count, functions: graph.functions.clone(), + min_compute_sms: graph.min_compute_sms, + max_cluster_size: graph.max_cluster_size, }); } diff --git a/heliopause/src/export/mod.rs b/heliopause/src/export/mod.rs index 507838a83..d379a522f 100644 --- a/heliopause/src/export/mod.rs +++ b/heliopause/src/export/mod.rs @@ -114,6 +114,8 @@ pub(crate) struct GraphHandle { pub instantiate_flags: Option, #[serde(default)] pub recorded: usize, + #[serde(default)] + pub min_compute_sms: u32, } #[derive(Clone, Debug, Deserialize, Serialize)] diff --git a/helios/manifest.md b/helios/manifest.md index 81b0f9d98..db630fb97 100644 --- a/helios/manifest.md +++ b/helios/manifest.md @@ -111,20 +111,30 @@ execution. Each `PersistentWorker` carries: without GPU synchronization and drains active telemetry readers before unmapping allocations during teardown. -`NativeResources` retains the device's primary CUDA context, partitions SMs -through `cuDevSmResourceSplit` into explicit structured worker and compute -green contexts (preserving co-scheduled SM alignment on the compute partition), -applies the core's recorded CUDA context limits and cache configuration to the -primary context and both green contexts, and loads all modules and instantiates -and uploads every graph executable under its partition's green context and -non-blocking stream (clamping cooperative launch grids to that partition's SM -count) before the persistent worker starts. Serving and copy streams open on -the compute green context obtained through `cuCtxFromGreenCtx`, while the -worker graph launches once on a dedicated non-blocking stream created inside -the worker green context after startup tuning finishes -(`GraphExecutor::finish_startup` or `NativeResources::start_persistent_worker`). -Launch is idempotent and zeroes the stop flag with release semantics before -invoking `cuGraphLaunch`. +`NativeResources` retains the device's primary CUDA context whenever a core +declares a persistent worker or GPU prefix-cache compression is enabled. It +partitions SMs through `cuDevSmResourceSplit` (or `cuDevSmResourceSplitByCount` +on CUDA 13.0 drivers that do not export `cuDevSmResourceSplit`, placing compute +in `result[0]` and splitting three-way remainders via a temporary green context) +into disjoint green contexts: 2-way `(worker, compute)` for persistent-worker +cores without GPU compression, 2-way `(codec, compute)` for non-worker cores +with GPU compression, or 3-way `(worker, codec, compute)` when both are enabled. +The compute partition preserves driver-reported co-scheduled SM alignment and +satisfies the maximum `min_compute_sms` and `max_cluster_size` declared across +non-worker graphs in the rank bundle (`0` means unspecified for backward +compatibility with older cores). Helios applies the core's recorded CUDA context limits and cache +configuration to the primary context and every active green context, loads all +modules, and instantiates and uploads every graph executable under its +partition's green context and non-blocking stream—clamping cooperative launch +grids to that partition's SM count and validating kernel cluster dimensions +against the partition's SM count and co-scheduled alignment—before any +persistent worker starts. Serving and copy streams open on the compute green +context obtained through `cuCtxFromGreenCtx`, GPU KV-codec streams open on the +codec green context, and the worker graph launches once on a dedicated +non-blocking stream created inside the worker green context after startup +tuning finishes (`GraphExecutor::finish_startup` or +`NativeResources::start_persistent_worker`). Launch is idempotent and zeroes +the stop flag with release semantics before invoking `cuGraphLaunch`. During shutdown, `GraphExecutor::close` drains the compute and copy streams first, then signals `1u32` (release) to the stop flag and polls `cuStreamQuery` @@ -135,7 +145,7 @@ CUDA driver error, shutdown returns `ExecutionError::Drain` and marks the worker `WorkerState::FailedDrain`. Resource teardown stops any still-running worker, synchronizes the primary context, destroys worker and compute streams only after context synchronization succeeds, destroys executables, modules, and -mappings, and destroys both green contexts before releasing virtual-address +mappings, and destroys all created green contexts before releasing virtual-address reservations and the primary context. A failed worker drain follows the standard failed-drain invariant: the driver and GPU resources remain retained until process exit. @@ -517,7 +527,8 @@ The index is limited to 128 MiB. The `ModelIndex` includes: - Allocations with packed payload spans, or runtime sizing by continuation rows and KV pages with fixed virtual bases and maximum virtual extents. - Modules, globals, function symbols, parameter sizes, and function attributes. -- Graph declarations, function dependencies, and graph-body resource spans. +- Graph declarations, function dependencies, per-graph `min_compute_sms` and + `max_cluster_size` SM-budget bounds, and graph-body resource spans. - Serving configuration, typed sampling and frontend settings, and tokenizer/chat-template resource spans. - Offloaded Engram geometry, encoding, table spans, compact input names, and named external event waits. diff --git a/helios/proto/core.proto b/helios/proto/core.proto index cf865a915..c9abda6f1 100644 --- a/helios/proto/core.proto +++ b/helios/proto/core.proto @@ -248,6 +248,10 @@ message Graph { uint64 node_count = 4; uint64 edge_count = 5; repeated uint64 functions = 6; + // Minimum compute SMs required for resident execution of this graph; 0 means unspecified. + uint32 min_compute_sms = 7; + // Maximum CTA cluster size declared by kernel nodes in this graph; 0 means unspecified. + uint32 max_cluster_size = 8; } // ---------------------------------------------------------------- engine tables diff --git a/helios/proto/runtime_core.proto b/helios/proto/runtime_core.proto index e30a7eee5..6968a8e7f 100644 --- a/helios/proto/runtime_core.proto +++ b/helios/proto/runtime_core.proto @@ -747,6 +747,10 @@ message GraphIndex { uint64 node_count = 4; uint64 edge_count = 5; repeated uint64 functions = 6; + // Minimum compute SMs required for resident execution of this graph; 0 means unspecified. + uint32 min_compute_sms = 7; + // Maximum CTA cluster size declared by kernel nodes in this graph; 0 means unspecified. + uint32 max_cluster_size = 8; } diff --git a/helios/src/core/cache.rs b/helios/src/core/cache.rs index f6f798a9b..56f1ea88a 100644 --- a/helios/src/core/cache.rs +++ b/helios/src/core/cache.rs @@ -9216,6 +9216,8 @@ mod selection_tests { node_count: 1, edge_count: 0, functions: vec![0], + min_compute_sms: 0, + max_cluster_size: 0, }], ..Default::default() }; diff --git a/helios/src/core/conversion.rs b/helios/src/core/conversion.rs index d45718018..fe792b0d9 100644 --- a/helios/src/core/conversion.rs +++ b/helios/src/core/conversion.rs @@ -4014,6 +4014,8 @@ mod tests { node_count: 1, edge_count: 0, functions: vec![], + min_compute_sms: 0, + max_cluster_size: 0, }], ..Default::default() }; diff --git a/helios/src/core/export.rs b/helios/src/core/export.rs index afb6f165f..6c5dd9ad8 100644 --- a/helios/src/core/export.rs +++ b/helios/src/core/export.rs @@ -2348,6 +2348,8 @@ mod tests { node_count: 1, edge_count: 0, functions: vec![], + min_compute_sms: 0, + max_cluster_size: 0, }], ..Default::default() }, @@ -2484,6 +2486,8 @@ mod tests { node_count: 1, edge_count: 0, functions: vec![0], + min_compute_sms: 0, + max_cluster_size: 0, }], allocations: vec![wire::Allocation { name: "device-0".into(), @@ -2862,6 +2866,8 @@ mod tests { node_count: 1, edge_count: 0, functions: vec![0], + min_compute_sms: 0, + max_cluster_size: 0, }], events: vec![], peers: vec![], diff --git a/helios/src/core/protection.rs b/helios/src/core/protection.rs index 1dff95b8c..e92d45678 100644 --- a/helios/src/core/protection.rs +++ b/helios/src/core/protection.rs @@ -2013,6 +2013,8 @@ mod tests { node_count: 1, edge_count: 0, functions: vec![], + min_compute_sms: 0, + max_cluster_size: 0, }], events: vec![], peers: vec![], diff --git a/helios/src/core/schema.rs b/helios/src/core/schema.rs index 91229571d..24a0baf9b 100644 --- a/helios/src/core/schema.rs +++ b/helios/src/core/schema.rs @@ -1422,6 +1422,8 @@ mod tests { node_count: 1, edge_count: 0, functions: vec![], + min_compute_sms: 0, + max_cluster_size: 0, }], ..Default::default() }; diff --git a/helios/src/cuda.rs b/helios/src/cuda.rs index 4190fe33c..b63cb2842 100644 --- a/helios/src/cuda.rs +++ b/helios/src/cuda.rs @@ -16,6 +16,7 @@ type GetContext = unsafe extern "C" fn(*mut Handle) -> c_int; type SetContext = unsafe extern "C" fn(Handle) -> c_int; type GetDevice = unsafe extern "C" fn(*mut c_int) -> c_int; type StreamCreate = unsafe extern "C" fn(*mut Handle, c_uint) -> c_int; +type StreamGetGreenCtx = unsafe extern "C" fn(Handle, *mut Handle) -> c_int; type StreamOperation = unsafe extern "C" fn(Handle) -> c_int; type GraphLaunch = unsafe extern "C" fn(Handle, Handle) -> c_int; type ErrorText = unsafe extern "C" fn(c_int, *mut *const c_char) -> c_int; @@ -205,6 +206,7 @@ struct Driver { device_uuid: DeviceUuid, event_synchronize: StreamOperation, memcpy_batch: Option, + stream_get_green_ctx: Option, address_reserve: AddressReserve, address_free: AddressFree, memory_create: MemoryCreate, @@ -283,6 +285,10 @@ impl Driver { .get::(b"cuMemcpyBatchAsync_v2\0") .ok() .map(|f| *f), + stream_get_green_ctx: library + .get::(b"cuStreamGetGreenCtx\0") + .ok() + .map(|f| *f), address_reserve: symbol!("cuMemAddressReserve"), address_free: symbol!("cuMemAddressFree"), memory_create: symbol!("cuMemCreate"), @@ -699,6 +705,7 @@ pub(crate) struct Stream { driver: Arc, context: usize, handle: usize, + is_green_ctx: bool, } /// Reject a batch whose arrays disagree in length, that has more than @@ -755,6 +762,21 @@ impl Stream { Ok(driver) } + fn query_is_green_ctx(driver: &Driver, handle: Handle) -> bool { + let Some(get_green_ctx) = driver.stream_get_green_ctx else { + return false; + }; + let mut green_ctx: Handle = std::ptr::null_mut(); + // SAFETY: `handle` is a live CUDA stream handle and `green_ctx` is a valid output pointer. + let status = unsafe { get_green_ctx(handle, &mut green_ctx) }; + status == 0 && !green_ctx.is_null() + } + + #[cfg(test)] + pub(crate) fn is_green_ctx(&self) -> bool { + self.is_green_ctx + } + pub(crate) fn open(context: usize, expected_device: i32) -> Result { let driver = Self::bind(context, expected_device)?; let mut handle = std::ptr::null_mut(); @@ -762,10 +784,12 @@ impl Stream { driver.check("cuStreamCreate", unsafe { (driver.stream_create)(&mut handle, STREAM_NON_BLOCKING) })?; + let is_green_ctx = Self::query_is_green_ctx(&driver, handle); Ok(Self { driver, context, handle: handle as usize, + is_green_ctx, }) } @@ -794,10 +818,12 @@ impl Stream { driver.check("cuStreamCreateWithPriority", unsafe { (driver.stream_create_priority)(&mut handle, STREAM_NON_BLOCKING, least) })?; + let is_green_ctx = Self::query_is_green_ctx(&driver, handle); Ok(Self { driver, context, handle: handle as usize, + is_green_ctx, }) } @@ -821,7 +847,12 @@ impl Stream { if sizes.is_empty() { return Ok(()); } - if let Some(memcpy_batch) = self.driver.memcpy_batch { + // R580 drivers segfault inside `cuMemcpyBatchAsync_v2` when copying from + // `cuMemHostGetDevicePointer` into a `cuMemMap` VMM range on a Green Context + // stream; route Green Context streams through `cuMemcpyAsync`. + if !self.is_green_ctx + && let Some(memcpy_batch) = self.driver.memcpy_batch + { let attributes = CopyAttributes { source_order: SOURCE_ORDER_STREAM, source_location: [0; 2], diff --git a/helios/src/runtime_core/describe.rs b/helios/src/runtime_core/describe.rs index 8d11be769..a5dc0f739 100644 --- a/helios/src/runtime_core/describe.rs +++ b/helios/src/runtime_core/describe.rs @@ -540,6 +540,8 @@ fn rank_json(rank: usize, bundle: &wire::BundleIndex, options: InspectionOptions "estimated_duration_ns": g.estimated_duration_ns, "node_count": bundle.graphs.iter().find(|graph| graph.name == g.name).map(|graph| graph.node_count), "edge_count": bundle.graphs.iter().find(|graph| graph.name == g.name).map(|graph| graph.edge_count), + "min_compute_sms": bundle.graphs.iter().find(|graph| graph.name == g.name).map(|graph| graph.min_compute_sms), + "max_cluster_size": bundle.graphs.iter().find(|graph| graph.name == g.name).map(|graph| graph.max_cluster_size), })).collect::>()).unwrap_or_default(), "roce": bundle.roce.as_ref().map(|r| json!({ "world": r.world, "rank": r.rank, "proxy_abi": r.proxy_abi, @@ -784,6 +786,8 @@ fn payload_rank_json( "estimated_duration_ns": g.estimated_duration_ns, "node_count": core.graphs.iter().find(|graph| graph.name == g.name).map(|graph| graph.node_count as u64), "edge_count": core.graphs.iter().find(|graph| graph.name == g.name).map(|graph| graph.edge_count as u64), + "min_compute_sms": core.graphs.iter().find(|graph| graph.name == g.name).map(|graph| graph.min_compute_sms), + "max_cluster_size": core.graphs.iter().find(|graph| graph.name == g.name).map(|graph| graph.max_cluster_size), })).collect::>()).unwrap_or_default(), "roce": body.roce.as_ref().map(|r| json!({ "world": r.world, "rank": r.rank, "proxy_abi": r.proxy_abi, diff --git a/helios/src/runtime_core/driver.rs b/helios/src/runtime_core/driver.rs index 23fcf3b9c..cff4e4c68 100644 --- a/helios/src/runtime_core/driver.rs +++ b/helios/src/runtime_core/driver.rs @@ -94,6 +94,9 @@ pub const CU_DEV_RESOURCE_TYPE_SM: c_int = 1; /// `CU_DEV_SM_RESOURCE_GROUP_BACKFILL`: include remaining SMs beyond co-scheduled multiples /// in a structured SM resource group rather than dropping them to an unstructured remainder. pub const CU_DEV_SM_RESOURCE_GROUP_BACKFILL: c_uint = 1; +/// `CU_DEV_SM_RESOURCE_SPLIT_MAX_POTENTIAL_CLUSTER_SIZE`: request partitions supporting maximal +/// CTA clusters from `cuDevSmResourceSplitByCount`. +pub const CU_DEV_SM_RESOURCE_SPLIT_MAX_POTENTIAL_CLUSTER_SIZE: c_uint = 2; /// `CU_GREEN_CTX_DEFAULT_STREAM`: required creation flag for CUDA green contexts. pub const CU_GREEN_CTX_DEFAULT_STREAM: c_uint = 1; /// `CU_STREAM_NON_BLOCKING`: required flag for streams created on a green context. @@ -175,14 +178,28 @@ impl DevResource { pub struct GreenCtxDriver { pub device_get_dev_resource: unsafe extern "C" fn(c_int, *mut DevResource, c_int) -> c_int, - pub dev_sm_resource_split: unsafe extern "C" fn( - *mut DevResource, - c_uint, - *const DevResource, - *mut DevResource, - c_uint, - *mut DevSmResourceGroupParams, - ) -> c_int, + /// Structured SM split introduced in CUDA 13.1 (`cuDevSmResourceSplit`). + pub dev_sm_resource_split: Option< + unsafe extern "C" fn( + *mut DevResource, + c_uint, + *const DevResource, + *mut DevResource, + c_uint, + *mut DevSmResourceGroupParams, + ) -> c_int, + >, + /// Count-based SM split available since CUDA 12.4 / R580 (`cuDevSmResourceSplitByCount`). + pub dev_sm_resource_split_by_count: Option< + unsafe extern "C" fn( + *mut DevResource, + *mut c_uint, + *const DevResource, + *mut DevResource, + c_uint, + c_uint, + ) -> c_int, + >, pub dev_resource_generate_desc: unsafe extern "C" fn(*mut Handle, *mut DevResource, c_uint) -> c_int, pub green_ctx_create: unsafe extern "C" fn(*mut Handle, Handle, c_int, c_uint) -> c_int, @@ -203,9 +220,21 @@ impl GreenCtxDriver { } // SAFETY: Signatures match cuda.h; `Driver` retains `library` for the full lifetime. unsafe { + let dev_sm_resource_split = library + .get(b"cuDevSmResourceSplit\0") + .ok() + .map(|symbol| *symbol); + let dev_sm_resource_split_by_count = library + .get(b"cuDevSmResourceSplitByCount\0") + .ok() + .map(|symbol| *symbol); + if dev_sm_resource_split.is_none() && dev_sm_resource_split_by_count.is_none() { + return None; + } Some(Self { device_get_dev_resource: opt_symbol!("cuDeviceGetDevResource"), - dev_sm_resource_split: opt_symbol!("cuDevSmResourceSplit"), + dev_sm_resource_split, + dev_sm_resource_split_by_count, dev_resource_generate_desc: opt_symbol!("cuDevResourceGenerateDesc"), green_ctx_create: opt_symbol!("cuGreenCtxCreate"), green_ctx_destroy: opt_symbol!("cuGreenCtxDestroy"), diff --git a/helios/src/runtime_core/format.rs b/helios/src/runtime_core/format.rs index 81adcdefd..7e2b03710 100644 --- a/helios/src/runtime_core/format.rs +++ b/helios/src/runtime_core/format.rs @@ -223,6 +223,31 @@ pub(super) struct Graph { pub node_count: usize, pub edge_count: usize, pub functions: Vec, + pub min_compute_sms: u32, + pub max_cluster_size: u32, +} + +/// `CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION`: 3D CTA cluster dimensions `(x, y, z)` in `u32` words. +pub const CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION: i32 = 4; + +/// Decode raw `CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION` bytes into total CTAs per cluster. +/// +/// Returns `Ok(0)` when all three dimensions are zero (unspecified cluster dimension), and an +/// error if fewer than 12 bytes are provided or the 3D product overflows `u32`. +pub fn kernel_cluster_size_from_bytes(bytes: &[u8]) -> Result { + if bytes.len() < 12 { + return Err(invalid("kernel cluster dimension attribute is truncated")); + } + let x = u32::from_ne_bytes(bytes[0..4].try_into().unwrap()); + let y = u32::from_ne_bytes(bytes[4..8].try_into().unwrap()); + let z = u32::from_ne_bytes(bytes[8..12].try_into().unwrap()); + if x == 0 && y == 0 && z == 0 { + return Ok(0); + } + x.max(1) + .checked_mul(y.max(1)) + .and_then(|xy| xy.checked_mul(z.max(1))) + .ok_or_else(|| invalid("kernel cluster dimension overflows u32")) } pub(super) struct Dependencies { @@ -675,6 +700,8 @@ mod tests { node_count: 2, edge_count: 0, functions: vec![], + min_compute_sms: 0, + max_cluster_size: 0, }], } } diff --git a/helios/src/runtime_core/metadata.rs b/helios/src/runtime_core/metadata.rs index 9322f686a..b27690a63 100644 --- a/helios/src/runtime_core/metadata.rs +++ b/helios/src/runtime_core/metadata.rs @@ -378,6 +378,8 @@ fn unverified_payload( .map(|graph| json!({ "name": graph.name, "node_count": graph.node_count, "edge_count": graph.edge_count, "resource": graph.resource, + "min_compute_sms": graph.min_compute_sms, + "max_cluster_size": graph.max_cluster_size, })) .collect::>() ); diff --git a/helios/src/runtime_core/mod.rs b/helios/src/runtime_core/mod.rs index bd3984833..01fe4064e 100644 --- a/helios/src/runtime_core/mod.rs +++ b/helios/src/runtime_core/mod.rs @@ -19,6 +19,7 @@ mod engram; #[cfg(test)] mod event_tests; mod format; +pub use format::{CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION, kernel_cluster_size_from_bytes}; pub mod host; mod limits; mod metadata; @@ -532,6 +533,14 @@ impl NativeResources { } unsafe fn initialize(core: &Core, ordinal: i32) -> Result { + unsafe { Self::initialize_with_options(core, ordinal, false) } + } + + unsafe fn initialize_with_options( + core: &Core, + ordinal: i32, + reserve_codec_partition: bool, + ) -> Result { let driver = Arc::new(Driver::load()?); // SAFETY: Driver signatures are checked against cuda.h; output storage is // valid, and CUDA initialization precedes all context/resource operations. @@ -566,6 +575,10 @@ impl NativeResources { .execution .as_ref() .and_then(|execution| execution.persistent_workers.first()); + let partition_request = persistent_worker::PartitionRequest::from_options( + wants_worker.map(|w| w.worker_sm_count), + reserve_codec_partition, + )?; let check_ctx = |operation: &str, status| -> Result<()> { let result = driver.check(operation, status); #[cfg(target_os = "linux")] @@ -578,11 +591,17 @@ impl NativeResources { result }; let mut context = null_mut(); - let primary_context = if wants_worker.is_some() { + let primary_context = if let Some(request) = partition_request { if driver.green_ctx.is_none() { - return Err(invalid( - "persistent worker requires CUDA driver Green Context APIs", - )); + if request.worker_sms().is_some() { + return Err(invalid( + "persistent worker requires CUDA driver Green Context APIs", + )); + } + return Err(invalid(format!( + "GPU prefix-cache compression requires CUDA driver Green Context APIs{}", + persistent_worker::CPU_CODEC_HINT + ))); } // PyTorch records deprecated CU_CTX_MAP_HOST (0x08) from cuCtxGetFlags(); // CUDA 11+ contexts always map host memory and cuDevicePrimaryCtxSetFlags_v2 @@ -976,18 +995,39 @@ impl NativeResources { unsafe { // Configure recorded limits and Green Context partitions after VA // reservations and mappings so cuCtxSetLimit cannot claim core VA. + let worker = core + .execution + .as_ref() + .and_then(|execution| execution.persistent_workers.first()); + let partition_request = persistent_worker::PartitionRequest::from_options( + worker.map(|w| w.worker_sm_count), + reserve_codec_partition, + )?; + if partition_request.is_some() && !self.primary_context { + return Err(invalid( + "green context partitioning requires primary-context initialization", + )); + } if self.primary_context { apply_context_settings(&driver, self.context, &core.context)?; - if let Some(worker) = core - .execution - .as_ref() - .and_then(|execution| execution.persistent_workers.first()) - { + if let Some(request) = partition_request { + let worker_graph = worker.map(|w| w.graph.as_str()); + let (min_compute_sms, max_cluster_size) = core + .graphs + .iter() + .filter(|g| Some(g.name.as_str()) != worker_graph) + .fold((0u32, 0u32), |(min_sms, max_cluster), g| { + ( + min_sms.max(g.min_compute_sms), + max_cluster.max(g.max_cluster_size), + ) + }); let partition = persistent_worker::GreenContextPartition::create( &driver, self.device, - worker.worker_sm_count, - reserve_codec_partition, + request, + min_compute_sms, + max_cluster_size, )?; let (worker_context, compute_context, codec_context) = ( partition.worker_context, @@ -995,7 +1035,9 @@ impl NativeResources { partition.codec_context, ); self.green_partition = Some(partition); - apply_context_settings(&driver, worker_context, &core.context)?; + if !worker_context.is_null() { + apply_context_settings(&driver, worker_context, &core.context)?; + } apply_context_settings(&driver, compute_context, &core.context)?; if !codec_context.is_null() { apply_context_settings(&driver, codec_context, &core.context)?; @@ -1145,24 +1187,57 @@ impl NativeResources { .and_then(|execution| execution.persistent_workers.first()) .map(|worker| worker.graph.as_str()); for graph in &core.graphs { - let (graph_context, upload_stream, partition_sms) = + let (graph_context, upload_stream, partition_sms, compute_coscheduled) = if let Some(partition) = self.green_partition.as_ref() { if worker_graph_name == Some(graph.name.as_str()) { ( partition.worker_context, partition.worker_stream, Some(partition.worker_sm_count), + None, ) } else { ( partition.compute_context, partition.compute_stream, Some(partition.compute_sm_count), + Some(partition.compute_coscheduled_alignment), ) } } else { - (self.context, null_mut(), None) + (self.context, null_mut(), None, None) }; + let codec_hint = if self + .green_partition + .as_ref() + .is_some_and(|p| !p.codec_context.is_null()) + { + persistent_worker::CPU_CODEC_HINT + } else { + "" + }; + if let Some(avail_sms) = partition_sms { + if graph.min_compute_sms > avail_sms { + return Err(invalid(format!( + "graph {} requires at least {} compute SMs, but partition has {avail_sms} SMs{codec_hint}", + graph.name, graph.min_compute_sms + ))); + } + if graph.max_cluster_size > avail_sms { + return Err(invalid(format!( + "graph {} declares cluster size {}, exceeding partition SM count {avail_sms}{codec_hint}", + graph.name, graph.max_cluster_size + ))); + } + } + if let Some(alignment) = compute_coscheduled + && graph.max_cluster_size > alignment + { + return Err(invalid(format!( + "graph {} declares cluster size {}, exceeding compute partition co-scheduled alignment {alignment}{codec_hint}", + graph.name, graph.max_cluster_size + ))); + } driver.check("cuCtxSetCurrent", (driver.context_set)(graph_context))?; let mut handle = null_mut(); driver.check("cuGraphCreate", (driver.graph_create)(&mut handle, 0))?; @@ -1260,6 +1335,28 @@ impl NativeResources { value.as_mut_ptr().cast(), 64, ); + if attribute.id == CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION { + // Per-node check also covers legacy cores whose manifest leaves max_cluster_size at 0. + let cluster_size = kernel_cluster_size_from_bytes(&bytes)?; + if cluster_size > 0 { + if let Some(avail_sms) = partition_sms + && cluster_size > avail_sms + { + return Err(invalid(format!( + "graph {} kernel cluster size {cluster_size} exceeds partition SM count {avail_sms}{codec_hint}", + graph.name + ))); + } + if let Some(alignment) = compute_coscheduled + && cluster_size > alignment + { + return Err(invalid(format!( + "graph {} kernel cluster size {cluster_size} exceeds compute partition co-scheduled alignment {alignment}{codec_hint}", + graph.name + ))); + } + } + } let mut status = (driver.graph_attribute)( result, attribute.id, @@ -1686,10 +1783,11 @@ impl NativeResources { /// CUDA context for host prefix-cache offload streams and GPU codec kernels. /// - /// Persistent-worker cores with GPU compression reserve a disjoint codec green - /// context so codec kernels never contend with cooperative compute SMs. Without - /// a codec partition, offload uses the rank's base context so DMA-only transfers - /// do not bind to the compute green context. + /// When GPU checkpoint compression is enabled, Helios reserves a disjoint codec + /// green context (2-way `(codec, compute)` or 3-way `(worker, codec, compute)`) + /// so codec kernels never contend with cooperative compute SMs. Without a codec + /// partition, offload uses the rank's base context so DMA-only transfers do not + /// bind to the compute green context. pub(super) fn offload_context(&self) -> Handle { self.green_partition .as_ref() @@ -2177,7 +2275,7 @@ impl NativeResources { } let mut previous_destroyed = false; if let Some(mut partition) = self.green_partition.take() { - if previous == partition.worker_context + if (!partition.worker_context.is_null() && previous == partition.worker_context) || previous == partition.compute_context || (!partition.codec_context.is_null() && previous == partition.codec_context) { diff --git a/helios/src/runtime_core/model.rs b/helios/src/runtime_core/model.rs index dd682c9a8..6dcffc45c 100644 --- a/helios/src/runtime_core/model.rs +++ b/helios/src/runtime_core/model.rs @@ -770,6 +770,8 @@ impl NativeModel { } else { None }; + let reserve_codec_partition = options.prefix_cache.enabled() + && options.prefix_cache.compression == crate::offload::KvCompression::Gpu; let phase = progress.phase( if devices.len() == 1 { "Initialize GPU" @@ -779,9 +781,11 @@ impl NativeModel { None, ); for (core, device) in cores.iter().zip(devices) { - model - .ranks - .push(NativeResources::initialize(core, *device)?); + model.ranks.push(NativeResources::initialize_with_options( + core, + *device, + reserve_codec_partition, + )?); } let rank_devices: Vec<_> = model.ranks.iter().map(|rank| rank.device).collect(); for (owner, rank) in model.ranks.iter_mut().enumerate() { @@ -907,8 +911,6 @@ impl NativeModel { .sum::(); let modules = cores.iter().map(|p| p.modules.len() as u64).sum::(); let phase = progress.phase("Prepare kernels", Some(kernels + modules)); - let reserve_codec_partition = options.prefix_cache.enabled() - && options.prefix_cache.compression == crate::offload::KvCompression::Gpu; model.parallel(&cores, &files, |rank, core, path| { rank.prepare_kernels( path, diff --git a/helios/src/runtime_core/persistent_worker.rs b/helios/src/runtime_core/persistent_worker.rs index 9c3ba31c8..85f69f9de 100644 --- a/helios/src/runtime_core/persistent_worker.rs +++ b/helios/src/runtime_core/persistent_worker.rs @@ -6,7 +6,8 @@ //! Generic persistent-worker CUDA Green Context partition and lifecycle controller. -use std::ffi::c_int; +use std::ffi::{c_int, c_uint}; +use std::num::NonZeroU32; use std::ptr::null_mut; use std::sync::atomic::{AtomicU8, AtomicU32, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, RwLock}; @@ -16,13 +17,64 @@ pub use crate::execution::WorkerState; use crate::execution::{PersistentWorkerControl, PersistentWorkerSnapshot}; use super::driver::{ - CU_DEV_RESOURCE_TYPE_SM, CU_DEV_SM_RESOURCE_GROUP_BACKFILL, CU_GREEN_CTX_DEFAULT_STREAM, + CU_DEV_RESOURCE_TYPE_SM, CU_DEV_SM_RESOURCE_GROUP_BACKFILL, + CU_DEV_SM_RESOURCE_SPLIT_MAX_POTENTIAL_CLUSTER_SIZE, CU_GREEN_CTX_DEFAULT_STREAM, CU_STREAM_NON_BLOCKING, CUDA_ERROR_NOT_READY, DevResource, DevSmResource, DevSmResourceGroupParams, Driver, Handle, }; use super::format::invalid; use crate::{Error, ExecutionError, Result}; +/// Actionable CLI hint appended when GPU prefix-cache compression cannot form a Green Context partition. +pub(super) const CPU_CODEC_HINT: &str = "; use --lossless-kv-compression cpu"; + +/// Requested SM partition topology for [`GreenContextPartition::create`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum PartitionRequest { + /// Two-way `(worker, compute)` split for a persistent worker without GPU codec isolation. + Worker(NonZeroU32), + /// Two-way `(codec, compute)` split for GPU prefix-cache compression without a worker. + Codec, + /// Three-way `(worker, codec, compute)` split for a persistent worker with GPU compression. + WorkerAndCodec(NonZeroU32), +} + +impl PartitionRequest { + pub(super) fn from_options( + worker_sm_count: Option, + reserve_codec_partition: bool, + ) -> Result> { + match (worker_sm_count, reserve_codec_partition) { + (None, false) => Ok(None), + (Some(0), _) => Err(invalid( + "persistent worker requires a positive worker_sm_count", + )), + (Some(count), false) => Ok(Some(Self::Worker(NonZeroU32::new(count).unwrap()))), + (None, true) => Ok(Some(Self::Codec)), + (Some(count), true) => Ok(Some(Self::WorkerAndCodec(NonZeroU32::new(count).unwrap()))), + } + } + + pub(super) fn worker_sms(self) -> Option { + match self { + Self::Worker(count) | Self::WorkerAndCodec(count) => Some(count.get()), + Self::Codec => None, + } + } + + pub(super) fn reserves_codec(self) -> bool { + matches!(self, Self::Codec | Self::WorkerAndCodec(_)) + } + + pub(super) fn cpu_codec_hint(self) -> &'static str { + if self.reserves_codec() { + CPU_CODEC_HINT + } else { + "" + } + } +} + /// Maximum time `PersistentWorkerRuntime::stop` polls `cuStreamQuery` after setting `stop_flag`. const WORKER_DRAIN_TIMEOUT: Duration = Duration::from_secs(5); const WORKER_DRAIN_SPIN_POLLS: u32 = 64; @@ -31,7 +83,12 @@ const WORKER_DRAIN_POLL_INTERVAL: Duration = Duration::from_millis(1); /// device reports at least 8-SM co-scheduling alignment and at least 16 remaining compute SMs. const PREFERRED_COMPUTE_COSCHEDULED_SMS: u32 = 16; -/// Partitioned CUDA Green Contexts and non-blocking streams for a core with a persistent worker. +/// Partitioned CUDA Green Contexts and non-blocking streams for SM-isolated execution. +/// +/// Supports three partition topologies: +/// - 2-way `(worker, compute)` for persistent-worker cores without GPU KV compression, +/// - 2-way `(codec, compute)` for non-worker cores with GPU KV compression, +/// - 3-way `(worker, codec, compute)` for persistent-worker cores with GPU KV compression. pub(super) struct GreenContextPartition { pub(super) worker_green_ctx: Handle, pub(super) codec_green_ctx: Handle, @@ -51,47 +108,67 @@ pub(super) struct GreenContextPartition { // `NativeResources`, which serializes creation and teardown. unsafe impl Send for GreenContextPartition {} -/// Planned `cuDevSmResourceSplit` requests for the worker, optional GPU codec, and compute groups. +/// Planned SM partition parameters for the optional worker, optional GPU codec, and compute groups. struct SmSplitPlan { + request: PartitionRequest, primary: Vec, fallback: Option>, + worker_index: Option, codec_index: Option, compute_index: usize, + aligned_worker_sms: Option, + aligned_codec_sms: Option, + baseline_coscheduled: u32, min_compute_coscheduled: u32, + min_compute_sms: u32, + required_compute_sms: u32, } -/// Plan two or three structured SM resource groups for `cuDevSmResourceSplit`: -/// group 0 receives `requested_worker_sms` rounded up to the device's co-scheduled SM alignment; -/// when `reserve_codec_partition` is true, group 1 receives one minimal aligned SM partition for -/// GPU KV-codec execution so codec kernels never contend with cooperative compute SMs; -/// and the final group uses discovery mode (`sm_count = 0`) with `CU_DEV_SM_RESOURCE_GROUP_BACKFILL` -/// to claim all remaining SMs while preserving co-scheduled SM alignment for multi-CTA clusters. +/// Plan two or three structured SM resource groups for `cuDevSmResourceSplit` (or the CUDA 13.0 +/// `cuDevSmResourceSplitByCount` fallback): +/// - when `request` includes a persistent worker, a worker group receives its requested SM count +/// rounded up to the device's co-scheduled SM alignment; +/// - when `request` reserves GPU KV-codec execution, a codec group receives one minimal aligned SM +/// partition so codec kernels never contend with cooperative compute SMs; +/// - the final compute group uses discovery mode (`sm_count = 0`) with +/// `CU_DEV_SM_RESOURCE_GROUP_BACKFILL` to claim all remaining SMs while preserving co-scheduled +/// SM alignment for multi-CTA clusters and meeting any declared `min_compute_sms` / `max_cluster_size` +/// bounds. /// -/// When the device reports at least 8-SM co-scheduled alignment and at least 16 compute SMs remain, -/// `primary` requests `coscheduled_sm_count = 16` on the compute group so kernels opting into -/// non-portable 16-CTA clusters can instantiate in the compute green context, with `fallback` -/// retrying at the device's baseline alignment if the driver rejects 16. +/// When `max_cluster_size` does not already force a wider alignment, the device reports at least +/// 8-SM co-scheduled alignment, and at least 16 compute SMs remain, `primary` requests +/// `coscheduled_sm_count = 16` on the compute group with `fallback` retrying at the baseline +/// alignment if the driver rejects 16. fn plan_sm_split( device_sm: DevSmResource, - requested_worker_sms: u32, - reserve_codec_partition: bool, + request: PartitionRequest, + min_compute_sms: u32, + max_cluster_size: u32, ) -> Result { let total_sms = device_sm.sm_count; if total_sms == 0 { return Err(invalid("device reported zero streaming multiprocessors")); } - if requested_worker_sms == 0 { - return Err(invalid( - "persistent worker requires a positive worker_sm_count", - )); - } let coscheduled = device_sm.sm_coscheduled_alignment.max(2); let min_partition = device_sm.min_sm_partition_size.max(coscheduled); - let aligned_worker = requested_worker_sms - .max(min_partition) - .checked_next_multiple_of(coscheduled) - .ok_or_else(|| invalid("persistent worker SM request overflows alignment"))?; - let aligned_codec = reserve_codec_partition + let required_compute_coscheduled = if max_cluster_size > coscheduled { + max_cluster_size + .checked_next_multiple_of(coscheduled) + .ok_or_else(|| invalid("graph max_cluster_size overflows co-scheduled SM alignment"))? + } else { + coscheduled + }; + let aligned_worker = request + .worker_sms() + .map(|requested| { + requested + .max(min_partition) + .checked_next_multiple_of(coscheduled) + .ok_or_else(|| invalid("persistent worker SM request overflows alignment")) + }) + .transpose()?; + let aligned_codec = request + .reserves_codec() .then(|| { min_partition .checked_next_multiple_of(coscheduled) @@ -99,28 +176,54 @@ fn plan_sm_split( }) .transpose()?; let reserved_sms = aligned_worker + .unwrap_or(0) .checked_add(aligned_codec.unwrap_or(0)) - .ok_or_else(|| invalid("persistent worker SM request overflows alignment"))?; - if reserved_sms >= total_sms || total_sms - reserved_sms < min_partition { - let message = match aligned_codec { - Some(codec_sms) => format!( - "persistent worker ({aligned_worker} SMs) and GPU codec partition ({codec_sms} SMs) at co-scheduled alignment {coscheduled} out of {total_sms} leave insufficient structured compute SMs for GPU checkpoint compression; use --lossless-kv-compression cpu" + .ok_or_else(|| invalid("green context SM reservation overflows alignment"))?; + let required_compute_sms = min_partition + .max(min_compute_sms) + .max(required_compute_coscheduled); + if reserved_sms >= total_sms || total_sms - reserved_sms < required_compute_sms { + let remaining = total_sms.saturating_sub(reserved_sms); + let requirement_detail = if min_compute_sms > min_partition || max_cluster_size > coscheduled { + format!( + " (remaining {remaining} SMs < required {required_compute_sms} SMs for min_compute_sms={min_compute_sms}, max_cluster_size={max_cluster_size})" + ) + } else { + String::new() + }; + let message = match request { + PartitionRequest::WorkerAndCodec(_) => format!( + "persistent worker ({} SMs) and GPU codec partition ({} SMs) at co-scheduled alignment {coscheduled} out of {total_sms} leave insufficient structured compute SMs{requirement_detail} for GPU checkpoint compression{CPU_CODEC_HINT}", + aligned_worker.unwrap(), + aligned_codec.unwrap(), + ), + PartitionRequest::Codec => format!( + "GPU codec partition ({} SMs) at co-scheduled alignment {coscheduled} out of {total_sms} leaves insufficient structured compute SMs{requirement_detail} for GPU checkpoint compression{CPU_CODEC_HINT}", + aligned_codec.unwrap(), ), - None => format!( - "persistent worker requested {requested_worker_sms} SMs (aligned to {aligned_worker} at co-scheduled alignment {coscheduled}) out of {total_sms}, leaving insufficient structured compute SMs" + PartitionRequest::Worker(requested) => format!( + "persistent worker requested {requested} SMs (aligned to {} at co-scheduled alignment {coscheduled}) out of {total_sms}, leaving insufficient structured compute SMs{requirement_detail}", + aligned_worker.unwrap(), ), }; return Err(invalid(message)); } - let mut base_params = Vec::with_capacity(if aligned_codec.is_some() { 3 } else { 2 }); - base_params.push(DevSmResourceGroupParams { - sm_count: aligned_worker, - coscheduled_sm_count: coscheduled, - preferred_coscheduled_sm_count: 0, - flags: 0, - reserved: [0; 12], + let group_capacity = + usize::from(aligned_worker.is_some()) + usize::from(aligned_codec.is_some()) + 1; + let mut base_params = Vec::with_capacity(group_capacity); + let worker_index = aligned_worker.map(|worker_sms| { + let idx = base_params.len(); + base_params.push(DevSmResourceGroupParams { + sm_count: worker_sms, + coscheduled_sm_count: coscheduled, + preferred_coscheduled_sm_count: 0, + flags: 0, + reserved: [0; 12], + }); + idx }); let codec_index = aligned_codec.map(|codec_sms| { + let idx = base_params.len(); base_params.push(DevSmResourceGroupParams { sm_count: codec_sms, coscheduled_sm_count: coscheduled, @@ -128,51 +231,122 @@ fn plan_sm_split( flags: 0, reserved: [0; 12], }); - 1 + idx }); let compute_index = base_params.len(); base_params.push(DevSmResourceGroupParams { sm_count: 0, - coscheduled_sm_count: coscheduled, + coscheduled_sm_count: required_compute_coscheduled, preferred_coscheduled_sm_count: 0, flags: CU_DEV_SM_RESOURCE_GROUP_BACKFILL, reserved: [0; 12], }); let remaining_sms = total_sms - reserved_sms; - if coscheduled >= 8 - && PREFERRED_COMPUTE_COSCHEDULED_SMS > coscheduled + let (primary, fallback) = if coscheduled >= 8 + && required_compute_coscheduled < PREFERRED_COMPUTE_COSCHEDULED_SMS && remaining_sms >= PREFERRED_COMPUTE_COSCHEDULED_SMS { let mut preferred = base_params.clone(); preferred[compute_index].coscheduled_sm_count = PREFERRED_COMPUTE_COSCHEDULED_SMS; - Ok(SmSplitPlan { - primary: preferred, - fallback: Some(base_params), - codec_index, - compute_index, - min_compute_coscheduled: coscheduled, - }) + (preferred, Some(base_params)) } else { - Ok(SmSplitPlan { - primary: base_params, - fallback: None, - codec_index, - compute_index, - min_compute_coscheduled: coscheduled, - }) + (base_params, None) + }; + Ok(SmSplitPlan { + request, + primary, + fallback, + worker_index, + codec_index, + compute_index, + aligned_worker_sms: aligned_worker, + aligned_codec_sms: aligned_codec, + baseline_coscheduled: coscheduled, + min_compute_coscheduled: required_compute_coscheduled, + min_compute_sms, + required_compute_sms, + }) +} + +/// Plan the structured compute SM target and flag attempts for the CUDA 13.0 +/// `cuDevSmResourceSplitByCount` fallback. +/// +/// Compute is placed in `result[0]` (the structured output) rather than `remainder` so compute +/// retains hardware co-scheduled SM alignment while worker/codec claim the disjoint remainder. +fn plan_split_by_count( + device_sm: DevSmResource, + plan: &SmSplitPlan, +) -> Result<(u32, u32, &'static [c_uint])> { + let reserved_sms = plan + .aligned_worker_sms + .unwrap_or(0) + .saturating_add(plan.aligned_codec_sms.unwrap_or(0)); + let remaining_sms = device_sm.sm_count.saturating_sub(reserved_sms); + let compute_target = (remaining_sms / plan.baseline_coscheduled) * plan.baseline_coscheduled; + if compute_target < plan.required_compute_sms { + let suffix = plan.request.cpu_codec_hint(); + return Err(invalid(format!( + "cuDevSmResourceSplitByCount aligned compute partition ({compute_target} SMs out of {}) is below required {} SMs{suffix}", + device_sm.sm_count, plan.required_compute_sms + ))); + } + let flags: &'static [c_uint] = if plan.min_compute_coscheduled > plan.baseline_coscheduled { + &[CU_DEV_SM_RESOURCE_SPLIT_MAX_POTENTIAL_CLUSTER_SIZE] + } else if plan.fallback.is_some() { + &[CU_DEV_SM_RESOURCE_SPLIT_MAX_POTENTIAL_CLUSTER_SIZE, 0] + } else { + &[0] + }; + Ok((compute_target, reserved_sms, flags)) +} + +/// Validate the actual SM geometry reported by `cuGreenCtxGetDevResource` for the compute +/// green context without inflating or overriding driver-reported alignment. +fn validate_actual_compute_partition( + actual_compute_sm: DevSmResource, + required_min_compute_sms: u32, + required_compute_coscheduled: u32, + max_cluster_size: u32, + structured_split: bool, + request: PartitionRequest, +) -> Result<()> { + let suffix = request.cpu_codec_hint(); + if actual_compute_sm.sm_count == 0 || actual_compute_sm.sm_count < required_min_compute_sms { + return Err(invalid(format!( + "compute green context partition has {} SMs, below required minimum {}{suffix}", + actual_compute_sm.sm_count, + required_min_compute_sms.max(1) + ))); + } + if structured_split { + if actual_compute_sm.sm_coscheduled_alignment < required_compute_coscheduled { + return Err(invalid(format!( + "compute green context partition returned co-scheduled alignment {}, below required {required_compute_coscheduled}{suffix}", + actual_compute_sm.sm_coscheduled_alignment + ))); + } + } else if actual_compute_sm.sm_coscheduled_alignment == 0 + || (max_cluster_size > 1 && actual_compute_sm.sm_coscheduled_alignment < max_cluster_size) + { + return Err(invalid(format!( + "compute green context partition returned co-scheduled alignment {}, below required cluster size {}{suffix}", + actual_compute_sm.sm_coscheduled_alignment, + max_cluster_size.max(1) + ))); } + Ok(()) } /// Invoke `cuDevSmResourceSplit` with the primary split plan and retry with the baseline-aligned /// fallback if the driver rejects the wider compute co-scheduled alignment. fn split_sm_groups( - plan: SmSplitPlan, + plan: &SmSplitPlan, mut invoke: impl FnMut(&mut [DevSmResourceGroupParams]) -> c_int, ) -> (c_int, Vec) { - let mut active = plan.primary; + let mut active = plan.primary.clone(); let status = invoke(&mut active); if status != 0 { - if let Some(mut fallback) = plan.fallback { + if let Some(mut fallback) = plan.fallback.clone() { let fallback_status = invoke(&mut fallback); return (fallback_status, fallback); } @@ -181,20 +355,48 @@ fn split_sm_groups( } impl GreenContextPartition { - /// Split the device's SMs with `cuDevSmResourceSplit` into explicit structured groups: - /// a worker partition of at least `requested_worker_sms`, an optional disjoint GPU codec - /// partition when `reserve_codec_partition` is true, and a co-scheduled compute partition, - /// then create green contexts and non-blocking streams for the worker and compute groups. + /// Split the device's SMs into disjoint partitions: + /// an optional worker partition, an optional GPU codec partition, and a compute partition + /// satisfying `min_compute_sms` and `max_cluster_size`. + /// + /// Uses `cuDevSmResourceSplit` on CUDA 13.1+ drivers and falls back to + /// `cuDevSmResourceSplitByCount` on CUDA 13.0 / R580 drivers. pub(super) unsafe fn create( driver: &Driver, device: i32, - requested_worker_sms: u32, - reserve_codec_partition: bool, + request: PartitionRequest, + min_compute_sms: u32, + max_cluster_size: u32, + ) -> Result { + unsafe { + Self::create_with_strategy( + driver, + device, + request, + min_compute_sms, + max_cluster_size, + true, + ) + } + } + + unsafe fn create_with_strategy( + driver: &Driver, + device: i32, + request: PartitionRequest, + min_compute_sms: u32, + max_cluster_size: u32, + prefer_structured_split: bool, ) -> Result { - let gc = driver - .green_ctx - .as_ref() - .ok_or_else(|| invalid("persistent worker requires CUDA driver Green Context APIs"))?; + let gc = driver.green_ctx.as_ref().ok_or_else(|| { + if request.worker_sms().is_some() { + invalid("persistent worker requires CUDA driver Green Context APIs") + } else { + invalid(format!( + "GPU prefix-cache compression requires CUDA driver Green Context APIs{CPU_CODEC_HINT}" + )) + } + })?; let mut partition = Self { worker_green_ctx: null_mut(), codec_green_ctx: null_mut(), @@ -209,6 +411,7 @@ impl GreenContextPartition { compute_sm_count: 0, compute_coscheduled_alignment: 0, }; + let mut temp_green_ctx: Handle = null_mut(); let setup = (|| -> Result<()> { // SAFETY: Output structs and pointers satisfy cuda.h contracts; any handles created // before an error are released by `cleanup` below. @@ -223,88 +426,261 @@ impl GreenContextPartition { .ok_or_else(|| invalid("device did not report an SM resource"))?; let plan = plan_sm_split( device_sm_info, - requested_worker_sms, - reserve_codec_partition, + request, + min_compute_sms, + max_cluster_size, )?; - let coscheduled = plan.min_compute_coscheduled; - let codec_index = plan.codec_index; - let compute_index = plan.compute_index; - let group_count = plan.primary.len(); - let mut groups = vec![DevResource::zeroed(); group_count]; - let (status, group_params) = split_sm_groups(plan, |params| { - groups.fill(DevResource::zeroed()); - (gc.dev_sm_resource_split)( - groups.as_mut_ptr(), - group_count as u32, - &device_sm, - null_mut(), - 0, - params.as_mut_ptr(), - ) - }); - driver.check("cuDevSmResourceSplit", status)?; - let worker_split = groups[0] - .sm() - .ok_or_else(|| invalid("worker SM split did not return an SM resource"))?; - let compute_split = groups[compute_index] - .sm() - .ok_or_else(|| invalid("compute SM split did not return an SM resource"))?; - if worker_split.sm_count < group_params[0].sm_count || compute_split.sm_count == 0 { - return Err(invalid(format!( - "SM split for persistent worker ({requested_worker_sms} requested out of {}) left no structured compute SMs", - device_sm_info.sm_count - ))); - } - if let Some(idx) = codec_index { - let codec_split = groups[idx] - .sm() - .ok_or_else(|| invalid("codec SM split did not return an SM resource"))?; - if codec_split.sm_count < group_params[idx].sm_count { + let suffix = request.cpu_codec_hint(); + let required_compute_coscheduled = plan.min_compute_coscheduled; + let required_min_compute_sms = plan.min_compute_sms; + let structured_split; + let (mut worker_res, mut codec_res, mut compute_res): ( + Option, + Option, + DevResource, + ) = if let Some(split_structured) = + gc.dev_sm_resource_split.filter(|_| prefer_structured_split) + { + structured_split = true; + let group_count = plan.primary.len(); + let mut groups = vec![DevResource::zeroed(); group_count]; + let (status, group_params) = split_sm_groups(&plan, |params| { + groups.fill(DevResource::zeroed()); + split_structured( + groups.as_mut_ptr(), + group_count as u32, + &device_sm, + null_mut(), + 0, + params.as_mut_ptr(), + ) + }); + driver.check("cuDevSmResourceSplit", status)?; + if let Some(idx) = plan.worker_index { + let worker_split = groups[idx].sm().ok_or_else(|| { + invalid("worker SM split did not return an SM resource") + })?; + if worker_split.sm_count < group_params[idx].sm_count { + return Err(invalid(format!( + "SM split for persistent worker ({} requested out of {}) returned {} SMs", + group_params[idx].sm_count, + device_sm_info.sm_count, + worker_split.sm_count + ))); + } + } + if let Some(idx) = plan.codec_index { + let codec_split = groups[idx].sm().ok_or_else(|| { + invalid("codec SM split did not return an SM resource") + })?; + if codec_split.sm_count < group_params[idx].sm_count { + return Err(invalid(format!( + "SM split for GPU codec ({} requested out of {}) returned {} SMs", + group_params[idx].sm_count, + device_sm_info.sm_count, + codec_split.sm_count + ))); + } + } + let compute_split = groups[plan.compute_index].sm().ok_or_else(|| { + invalid("compute SM split did not return an SM resource") + })?; + if compute_split.sm_count == 0 + || compute_split.sm_count < required_min_compute_sms + { return Err(invalid(format!( - "SM split for GPU codec ({} requested out of {}) returned {} SMs", - group_params[idx].sm_count, + "SM split left {} compute SMs out of {}, below required minimum {}{suffix}", + compute_split.sm_count, device_sm_info.sm_count, - codec_split.sm_count + required_min_compute_sms.max(1) ))); } - } - if compute_split.sm_coscheduled_alignment < coscheduled { + if compute_split.sm_coscheduled_alignment < required_compute_coscheduled { + return Err(invalid(format!( + "compute SM partition co-scheduled alignment {} is below required {required_compute_coscheduled}{suffix}", + compute_split.sm_coscheduled_alignment + ))); + } + ( + plan.worker_index.map(|idx| groups[idx]), + plan.codec_index.map(|idx| groups[idx]), + groups[plan.compute_index], + ) + } else if let Some(split_by_count) = gc.dev_sm_resource_split_by_count { + structured_split = false; + let (compute_target, reserved_sms, flag_attempts) = + plan_split_by_count(device_sm_info, &plan)?; + let mut chosen: Option<(DevResource, DevResource)> = None; + let mut last_error: Option = None; + for &flags in flag_attempts { + let mut compute_out = DevResource::zeroed(); + let mut remainder_out = DevResource::zeroed(); + let mut nb_groups: c_uint = 1; + let status = split_by_count( + &mut compute_out, + &mut nb_groups, + &device_sm, + &mut remainder_out, + flags, + compute_target, + ); + if status != 0 { + last_error = + driver.check("cuDevSmResourceSplitByCount(compute)", status).err(); + continue; + } + if nb_groups != 1 { + last_error = Some(invalid(format!( + "cuDevSmResourceSplitByCount returned {nb_groups} compute groups (expected 1){suffix}" + ))); + continue; + } + let Some(compute_sm) = compute_out.sm() else { + last_error = Some(invalid( + "compute SM split did not return an SM resource", + )); + continue; + }; + let Some(rem_sm) = remainder_out.sm() else { + last_error = Some(invalid( + "SM split remainder did not return an SM resource", + )); + continue; + }; + if compute_sm.sm_count < required_min_compute_sms.max(1) { + last_error = Some(invalid(format!( + "SM split left {} compute SMs out of {}, below required minimum {}{suffix}", + compute_sm.sm_count, + device_sm_info.sm_count, + required_min_compute_sms.max(1) + ))); + continue; + } + if rem_sm.sm_count < reserved_sms { + last_error = Some(invalid(format!( + "SM split remainder ({} SMs) is below reserved {reserved_sms} SMs{suffix}", + rem_sm.sm_count + ))); + continue; + } + chosen = Some((compute_out, remainder_out)); + break; + } + let (compute_out, mut remainder_out) = chosen.ok_or_else(|| { + last_error.unwrap_or_else(|| { + invalid(format!( + "cuDevSmResourceSplitByCount could not partition SMs{suffix}" + )) + }) + })?; + match request { + PartitionRequest::Worker(_) => (Some(remainder_out), None, compute_out), + PartitionRequest::Codec => (None, Some(remainder_out), compute_out), + PartitionRequest::WorkerAndCodec(_) => { + // Refresh remainder through a temporary green context because + // cuDevSmResourceSplitByCount outputs cannot be re-split directly. + let worker_sms = plan.aligned_worker_sms.unwrap(); + let codec_sms = plan.aligned_codec_sms.unwrap(); + let mut rem_desc = null_mut(); + driver.check( + "cuDevResourceGenerateDesc(remainder)", + (gc.dev_resource_generate_desc)(&mut rem_desc, &mut remainder_out, 1), + )?; + driver.check( + "cuGreenCtxCreate(remainder)", + (gc.green_ctx_create)( + &mut temp_green_ctx, + rem_desc, + device, + CU_GREEN_CTX_DEFAULT_STREAM, + ), + )?; + let mut rem_actual = DevResource::zeroed(); + driver.check( + "cuGreenCtxGetDevResource(remainder)", + (gc.green_ctx_get_dev_resource)( + temp_green_ctx, + &mut rem_actual, + CU_DEV_RESOURCE_TYPE_SM, + ), + )?; + let mut worker_out = DevResource::zeroed(); + let mut codec_out = DevResource::zeroed(); + let mut nb_worker: c_uint = 1; + driver.check( + "cuDevSmResourceSplitByCount(worker)", + split_by_count( + &mut worker_out, + &mut nb_worker, + &rem_actual, + &mut codec_out, + 0, + worker_sms, + ), + )?; + if nb_worker != 1 { + return Err(invalid(format!( + "cuDevSmResourceSplitByCount returned {nb_worker} worker groups (expected 1){suffix}" + ))); + } + let worker_sm = worker_out.sm().ok_or_else(|| { + invalid("worker SM split did not return an SM resource") + })?; + if worker_sm.sm_count < worker_sms { + return Err(invalid(format!( + "SM split for persistent worker ({worker_sms} requested out of {}) returned {} SMs", + device_sm_info.sm_count, worker_sm.sm_count + ))); + } + let codec_sm = codec_out.sm().ok_or_else(|| { + invalid("codec SM split did not return an SM resource") + })?; + if codec_sm.sm_count < codec_sms { + return Err(invalid(format!( + "SM split for GPU codec ({codec_sms} requested out of {}) returned {} SMs{suffix}", + device_sm_info.sm_count, codec_sm.sm_count + ))); + } + (Some(worker_out), Some(codec_out), compute_out) + } + } + } else { return Err(invalid(format!( - "compute SM partition co-scheduled alignment {} is below required {coscheduled}", - compute_split.sm_coscheduled_alignment + "CUDA driver exports neither cuDevSmResourceSplit nor cuDevSmResourceSplitByCount{suffix}" ))); - } + }; + let mut worker_desc = null_mut(); - driver.check( - "cuDevResourceGenerateDesc(worker)", - (gc.dev_resource_generate_desc)(&mut worker_desc, &mut groups[0], 1), - )?; + if let Some(res) = worker_res.as_mut() { + driver.check( + "cuDevResourceGenerateDesc(worker)", + (gc.dev_resource_generate_desc)(&mut worker_desc, res, 1), + )?; + } let mut codec_desc = null_mut(); - if let Some(idx) = codec_index { + if let Some(res) = codec_res.as_mut() { driver.check( "cuDevResourceGenerateDesc(codec)", - (gc.dev_resource_generate_desc)(&mut codec_desc, &mut groups[idx], 1), + (gc.dev_resource_generate_desc)(&mut codec_desc, res, 1), )?; } let mut compute_desc = null_mut(); driver.check( "cuDevResourceGenerateDesc(compute)", - (gc.dev_resource_generate_desc)( - &mut compute_desc, - &mut groups[compute_index], - 1, - ), - )?; - driver.check( - "cuGreenCtxCreate(worker)", - (gc.green_ctx_create)( - &mut partition.worker_green_ctx, - worker_desc, - device, - CU_GREEN_CTX_DEFAULT_STREAM, - ), + (gc.dev_resource_generate_desc)(&mut compute_desc, &mut compute_res, 1), )?; - if codec_index.is_some() { + if worker_res.is_some() { + driver.check( + "cuGreenCtxCreate(worker)", + (gc.green_ctx_create)( + &mut partition.worker_green_ctx, + worker_desc, + device, + CU_GREEN_CTX_DEFAULT_STREAM, + ), + )?; + } + if codec_res.is_some() { driver.check( "cuGreenCtxCreate(codec)", (gc.green_ctx_create)( @@ -324,15 +700,24 @@ impl GreenContextPartition { CU_GREEN_CTX_DEFAULT_STREAM, ), )?; - let mut actual_worker = DevResource::zeroed(); - driver.check( - "cuGreenCtxGetDevResource(worker)", - (gc.green_ctx_get_dev_resource)( - partition.worker_green_ctx, - &mut actual_worker, - CU_DEV_RESOURCE_TYPE_SM, - ), - )?; + if worker_res.is_some() { + let mut actual_worker = DevResource::zeroed(); + driver.check( + "cuGreenCtxGetDevResource(worker)", + (gc.green_ctx_get_dev_resource)( + partition.worker_green_ctx, + &mut actual_worker, + CU_DEV_RESOURCE_TYPE_SM, + ), + )?; + let actual_worker_sm = actual_worker.sm().ok_or_else(|| { + invalid("worker green context did not report an SM resource") + })?; + partition.worker_sm_count = actual_worker_sm.sm_count; + if partition.worker_sm_count == 0 { + return Err(invalid("worker green context partition has zero SMs")); + } + } let mut actual_compute = DevResource::zeroed(); driver.check( "cuGreenCtxGetDevResource(compute)", @@ -342,16 +727,12 @@ impl GreenContextPartition { CU_DEV_RESOURCE_TYPE_SM, ), )?; - let actual_worker_sm = actual_worker - .sm() - .ok_or_else(|| invalid("worker green context did not report an SM resource"))?; let actual_compute_sm = actual_compute .sm() .ok_or_else(|| invalid("compute green context did not report an SM resource"))?; - partition.worker_sm_count = actual_worker_sm.sm_count; partition.compute_sm_count = actual_compute_sm.sm_count; partition.compute_coscheduled_alignment = actual_compute_sm.sm_coscheduled_alignment; - if codec_index.is_some() { + if codec_res.is_some() { let mut actual_codec = DevResource::zeroed(); driver.check( "cuGreenCtxGetDevResource(codec)", @@ -369,21 +750,23 @@ impl GreenContextPartition { return Err(invalid("codec green context partition has zero SMs")); } } - if partition.worker_sm_count == 0 - || partition.compute_sm_count == 0 - || partition.compute_coscheduled_alignment < coscheduled - { - return Err(invalid( - "green context partition has zero SMs or lost co-scheduled alignment", - )); - } - driver.check( - "cuCtxFromGreenCtx(worker)", - (gc.ctx_from_green_ctx)( - &mut partition.worker_context, - partition.worker_green_ctx, - ), + validate_actual_compute_partition( + actual_compute_sm, + required_min_compute_sms, + required_compute_coscheduled, + max_cluster_size, + structured_split, + request, )?; + if !partition.worker_green_ctx.is_null() { + driver.check( + "cuCtxFromGreenCtx(worker)", + (gc.ctx_from_green_ctx)( + &mut partition.worker_context, + partition.worker_green_ctx, + ), + )?; + } if !partition.codec_green_ctx.is_null() { driver.check( "cuCtxFromGreenCtx(codec)", @@ -400,15 +783,17 @@ impl GreenContextPartition { partition.compute_green_ctx, ), )?; - driver.check( - "cuGreenCtxStreamCreate(worker)", - (gc.green_ctx_stream_create)( - &mut partition.worker_stream, - partition.worker_green_ctx, - CU_STREAM_NON_BLOCKING, - 0, - ), - )?; + if !partition.worker_green_ctx.is_null() { + driver.check( + "cuGreenCtxStreamCreate(worker)", + (gc.green_ctx_stream_create)( + &mut partition.worker_stream, + partition.worker_green_ctx, + CU_STREAM_NON_BLOCKING, + 0, + ), + )?; + } driver.check( "cuGreenCtxStreamCreate(compute)", (gc.green_ctx_stream_create)( @@ -421,6 +806,12 @@ impl GreenContextPartition { Ok(()) } })(); + if !temp_green_ctx.is_null() { + // SAFETY: Temporary remainder green context has no streams or work launched on it. + unsafe { + (gc.green_ctx_destroy)(temp_green_ctx); + } + } if let Err(error) = setup { // SAFETY: No work was launched on these newly created streams or contexts. unsafe { @@ -1057,14 +1448,34 @@ mod tests { #[test] fn plan_sm_split_aligns_worker_and_discovers_structured_compute_group() { + let worker = |n| PartitionRequest::Worker(NonZeroU32::new(n).unwrap()); + let worker_codec = |n| PartitionRequest::WorkerAndCodec(NonZeroU32::new(n).unwrap()); + + assert_eq!(PartitionRequest::from_options(None, false).unwrap(), None); + assert!(PartitionRequest::from_options(Some(0), false).is_err()); + assert!(PartitionRequest::from_options(Some(0), true).is_err()); + assert_eq!( + PartitionRequest::from_options(None, true).unwrap(), + Some(PartitionRequest::Codec) + ); + assert_eq!( + PartitionRequest::from_options(Some(8), false).unwrap(), + Some(worker(8)) + ); + assert_eq!( + PartitionRequest::from_options(Some(8), true).unwrap(), + Some(worker_codec(8)) + ); + let sm103 = DevSmResource { sm_count: 152, min_sm_partition_size: 8, sm_coscheduled_alignment: 8, flags: 0, }; - let plan = plan_sm_split(sm103, 8, false).unwrap(); + let plan = plan_sm_split(sm103, worker(8), 0, 0).unwrap(); assert_eq!(plan.min_compute_coscheduled, 8); + assert_eq!(plan.worker_index, Some(0)); assert_eq!(plan.codec_index, None); assert_eq!(plan.compute_index, 1); assert_eq!(plan.primary.len(), 2); @@ -1080,26 +1491,57 @@ mod tests { assert_eq!(fallback[1].flags, CU_DEV_SM_RESOURCE_GROUP_BACKFILL); // Unaligned requests round up to co-scheduled alignment. - let rounded = plan_sm_split(sm103, 4, false).unwrap(); + let rounded = plan_sm_split(sm103, worker(4), 0, 0).unwrap(); assert_eq!(rounded.primary[0].sm_count, 8); assert_eq!(rounded.primary[1].coscheduled_sm_count, 16); - let rounded_12 = plan_sm_split(sm103, 12, false).unwrap(); + let rounded_12 = plan_sm_split(sm103, worker(12), 0, 0).unwrap(); assert_eq!(rounded_12.primary[0].sm_count, 16); assert_eq!(rounded_12.primary[1].coscheduled_sm_count, 16); // Remaining compute SMs below 16 stay at the device's baseline co-scheduled alignment. - let narrow = plan_sm_split(sm103, 144, false).unwrap(); + let narrow = plan_sm_split(sm103, worker(144), 0, 0).unwrap(); assert_eq!(narrow.primary[0].sm_count, 144); assert_eq!(narrow.primary[1].coscheduled_sm_count, 8); assert!(narrow.fallback.is_none()); // Requests leaving fewer than one aligned compute partition fail. - assert!(plan_sm_split(sm103, 0, false).is_err()); - assert!(plan_sm_split(sm103, 145, false).is_err()); - assert!(plan_sm_split(sm103, 152, false).is_err()); + assert!(plan_sm_split(sm103, worker(145), 0, 0).is_err()); + assert!(plan_sm_split(sm103, worker(152), 0, 0).is_err()); + + // Two-way (codec, compute) split without a persistent worker isolates codec SMs fleet-wide. + let two_way_codec = plan_sm_split(sm103, PartitionRequest::Codec, 0, 0).unwrap(); + assert_eq!(two_way_codec.worker_index, None); + assert_eq!(two_way_codec.codec_index, Some(0)); + assert_eq!(two_way_codec.compute_index, 1); + assert_eq!(two_way_codec.primary.len(), 2); + assert_eq!(two_way_codec.primary[0].sm_count, 8); + assert_eq!(two_way_codec.primary[0].coscheduled_sm_count, 8); + assert_eq!(two_way_codec.primary[0].flags, 0); + assert_eq!(two_way_codec.primary[1].sm_count, 0); + assert_eq!(two_way_codec.primary[1].coscheduled_sm_count, 16); + assert_eq!(two_way_codec.primary[1].flags, CU_DEV_SM_RESOURCE_GROUP_BACKFILL); + assert!(two_way_codec.fallback.is_some()); + + // Explicit max_cluster_size=16 requires 16-SM co-scheduling with no fallback to 8. + let cluster16 = plan_sm_split(sm103, PartitionRequest::Codec, 128, 16).unwrap(); + assert_eq!(cluster16.min_compute_coscheduled, 16); + assert_eq!(cluster16.min_compute_sms, 128); + assert_eq!(cluster16.primary[1].coscheduled_sm_count, 16); + assert!(cluster16.fallback.is_none()); + + // Insufficient compute SMs for declared min_compute_sms fails closed with CPU fallback hint. + let min_sm_err = plan_sm_split(sm103, PartitionRequest::Codec, 148, 8) + .err() + .expect("144 remaining SMs cannot satisfy min_compute_sms=148") + .to_string(); + assert!( + min_sm_err.contains("--lossless-kv-compression cpu") && min_sm_err.contains("148"), + "unexpected min_compute_sms error: {min_sm_err}" + ); // Three-way split reserves one aligned codec partition while keeping 16-CTA compute alignment. - let three_way = plan_sm_split(sm103, 8, true).unwrap(); + let three_way = plan_sm_split(sm103, worker_codec(8), 0, 0).unwrap(); + assert_eq!(three_way.worker_index, Some(0)); assert_eq!(three_way.codec_index, Some(1)); assert_eq!(three_way.compute_index, 2); assert_eq!(three_way.primary.len(), 3); @@ -1120,7 +1562,7 @@ mod tests { sm_coscheduled_alignment: 8, flags: 0, }; - let small_err = plan_sm_split(small_sm103, 8, true) + let small_err = plan_sm_split(small_sm103, worker_codec(8), 0, 0) .err() .expect("16-SM device cannot fit three 8-SM partitions") .to_string(); @@ -1136,7 +1578,7 @@ mod tests { sm_coscheduled_alignment: 2, flags: 0, }; - let plan80 = plan_sm_split(sm80, 6, false).unwrap(); + let plan80 = plan_sm_split(sm80, worker(6), 0, 0).unwrap(); assert_eq!(plan80.min_compute_coscheduled, 2); assert_eq!(plan80.primary[0].sm_count, 6); assert_eq!(plan80.primary[0].coscheduled_sm_count, 2); @@ -1144,7 +1586,7 @@ mod tests { assert_eq!(plan80.primary[1].coscheduled_sm_count, 2); assert_eq!(plan80.primary[1].flags, CU_DEV_SM_RESOURCE_GROUP_BACKFILL); assert!(plan80.fallback.is_none()); - let plan80_codec = plan_sm_split(sm80, 6, true).unwrap(); + let plan80_codec = plan_sm_split(sm80, worker_codec(6), 0, 0).unwrap(); assert_eq!(plan80_codec.codec_index, Some(1)); assert_eq!(plan80_codec.compute_index, 2); assert_eq!(plan80_codec.primary[1].sm_count, 2); @@ -1154,6 +1596,8 @@ mod tests { #[test] fn split_sm_groups_retries_baseline_alignment_when_driver_rejects_cluster16() { + let worker = |n| PartitionRequest::Worker(NonZeroU32::new(n).unwrap()); + let worker_codec = |n| PartitionRequest::WorkerAndCodec(NonZeroU32::new(n).unwrap()); let sm103 = DevSmResource { sm_count: 152, min_sm_partition_size: 8, @@ -1163,7 +1607,8 @@ mod tests { // Primary 16-SM compute alignment succeeds without invoking fallback. let mut seen = Vec::new(); - let (status, active) = split_sm_groups(plan_sm_split(sm103, 8, false).unwrap(), |params| { + let plan = plan_sm_split(sm103, worker(8), 0, 0).unwrap(); + let (status, active) = split_sm_groups(&plan, |params| { seen.push(params[1].coscheduled_sm_count); 0 }); @@ -1173,7 +1618,7 @@ mod tests { // Driver rejection of 16 falls back to the device's 8-SM co-scheduled alignment. let mut seen_fallback = Vec::new(); - let (status, active) = split_sm_groups(plan_sm_split(sm103, 8, false).unwrap(), |params| { + let (status, active) = split_sm_groups(&plan, |params| { seen_fallback.push(params[1].coscheduled_sm_count); if params[1].coscheduled_sm_count == 16 { 1 @@ -1187,7 +1632,8 @@ mod tests { // Three-way fallback also retries compute group 2 at baseline alignment. let mut seen_three = Vec::new(); - let (status, active) = split_sm_groups(plan_sm_split(sm103, 8, true).unwrap(), |params| { + let plan_three = plan_sm_split(sm103, worker_codec(8), 0, 0).unwrap(); + let (status, active) = split_sm_groups(&plan_three, |params| { assert_eq!(params.len(), 3); seen_three.push(params[2].coscheduled_sm_count); if params[2].coscheduled_sm_count == 16 { @@ -1199,6 +1645,114 @@ mod tests { assert_eq!(status, 0); assert_eq!(seen_three, vec![16, 8]); assert_eq!(active[2].coscheduled_sm_count, 8); + + // Two-way (codec, compute) fallback retries compute group 1 at baseline alignment. + let mut seen_two_codec = Vec::new(); + let plan_two_codec = plan_sm_split(sm103, PartitionRequest::Codec, 0, 0).unwrap(); + let (status, active) = split_sm_groups(&plan_two_codec, |params| { + assert_eq!(params.len(), 2); + seen_two_codec.push(params[1].coscheduled_sm_count); + if params[1].coscheduled_sm_count == 16 { + 1 + } else { + 0 + } + }); + assert_eq!(status, 0); + assert_eq!(seen_two_codec, vec![16, 8]); + assert_eq!(active[1].coscheduled_sm_count, 8); + } + + #[test] + fn plan_split_by_count_and_actual_alignment_validation_cover_r580_and_downgrades() { + let worker_codec = PartitionRequest::WorkerAndCodec(NonZeroU32::new(8).unwrap()); + let gb10 = DevSmResource { + sm_count: 48, + min_sm_partition_size: 8, + sm_coscheduled_alignment: 8, + flags: 0, + }; + let two_way_gb10 = plan_sm_split(gb10, PartitionRequest::Codec, 0, 0).unwrap(); + let (compute_target, reserved, flags) = plan_split_by_count(gb10, &two_way_gb10).unwrap(); + assert_eq!((compute_target, reserved), (40, 8)); + assert_eq!(flags, &[CU_DEV_SM_RESOURCE_SPLIT_MAX_POTENTIAL_CLUSTER_SIZE, 0]); + + let three_way_gb10 = plan_sm_split(gb10, worker_codec, 0, 0).unwrap(); + let (compute_target, reserved, flags) = + plan_split_by_count(gb10, &three_way_gb10).unwrap(); + assert_eq!((compute_target, reserved), (32, 16)); + assert_eq!(flags, &[CU_DEV_SM_RESOURCE_SPLIT_MAX_POTENTIAL_CLUSTER_SIZE, 0]); + + // Non-multiple-of-8 device (188-SM SM120) floors compute_target to an 8-SM multiple. + let sm120 = DevSmResource { + sm_count: 188, + min_sm_partition_size: 8, + sm_coscheduled_alignment: 8, + flags: 0, + }; + let two_way_120 = plan_sm_split(sm120, PartitionRequest::Codec, 0, 0).unwrap(); + let (compute_target, reserved, _) = plan_split_by_count(sm120, &two_way_120).unwrap(); + assert_eq!((compute_target, reserved), (176, 8)); + + // Explicit max_cluster_size=16 tries only MAX_POTENTIAL_CLUSTER_SIZE without flags=0 fallback. + let cluster16 = plan_sm_split(sm120, PartitionRequest::Codec, 128, 16).unwrap(); + let (_, _, flags16) = plan_split_by_count(sm120, &cluster16).unwrap(); + assert_eq!(flags16, &[CU_DEV_SM_RESOURCE_SPLIT_MAX_POTENTIAL_CLUSTER_SIZE]); + + // If min_compute_sms exceeds the aligned SplitByCount target (180 > 176), fail closed. + let tight_120 = plan_sm_split(sm120, PartitionRequest::Codec, 180, 0).unwrap(); + let err = plan_split_by_count(sm120, &tight_120).unwrap_err().to_string(); + assert!(err.contains("--lossless-kv-compression cpu"), "{err}"); + + // Structured split must reject driver downgrade below required alignment (8 < 16). + let downgraded = DevSmResource { + sm_count: 144, + min_sm_partition_size: 2, + sm_coscheduled_alignment: 8, + flags: 0, + }; + assert!( + validate_actual_compute_partition( + downgraded, + 128, + 16, + 16, + true, + PartitionRequest::Codec, + ) + .is_err() + ); + let honored = DevSmResource { + sm_coscheduled_alignment: 16, + ..downgraded + }; + validate_actual_compute_partition(honored, 128, 16, 16, true, PartitionRequest::Codec) + .unwrap(); + + // Count-based split on GB10 R580 accepts TPC granularity 2 when no graph needs > 2 clusters, + // rejects 0 alignment, and rejects any graph declaring max_cluster_size > 2. + let gb10_tpc2 = DevSmResource { + sm_count: 40, + min_sm_partition_size: 2, + sm_coscheduled_alignment: 2, + flags: 0, + }; + validate_actual_compute_partition(gb10_tpc2, 0, 8, 0, false, PartitionRequest::Codec) + .unwrap(); + validate_actual_compute_partition(gb10_tpc2, 0, 8, 1, false, PartitionRequest::Codec) + .unwrap(); + assert!( + validate_actual_compute_partition(gb10_tpc2, 0, 8, 4, false, PartitionRequest::Codec) + .is_err() + ); + let zero_align = DevSmResource { + sm_coscheduled_alignment: 0, + ..gb10_tpc2 + }; + assert!( + validate_actual_compute_partition(zero_align, 0, 8, 0, false, PartitionRequest::Codec) + .is_err() + ); } #[test] @@ -1670,6 +2224,8 @@ extern "C" __global__ void cluster_2cta(int* out) { node_count: 1, edge_count: 0, functions: vec![0], + min_compute_sms: 0, + max_cluster_size: 0, }, Graph { name: "coop_step".into(), @@ -1678,6 +2234,8 @@ extern "C" __global__ void cluster_2cta(int* out) { node_count: 2, edge_count: 1, functions: vec![1], + min_compute_sms: 0, + max_cluster_size: 0, }, Graph { name: "cluster_step".into(), @@ -1686,6 +2244,8 @@ extern "C" __global__ void cluster_2cta(int* out) { node_count: 1, edge_count: 0, functions: vec![2], + min_compute_sms: 0, + max_cluster_size: 0, }, ], reservations: vec![Reservation { @@ -2121,9 +2681,9 @@ extern "C" __global__ void step_emit_completion( Function { id: 2, module: "exec_mod".into(), symbol: "step_emit_completion".into(), parameter_sizes: vec![8, 8, 8, 8], attributes: vec![] }, ], graphs: vec![ - Graph { name: "worker_spin".into(), flags: 0, resource: "g_worker".into(), node_count: 1, edge_count: 0, functions: vec![0] }, - Graph { name: "startup_tune".into(), flags: 0, resource: "g_tune".into(), node_count: 1, edge_count: 0, functions: vec![1] }, - Graph { name: "decode_b1".into(), flags: 0, resource: "g_decode".into(), node_count: 1, edge_count: 0, functions: vec![2] }, + Graph { name: "worker_spin".into(), flags: 0, resource: "g_worker".into(), node_count: 1, edge_count: 0, functions: vec![0], min_compute_sms: 0, max_cluster_size: 0 }, + Graph { name: "startup_tune".into(), flags: 0, resource: "g_tune".into(), node_count: 1, edge_count: 0, functions: vec![1], min_compute_sms: 0, max_cluster_size: 0 }, + Graph { name: "decode_b1".into(), flags: 0, resource: "g_decode".into(), node_count: 1, edge_count: 0, functions: vec![2], min_compute_sms: 0, max_cluster_size: 0 }, ], reservations: vec![Reservation { address: device_va, nbytes: 64 << 20 }], execution: Some(wire::Execution { @@ -2405,6 +2965,8 @@ extern "C" __global__ void worker_ignore_stop( node_count: 1, edge_count: 0, functions: vec![0], + min_compute_sms: 0, + max_cluster_size: 0, }], reservations: vec![Reservation { address: device_va, @@ -2799,6 +3361,8 @@ extern "C" __global__ void coop_all_sms(int* state, int step) { node_count: 1, edge_count: 0, functions: [0].into_iter().collect(), + min_compute_sms: 0, + max_cluster_size: 0, }, Graph { name: "coop_step".into(), @@ -2807,6 +3371,8 @@ extern "C" __global__ void coop_all_sms(int* state, int step) { node_count: 2, edge_count: 1, functions: [1].into_iter().collect(), + min_compute_sms: 0, + max_cluster_size: 0, }, ], context: Context { @@ -3104,4 +3670,632 @@ extern "C" __global__ void coop_all_sms(int* state, int step) { }); drop(owner); } + + #[test] + #[ignore = "requires an assigned CUDA_VISIBLE_DEVICES GPU with Green Context support and nvcc"] + fn cuda_two_way_codec_compute_partition_isolates_gpu_codec_without_persistent_worker() { + use super::super::{ + NativeResources, + format::{Allocation, Context, Core, Function, Graph, Memory, Module}, + protobuf::wire, + }; + use crate::offload::GpuRankCodec; + use flare_selene::shared::{ + codec::{Encoding, Field, Plan}, + gpu_codec::{DeviceSpan, GpuPlan}, + wire::{PackedUnit, packed_unit::Representation}, + }; + use prost::Message; + use std::collections::HashMap; + use std::sync::atomic::{AtomicBool, AtomicU64}; + + let driver = Driver::load().unwrap(); + let (major, minor, total_sms, max_smem_per_sm, max_smem_optin) = unsafe { + driver.check("cuInit", (driver.init)(0)).unwrap(); + let mut device = 0; + driver + .check("cuDeviceGet", (driver.device)(&mut device, 0)) + .unwrap(); + let attr = |code: i32| { + let mut val = 0; + driver + .check( + "cuDeviceGetAttribute", + (driver.device_attribute)(&mut val, code, device), + ) + .unwrap(); + val + }; + (attr(75), attr(76), attr(16), attr(81), attr(97)) + }; + assert!(driver.green_ctx.is_some()); + assert!(total_sms >= 16, "2-way codec test requires >= 16 SMs, got {total_sms}"); + let one_block_smem = ((max_smem_per_sm as u32) / 2 + 4096).min(max_smem_optin as u32); + + let nvcc = ["/usr/local/cuda-13.2/bin/nvcc", "/opt/cuda/bin/nvcc"] + .into_iter() + .find(|p| std::path::Path::new(p).exists()) + .unwrap_or("nvcc"); + let arch = if (major, minor) == (10, 3) { + format!("-arch=sm_{major}{minor}a") + } else { + format!("-arch=sm_{major}{minor}") + }; + let unique = format!( + "flare-2way-codec-{}-{:?}", + std::process::id(), + std::thread::current().id() + ) + .replace(|c: char| !c.is_ascii_alphanumeric() && c != '-', "_"); + + let codec_cu = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../ignition/preparation/kv_codec_gpu.cu"); + let codec_cubin_path = std::env::temp_dir().join(format!("{unique}-codec.cubin")); + let compiled_codec = std::process::Command::new(nvcc) + .args([ + "-cubin", + "-O3", + &arch, + codec_cu.to_str().unwrap(), + "-o", + codec_cubin_path.to_str().unwrap(), + ]) + .output() + .expect("failed to execute nvcc for kv_codec_gpu.cu"); + assert!( + compiled_codec.status.success(), + "nvcc failed on kv_codec_gpu.cu ({}): {}", + compiled_codec.status, + String::from_utf8_lossy(&compiled_codec.stderr) + ); + let codec_cubin = std::fs::read(&codec_cubin_path).unwrap(); + let _ = std::fs::remove_file(&codec_cubin_path); + + let cu_source = r#" +extern "C" __global__ void coop_all_sms(int* state, int step) { + extern __shared__ unsigned int dyn_smem[]; + if (threadIdx.x == 0) { + const unsigned int n = gridDim.x; + const unsigned int b = blockIdx.x; + dyn_smem[0] = b; + state[4 + b] = step * 1000 + static_cast(dyn_smem[0]); + __threadfence(); + unsigned int prev = 0; + asm volatile("atom.add.acq_rel.gpu.u32 %0, [%1], 1;" : "=r"(prev) : "l"(state) : "memory"); + (void)prev; + while (true) { + unsigned int count = 0; + asm volatile("ld.acquire.gpu.global.u32 %0, [%1];" : "=r"(count) : "l"(state) : "memory"); + if (count >= n) break; + asm volatile("nanosleep.u32 50;"); + } + const int neighbor = state[4 + (n - 1u - b)]; + state[256 + b] = neighbor + 7; + if (b == 0u) state[2] = static_cast(n); + } +} +"#; + let cu_path = std::env::temp_dir().join(format!("{unique}.cu")); + let cubin_path = std::env::temp_dir().join(format!("{unique}.cubin")); + std::fs::write(&cu_path, cu_source).unwrap(); + let compiled = std::process::Command::new(nvcc) + .args([ + "-cubin", + "-O3", + &arch, + cu_path.to_str().unwrap(), + "-o", + cubin_path.to_str().unwrap(), + ]) + .output() + .expect("failed to execute nvcc"); + assert!( + compiled.status.success(), + "nvcc failed ({}): {}", + compiled.status, + String::from_utf8_lossy(&compiled.stderr) + ); + let cubin_bytes = std::fs::read(&cubin_path).unwrap(); + let _ = std::fs::remove_file(&cu_path); + let _ = std::fs::remove_file(&cubin_path); + + let encode_record = |msg_bytes: Vec, out: &mut Vec| { + out.extend_from_slice(&(msg_bytes.len() as u32).to_le_bytes()); + out.extend_from_slice(&msg_bytes); + }; + let ptr_blob = |allocation: &str, offset: u64| wire::Blob { + data: vec![0u8; 8], + relocations: vec![wire::Relocation { + offset: 0, + target: Some(wire::Reference { + allocation: allocation.into(), + offset, + }), + kind: wire::RelocationKind::Pointer as i32, + }], + }; + + let step_val: i32 = 31; + let mut coop_records = Vec::new(); + encode_record( + wire::Node { + operation: Some(wire::node::Operation::Memset(wire::Memset { + destination: Some(wire::Reference { + allocation: "compute_state".into(), + offset: 0, + }), + pitch: 4096, + value: 0, + element_size: 4, + width: 1024, + height: 1, + })), + } + .encode_to_vec(), + &mut coop_records, + ); + encode_record( + wire::Node { + operation: Some(wire::node::Operation::Kernel(wire::Kernel { + function: 0, + grid: vec![total_sms as u32, 1, 1], + block: vec![256, 1, 1], + shared: one_block_smem, + arguments: vec![ + ptr_blob("compute_state", 0), + wire::Blob { + data: step_val.to_le_bytes().to_vec(), + relocations: vec![], + }, + ], + attributes: vec![wire::Attribute { + id: 2, + value: Some(wire::Blob { + data: { + let mut bytes = vec![0u8; 64]; + bytes[0] = 1; + bytes + }, + relocations: vec![], + }), + }], + })), + } + .encode_to_vec(), + &mut coop_records, + ); + encode_record( + wire::Edge { + source: 0, + destination: 1, + data: vec![0; 8], + } + .encode_to_vec(), + &mut coop_records, + ); + + let mut blobs = HashMap::new(); + blobs.insert("compute_test.cubin".to_string(), cubin_bytes); + blobs.insert("graph_coop".to_string(), coop_records); + let files = TestFiles(blobs); + + let build_core = |min_compute_sms: u32, max_cluster_size: u32| Core { + resources: HashMap::new(), + architecture: [major, minor], + allocations: vec![Allocation { + name: "compute_state".into(), + nbytes: 2 << 20, + alignment: 2 << 20, + file: None, + data_spans: vec![], + sources: vec![], + relocations: vec![], + address: None, + memory: Memory::Device, + sizing: None, + }], + modules: vec![Module { + name: "compute_mod".into(), + file: "compute_test.cubin".into(), + globals: vec![], + }], + functions: vec![Function { + id: 0, + module: "compute_mod".into(), + symbol: "coop_all_sms".into(), + parameter_sizes: vec![8, 4], + attributes: vec![], + }], + events: vec![], + graphs: vec![Graph { + name: "coop_step".into(), + flags: 0, + resource: "graph_coop".into(), + node_count: 2, + edge_count: 1, + functions: vec![0], + min_compute_sms, + max_cluster_size, + }], + context: Context { + flags: 0x08, + cache: 0, + limits: vec![[0, 4096]], + }, + reservations: vec![], + execution: None, + external_extents: vec![], + }; + + // 1. Declaring min_compute_sms above what the 2-way split leaves must fail closed. + let oversized = build_core(total_sms as u32, 0); + let phase_err = crate::startup::StartupProgress::silent().phase("Reject oversized", None); + let mut oversized_owner = + unsafe { NativeResources::initialize_with_options(&oversized, 0, true).unwrap() }; + unsafe { + oversized_owner.reserve(&oversized).unwrap(); + oversized_owner.allocate(&oversized, &phase_err).unwrap(); + oversized_owner + .load_payload(&files, &oversized, &phase_err, 1) + .unwrap(); + } + let err = unsafe { + oversized_owner + .prepare_kernels(&files, &oversized, &phase_err, None, true) + .expect_err("min_compute_sms == total_sms must fail 2-way codec split") + } + .to_string(); + assert!( + err.contains("--lossless-kv-compression cpu"), + "unexpected 2-way rejection message: {err}" + ); + drop(oversized_owner); + + // 2. Non-worker core with reserve_codec_partition=true builds a 2-way (codec, compute) split. + let core = build_core(16, 8); + let phase = crate::startup::StartupProgress::silent().phase("Load 2-way codec test", None); + let mut owner = + unsafe { NativeResources::initialize_with_options(&core, 0, true).unwrap() }; + unsafe { + owner.reserve(&core).unwrap(); + owner.allocate(&core, &phase).unwrap(); + owner.load_payload(&files, &core, &phase, 1).unwrap(); + owner + .prepare_kernels(&files, &core, &phase, None, true) + .unwrap(); + owner.prepare_graphs(&files, &core, &phase).unwrap(); + } + let partition = owner.green_partition.as_ref().unwrap(); + assert_eq!(partition.worker_sm_count, 0); + assert!(partition.worker_context.is_null()); + assert!(partition.worker_stream.is_null()); + assert!(partition.codec_sm_count >= 8); + assert!(partition.compute_sm_count >= 16); + assert!(partition.compute_coscheduled_alignment >= 8); + assert!(partition.codec_sm_count + partition.compute_sm_count <= total_sms as u32); + assert_eq!(owner.offload_context(), partition.codec_context); + assert_eq!(owner.execution_context(), partition.compute_context); + assert_ne!(owner.offload_context(), owner.execution_context()); + assert_ne!(owner.offload_context(), owner.context); + assert_eq!( + unsafe { query_context_limit(&driver, partition.compute_context, 0) }, + 4096 + ); + assert_eq!( + unsafe { query_context_limit(&driver, partition.codec_context, 0) }, + 4096 + ); + + let row_bytes = 16 * 65_536 + 65_536; + let page_bytes = 32_768; + let page_plan = GpuPlan::from_plan( + &Plan::new( + page_bytes, + &[Field { + offset: 0, + length: page_bytes, + encoding: Encoding::Fp8Page512, + }], + ) + .unwrap(), + ) + .unwrap(); + let row_plan = GpuPlan::from_plan( + &Plan::new( + row_bytes, + &[ + Field { + offset: 0, + length: 16 * 65_536, + encoding: Encoding::Float32Matrix128, + }, + Field { + offset: 16 * 65_536, + length: 65_536, + encoding: Encoding::Bfloat16, + }, + ], + ) + .unwrap(), + ) + .unwrap(); + let codec_ctx = owner.offload_context() as usize; + let compute_ctx = owner.execution_context() as usize; + let codec_stream = crate::cuda::Stream::open_lowest_priority(codec_ctx, 0).unwrap(); + let codec_event = codec_stream.blocking_event().unwrap(); + let mut gpu_codec = + GpuRankCodec::new(&page_plan, &row_plan, 4, &codec_cubin, &codec_stream, &codec_event) + .unwrap(); + + let mut raw_row = vec![0u8; row_bytes]; + for (i, chunk) in raw_row[..16 * 65_536].chunks_exact_mut(4).enumerate() { + let v = ((i % 128) as f32 * 0.001 + (i / 128) as f32 * 0.0001).to_bits(); + chunk.copy_from_slice(&v.to_le_bytes()); + } + for (i, chunk) in raw_row[16 * 65_536..].chunks_exact_mut(2).enumerate() { + let v = 0x3c00u16.wrapping_add((i % 32) as u16); + chunk.copy_from_slice(&v.to_le_bytes()); + } + let d_src = codec_stream.alloc_device(row_bytes).unwrap(); + let d_dst = codec_stream.alloc_device(row_bytes).unwrap(); + let mut h_io = codec_stream.host_buffer(row_bytes).unwrap(); + h_io.bytes_mut().copy_from_slice(&raw_row); + unsafe { + codec_stream + .copy_htod_async(d_src.ptr(), h_io.address() as _, row_bytes) + .unwrap(); + } + codec_stream.synchronize().unwrap(); + + let coop_idx = owner + .names + .iter() + .position(|name| name == "coop_step") + .unwrap(); + let coop_graph = owner.executables[coop_idx] as usize; + let compute_sms = partition.compute_sm_count; + let compute_addr = owner.allocation("compute_state").unwrap().address; + let compute_stream = crate::cuda::Stream::open(compute_ctx, 0).unwrap(); + let compute_host = compute_stream.host_buffer(4096).unwrap(); + + let stop_flag = AtomicBool::new(false); + let coop_steps = AtomicU64::new(0); + let codec_rounds = AtomicU64::new(0); + std::thread::scope(|s| { + let stop_ref = &stop_flag; + let coop_ref = &coop_steps; + let compute_handle = s.spawn(move || { + while !stop_ref.load(Ordering::Relaxed) { + compute_stream.launch(coop_graph).unwrap(); + compute_stream.synchronize().unwrap(); + coop_ref.fetch_add(1, Ordering::Relaxed); + } + unsafe { + compute_stream + .download(&compute_host, compute_addr, 4096) + .unwrap(); + } + compute_stream.synchronize().unwrap(); + let words: Vec = compute_host + .bytes() + .chunks_exact(4) + .map(|c| i32::from_le_bytes(c.try_into().unwrap())) + .collect(); + assert_eq!(words[2] as u32, compute_sms); + assert_eq!(words[256], step_val * 1000 + (compute_sms as i32 - 1) + 7); + (compute_stream, compute_host) + }); + + let stop_ref = &stop_flag; + let codec_ref = &codec_rounds; + let row_plan_ref = &row_plan; + let raw_row_ref = &raw_row; + let src_ptr = d_src.ptr(); + let dst_ptr = d_dst.ptr(); + let profile = [0x42u8; 32]; + let codec_handle = s.spawn(move || { + while !stop_ref.load(Ordering::Relaxed) { + let src_spans = [DeviceSpan { + device: src_ptr, + offset: 0, + length: row_bytes, + }]; + let (unit, pkt) = gpu_codec + .encode_from_device_with( + row_plan_ref, + PackedUnit { + kind: 1, + logical_index: 0, + original_length: row_bytes as u64, + ..Default::default() + }, + &profile, + &src_spans, + &codec_stream, + &codec_event, + |u, data| (u, data.to_vec()), + ) + .unwrap(); + assert_eq!(unit.representation, Representation::Packet as i32); + assert!(unit.stored_length < row_bytes as u64); + let dst_spans = [DeviceSpan { + device: dst_ptr, + offset: 0, + length: row_bytes, + }]; + gpu_codec + .decode_to_device( + row_plan_ref, + &[pkt.as_slice()], + &dst_spans, + unit.stored_crc, + unit.original_crc, + &codec_stream, + &codec_event, + ) + .unwrap(); + codec_ref.fetch_add(1, Ordering::Relaxed); + } + h_io.bytes_mut().fill(0); + unsafe { + codec_stream + .download(&h_io, dst_ptr as usize, row_bytes) + .unwrap(); + } + codec_stream.synchronize().unwrap(); + assert_eq!(h_io.bytes(), raw_row_ref.as_slice()); + (gpu_codec, codec_stream, codec_event, h_io) + }); + + std::thread::sleep(Duration::from_millis(500)); + stop_flag.store(true, Ordering::Relaxed); + + let (compute_stream, compute_host) = compute_handle.join().unwrap(); + let (gpu_codec, codec_stream, codec_event, h_io) = codec_handle.join().unwrap(); + let steps = coop_steps.load(Ordering::Relaxed); + let rounds = codec_rounds.load(Ordering::Relaxed); + eprintln!( + "2-way Green Context SM120 check: codec={} SMs, compute={} SMs (cosched={}) | \ + concurrent_coop={steps} | gpu_codec_rounds={rounds}", + partition.codec_sm_count, + partition.compute_sm_count, + partition.compute_coscheduled_alignment, + ); + assert!(steps >= 200, "cooperative compute stalled: only {steps} steps"); + assert!(rounds >= 20, "GPU codec stalled: only {rounds} rounds"); + drop((gpu_codec, d_src, d_dst, h_io, codec_event, codec_stream)); + drop((compute_host, compute_stream)); + }); + drop(owner); + } + + #[test] + #[ignore = "requires an NVIDIA GPU with CUDA Green Context driver APIs"] + fn cuda_split_by_count_fallback_partitions_two_way_and_three_way() { + let driver = Driver::load().unwrap(); + unsafe { + driver.check("cuInit", (driver.init)(0)).unwrap(); + let mut device = 0; + driver.check("cuDeviceGet", (driver.device)(&mut device, 0)).unwrap(); + let mut primary = null_mut(); + driver + .check("cuDevicePrimaryCtxRetain", (driver.primary_ctx_retain)(&mut primary, device)) + .unwrap(); + driver + .check("cuCtxSetCurrent", (driver.context_set)(primary)) + .unwrap(); + + // 2-way (codec, compute) through cuDevSmResourceSplitByCount. + let mut two_way = GreenContextPartition::create_with_strategy( + &driver, + device, + PartitionRequest::Codec, + 16, + 8, + false, + ) + .unwrap(); + assert!(two_way.worker_green_ctx.is_null()); + assert!(!two_way.codec_green_ctx.is_null()); + assert!(!two_way.compute_green_ctx.is_null()); + assert!(two_way.codec_sm_count >= 8); + assert!(two_way.compute_sm_count >= 16); + assert!(two_way.compute_coscheduled_alignment >= 8); + // Also verify Stream::open_lowest_priority detects green context (while primary + // context reports false) and copy_batch succeeds from registered host memory into a + // cuMemMap VMM allocation on the green-context stream. + let primary_stream = crate::cuda::Stream::open(primary as usize, 0).unwrap(); + assert!(!primary_stream.is_green_ctx()); + drop(primary_stream); + + let codec_stream = + crate::cuda::Stream::open_lowest_priority(two_way.codec_context as usize, 0) + .unwrap(); + assert!(codec_stream.is_green_ctx()); + let mut props = crate::runtime_core::driver::AllocationProperties { + kind: 1, + handles: 0, + location: crate::runtime_core::driver::Location { kind: 1, device }, + windows: null_mut(), + flags: [0; 8], + }; + let mut granularity = 0usize; + driver + .check( + "cuMemGetAllocationGranularity", + (driver.granularity)(&mut granularity, &props, 0), + ) + .unwrap(); + let vmm_size = granularity.max(2 << 20); + let mut vmm_va = 0u64; + let mut vmm_handle = 0u64; + driver + .check( + "cuMemAddressReserve", + (driver.reserve)(&mut vmm_va, vmm_size, granularity, 0, 0), + ) + .unwrap(); + driver + .check( + "cuMemCreate", + (driver.physical_create)(&mut vmm_handle, vmm_size, &mut props, 0), + ) + .unwrap(); + driver + .check("cuMemMap", (driver.map)(vmm_va, vmm_size, 0, vmm_handle, 0)) + .unwrap(); + let access = crate::runtime_core::driver::Access { + location: crate::runtime_core::driver::Location { kind: 1, device }, + flags: 3, + }; + driver + .check( + "cuMemSetAccess", + (driver.access)(vmm_va, vmm_size, &access, 1), + ) + .unwrap(); + let host_ptr = crate::os::map_host(4096).unwrap(); + std::slice::from_raw_parts_mut(host_ptr as *mut u8, 4096).fill(0x5a); + let reg = crate::cuda::register_host(primary as usize, host_ptr, 4096).unwrap(); + codec_stream + .copy_batch(&[vmm_va], &[reg.device_address()], &[4096]) + .unwrap(); + codec_stream.synchronize().unwrap(); + let verify = codec_stream.host_buffer(4096).unwrap(); + codec_stream + .download(&verify, vmm_va as usize, 4096) + .unwrap(); + codec_stream.synchronize().unwrap(); + assert_eq!(verify.bytes(), &[0x5au8; 4096]); + drop((verify, reg, codec_stream)); + crate::os::unmap_host(host_ptr, 4096); + let _ = (driver.unmap)(vmm_va, vmm_size); + let _ = (driver.physical_release)(vmm_handle); + let _ = (driver.release_address)(vmm_va, vmm_size); + two_way.destroy_streams(&driver); + two_way.destroy_green_contexts(&driver); + + // 3-way (worker, codec, compute) through cuDevSmResourceSplitByCount. + let mut three_way = GreenContextPartition::create_with_strategy( + &driver, + device, + PartitionRequest::WorkerAndCodec(NonZeroU32::new(8).unwrap()), + 16, + 8, + false, + ) + .unwrap(); + assert!(!three_way.worker_green_ctx.is_null()); + assert!(!three_way.codec_green_ctx.is_null()); + assert!(!three_way.compute_green_ctx.is_null()); + assert!(three_way.worker_sm_count >= 8); + assert!(three_way.codec_sm_count >= 8); + assert!(three_way.compute_sm_count >= 16); + assert!(three_way.compute_coscheduled_alignment >= 8); + three_way.destroy_streams(&driver); + three_way.destroy_green_contexts(&driver); + + let _ = (driver.primary_ctx_release)(device); + } + } } diff --git a/helios/src/runtime_core/protection.rs b/helios/src/runtime_core/protection.rs index ce9bbc6e1..5b8a3100d 100644 --- a/helios/src/runtime_core/protection.rs +++ b/helios/src/runtime_core/protection.rs @@ -3001,6 +3001,8 @@ mod payload_core_tests { node_count: 1, edge_count: 0, functions: vec![0], + min_compute_sms: 0, + max_cluster_size: 0, }], execution: Some(crate::runtime_core::wire::Execution { abi_version: 2, @@ -3086,6 +3088,8 @@ mod payload_core_tests { node_count: 1, edge_count: 0, functions: vec![0], + min_compute_sms: 0, + max_cluster_size: 0, }], execution: Some(crate::runtime_core::wire::Execution { abi_version: 2, @@ -4662,6 +4666,8 @@ mod payload_core_tests { node_count: 1, edge_count: 0, functions: vec![0], + min_compute_sms: 0, + max_cluster_size: 0, }], execution: Some(crate::runtime_core::wire::Execution { abi_version: 2, diff --git a/helios/src/runtime_core/protobuf.rs b/helios/src/runtime_core/protobuf.rs index ed255a80a..24d941d62 100644 --- a/helios/src/runtime_core/protobuf.rs +++ b/helios/src/runtime_core/protobuf.rs @@ -583,6 +583,8 @@ pub(super) fn decode(mut value: wire::BundleIndex) -> Result { node_count: size(v.node_count)?, edge_count: size(v.edge_count)?, functions: convert(v.functions, size)?, + min_compute_sms: v.min_compute_sms, + max_cluster_size: v.max_cluster_size, }) })?, execution: value.execution, @@ -1505,6 +1507,8 @@ pub(super) fn payload_rank( node_count: size(graph.node_count)?, edge_count: size(graph.edge_count)?, functions: convert(graph.functions.clone(), size)?, + min_compute_sms: graph.min_compute_sms, + max_cluster_size: graph.max_cluster_size, }) }) .collect::>>()?; @@ -1660,6 +1664,8 @@ mod payload_tests { node_count: 1, edge_count: 0, functions: vec![0], + min_compute_sms: 0, + max_cluster_size: 0, }], events: vec!["ready".into()], peers: vec![], @@ -1898,6 +1904,8 @@ mod payload_tests { node_count: 1, edge_count: 0, functions: vec![], + min_compute_sms: 0, + max_cluster_size: 0, }, Graph { name: "tune".into(), @@ -1906,6 +1914,8 @@ mod payload_tests { node_count: 1, edge_count: 0, functions: vec![], + min_compute_sms: 0, + max_cluster_size: 0, }, Graph { name: "worker_launch".into(), @@ -1914,6 +1924,8 @@ mod payload_tests { node_count: 1, edge_count: 0, functions: vec![], + min_compute_sms: 0, + max_cluster_size: 0, }, Graph { name: "worker_launch_2".into(), @@ -1922,6 +1934,8 @@ mod payload_tests { node_count: 1, edge_count: 0, functions: vec![], + min_compute_sms: 0, + max_cluster_size: 0, }, ], reservations: vec![], @@ -1995,4 +2009,67 @@ mod payload_tests { ); } } + + #[test] + fn legacy_graph_wire_bytes_omitting_sm_bounds_decode_to_zero() { + use prost::Message; + + // Legacy GraphIndex / payload::Graph wire bytes carrying only tags 1..=6 (omitting + // additive tags 7 `min_compute_sms` and 8 `max_cluster_size`). + let legacy_index = wire::GraphIndex { + name: "decode_b1".into(), + flags: 8, + resource: "graphs/decode_b1.bin".into(), + node_count: 3, + edge_count: 2, + functions: vec![0], + min_compute_sms: 0, + max_cluster_size: 0, + }; + let encoded_index = legacy_index.encode_to_vec(); + let decoded_index = wire::GraphIndex::decode(encoded_index.as_slice()).unwrap(); + assert_eq!(decoded_index.min_compute_sms, 0); + assert_eq!(decoded_index.max_cluster_size, 0); + + let legacy_payload_graph = payload::Graph { + name: "decode_b1".into(), + flags: 8, + resource: 0, + node_count: 3, + edge_count: 2, + functions: vec![0], + min_compute_sms: 0, + max_cluster_size: 0, + }; + let encoded_payload = legacy_payload_graph.encode_to_vec(); + let decoded_payload = payload::Graph::decode(encoded_payload.as_slice()).unwrap(); + assert_eq!(decoded_payload.min_compute_sms, 0); + assert_eq!(decoded_payload.max_cluster_size, 0); + + let placements = Placements::from([ + (vec![1u8; 32], placement("weights-a", 100, 4096)), + (vec![2u8; 32], placement("weights-b", 200, 8192)), + (vec![3u8; 32], placement("graphs", 4096, 64)), + (vec![4u8; 32], placement("globals", 0, 32)), + ]); + let mut body = rank(); + body.graphs = vec![decoded_payload]; + let core = payload_rank(&body, [12, 0], &placements).unwrap(); + assert_eq!(core.graphs.len(), 1); + assert_eq!(core.graphs[0].min_compute_sms, 0); + assert_eq!(core.graphs[0].max_cluster_size, 0); + + // Non-zero SM bounds round-trip through payload::Graph into Core. + let bounded = payload::Graph { + min_compute_sms: 64, + max_cluster_size: 16, + ..legacy_payload_graph + }; + let encoded_bounded = bounded.encode_to_vec(); + let decoded_bounded = payload::Graph::decode(encoded_bounded.as_slice()).unwrap(); + body.graphs = vec![decoded_bounded]; + let core_bounded = payload_rank(&body, [12, 0], &placements).unwrap(); + assert_eq!(core_bounded.graphs[0].min_compute_sms, 64); + assert_eq!(core_bounded.graphs[0].max_cluster_size, 16); + } } diff --git a/helios/src/runtime_core/selection.rs b/helios/src/runtime_core/selection.rs index cc9bf23f1..264c1be72 100644 --- a/helios/src/runtime_core/selection.rs +++ b/helios/src/runtime_core/selection.rs @@ -569,6 +569,8 @@ mod tests { node_count: 1, edge_count: 0, functions: vec![function], + min_compute_sms: 0, + max_cluster_size: 0, }) .collect(); let functions = execution @@ -626,7 +628,7 @@ mod tests { for name in ["tune", "unused_tune"] { core.graphs.push(Graph { name: name.into(), flags: 0, resource: name.into(), node_count: 1, edge_count: 0, - functions: vec![function], + functions: vec![function], min_compute_sms: 0, max_cluster_size: 0, }); } let execution = core.execution.as_mut().unwrap(); @@ -690,6 +692,8 @@ mod tests { node_count: 1, edge_count: 0, functions: vec![function], + min_compute_sms: 0, + max_cluster_size: 0, }); core.execution.as_mut().unwrap().persistent_workers = vec![wire::PersistentWorker { worker_sm_count: 8, @@ -748,6 +752,8 @@ mod tests { node_count: 1, edge_count: 0, functions: vec![function], + min_compute_sms: 0, + max_cluster_size: 0, }); two_workers[0] .execution @@ -1226,6 +1232,8 @@ mod tests { edge_count: 0, flags: 0, functions: vec![0], + min_compute_sms: 0, + max_cluster_size: 0, }); } LoadOptions { @@ -1551,6 +1559,8 @@ mod tests { edge_count: 0, flags: 0, functions: vec![0], + min_compute_sms: 0, + max_cluster_size: 0, }); } LoadOptions { @@ -1601,6 +1611,8 @@ mod tests { edge_count: 0, flags: 0, functions: vec![0], + min_compute_sms: 0, + max_cluster_size: 0, }); } } @@ -1694,6 +1706,7 @@ mod tests { core.graphs = core.execution.as_ref().unwrap().graphs.iter().map(|graph| Graph { name: graph.name.clone(), flags: 0, resource: graph.name.clone(), node_count: 1, edge_count: 0, functions: vec![0], + min_compute_sms: 0, max_cluster_size: 0, }).collect(); } diff --git a/ignition/preparation/capture.py b/ignition/preparation/capture.py index f71133b12..f03587bdd 100644 --- a/ignition/preparation/capture.py +++ b/ignition/preparation/capture.py @@ -107,6 +107,12 @@ def _seed_auxiliary_workspaces(session, device, *, warmup_storage): aux.synchronize() +def _track_capture_min_compute_sms(): + from b12x._lib.utils.device import track_capture_min_compute_sms + + return track_capture_min_compute_sms() + + def _capture_order(names, compiled, coordinator): sizes = {name: forward.capture_allocation_sizes for name, forward in compiled.items()} return allocation_order(names, sizes, coordinator) @@ -259,8 +265,10 @@ def memory_detail(): with torch.cuda.stream(warm): before_run(name) stream.wait_stream(warm) - with communication, session.capture(), torch.cuda.graph(graph, pool=pool, stream=stream): - function() + with _track_capture_min_compute_sms() as sm_tracker: + with communication, session.capture(), torch.cuda.graph(graph, pool=pool, stream=stream): + function() + min_compute_sms = int(sm_tracker.get("min_compute_sms", 0)) if exporting: graph = record_export_graph(graph, warmup_storage, owners=(function,)) if seal_low: @@ -269,6 +277,8 @@ def memory_detail(): if progress is not None: progress(f"instantiating {name}: {memory_detail()}") instantiate_graph(graph) + if min_compute_sms > 0: + graph._flare_min_compute_sms = min_compute_sms except Exception as error: error.add_note(f"Graph {name!r} on {device}: {memory_detail()}") raise diff --git a/ignition/preparation/runtime_core.py b/ignition/preparation/runtime_core.py index a09e4b71a..fad9701a1 100644 --- a/ignition/preparation/runtime_core.py +++ b/ignition/preparation/runtime_core.py @@ -295,12 +295,17 @@ def instantiate_graph(graph): def _graphs(graphs, *, recorder=None): result = [] for name, graph in graphs.items(): + raw_min_sms = getattr(graph, "_flare_min_compute_sms", None) + min_compute_sms = 0 if raw_min_sms is None else raw_min_sms + if type(min_compute_sms) is not int or min_compute_sms < 0: + raise ValueError(f"graph {name!r} min_compute_sms must be a nonnegative integer") + extra = {"min_compute_sms": min_compute_sms} if min_compute_sms > 0 else {} if isinstance(graph, RecordedExportGraph): if graph.recorder is not recorder: raise ValueError(f"graph {name!r} metadata belongs to another native module recorder") if not graph.recorded: raise ValueError(f"graph {name!r} export metadata has been released") - result.append(dict(name=name, recorded=graph.recorded)) + result.append(dict(name=name, recorded=graph.recorded, **extra)) continue flags = getattr(graph, "_flare_instantiation_flags", None) if flags is not None: @@ -309,13 +314,13 @@ def _graphs(graphs, *, recorder=None): template = int(graph.raw_cuda_graph()) if not template: raise ValueError("graph instantiation flags require a retained CUDA graph template") - result.append(dict(name=name, graph=template, instantiate_flags=flags)) + result.append(dict(name=name, graph=template, instantiate_flags=flags, **extra)) continue executable = int(graph.raw_cuda_graph_exec()) metadata = getattr(graph, "_flare_graph_metadata", None) template = (0 if metadata is not None and metadata.executable and metadata.executable == executable else int(graph.raw_cuda_graph())) - result.append(dict(name=name, graph=template, executable=executable)) + result.append(dict(name=name, graph=template, executable=executable, **extra)) return result diff --git a/ignition/preparation/runtime_core_pb2.py b/ignition/preparation/runtime_core_pb2.py index 43a69ec0a..6ce4aee26 100644 --- a/ignition/preparation/runtime_core_pb2.py +++ b/ignition/preparation/runtime_core_pb2.py @@ -2,7 +2,7 @@ # Generated by the protocol buffer compiler. DO NOT EDIT! # NO CHECKED-IN PROTOBUF GENCODE # source: runtime_core.proto -# Protobuf Python Version: 7.35.1 +# Protobuf Python Version: 7.36.1 """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool @@ -12,7 +12,7 @@ _runtime_version.ValidateProtobufRuntimeVersion( _runtime_version.Domain.PUBLIC, 7, - 35, + 36, 1, '', 'runtime_core.proto' @@ -24,7 +24,7 @@ -DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x12runtime_core.proto\x12\rflare.runtime\"\x99\x01\n\x0eProtectedIndex\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x0f\n\x07\x63ore_id\x18\x02 \x01(\x0c\x12\x0e\n\x06signer\x18\x03 \x01(\x0c\x12*\n\x06groups\x18\x04 \x03(\x0b\x32\x1a.flare.runtime.SignedGroup\x12)\n\x05ranks\x18\x05 \x03(\x0b\x32\x1a.flare.runtime.SignedGroup\"<\n\x0bSignedGroup\x12\x0c\n\x04kind\x18\x01 \x01(\r\x12\x0c\n\x04\x62ody\x18\x02 \x01(\x0c\x12\x11\n\tsignature\x18\x03 \x01(\x0c\"\xcc\x01\n\x11PublisherMetadata\x12(\n\x05index\x18\x01 \x01(\x0b\x32\x19.flare.runtime.ModelIndex\x12\x11\n\tnamespace\x18\x02 \x01(\t\x12\x17\n\x0fofficial_source\x18\x03 \x01(\t\x12\x14\n\x0cgroup_hashes\x18\x04 \x03(\x0c\x12\x13\n\x0b\x64\x65velopment\x18\x05 \x01(\x08\x12\r\n\x05ranks\x18\x06 \x01(\r\x12\'\n\x07license\x18\x07 \x01(\x0b\x32\x16.flare.runtime.License\"%\n\x07License\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04link\x18\x02 \x01(\t\"F\n\x0fResourceCatalog\x12\x33\n\tresources\x18\x01 \x03(\x0b\x32 .flare.runtime.ProtectedResource\"^\n\x11ProtectedResource\x12\x0e\n\x06offset\x18\x01 \x01(\x04\x12\x14\n\x0cstored_bytes\x18\x02 \x01(\x04\x12\x13\n\x0bplain_bytes\x18\x03 \x01(\x04\x12\x0e\n\x06sha256\x18\x04 \x03(\x0c\"`\n\nStoredData\x12\x0e\n\x06nbytes\x18\x01 \x01(\x04\x12\x0e\n\x06sha256\x18\x02 \x01(\x0c\x12\x0e\n\x06offset\x18\x03 \x01(\x04\x12\"\n\x05parts\x18\x04 \x03(\x0b\x32\x13.flare.runtime.Span\"\xd9\x01\n\x0eRankProtection\x12\x0c\n\x04rank\x18\x01 \x01(\r\x12*\n\x06\x62undle\x18\x02 \x01(\x0b\x32\x1a.flare.runtime.BundleIndex\x12\x33\n\x0b\x65xecutables\x18\x03 \x01(\x0b\x32\x1e.flare.runtime.ResourceCatalog\x12/\n\x07support\x18\x04 \x01(\x0b\x32\x1e.flare.runtime.ResourceCatalog\x12\'\n\x04\x64\x61ta\x18\x05 \x01(\x0b\x32\x19.flare.runtime.StoredData\"\x8c\x04\n\nModelIndex\x12\x0f\n\x07version\x18\x01 \x01(\r\x12)\n\x05ranks\x18\x02 \x03(\x0b\x32\x1a.flare.runtime.BundleIndex\x12.\n\x0bpeer_memory\x18\x03 \x03(\x0b\x32\x19.flare.runtime.PeerMemory\x12$\n\x06\x61ssets\x18\x05 \x03(\x0b\x32\x14.flare.runtime.Asset\x12%\n\x06\x65ngram\x18\x06 \x01(\x0b\x32\x15.flare.runtime.Engram\x12\x43\n\x11sampling_defaults\x18\x07 \x01(\x0b\x32(.flare.runtime.DefaultSamplingParameters\x12\x31\n\x08\x66rontend\x18\x08 \x01(\x0b\x32\x1f.flare.runtime.FrontendSettings\x12\'\n\x07\x63luster\x18\t \x01(\x0b\x32\x16.flare.runtime.Cluster\x12\x30\n\x08\x63ontract\x18\n \x01(\x0b\x32\x1e.flare.runtime.ServingContract\x12\x33\n\x07rebuild\x18\x0b \x01(\x0b\x32\x1e.flare.runtime.RebuildManifestB\x02\x18\x01\x12\x37\n\x0bpreparation\x18\x0c \x01(\x0b\x32\".flare.runtime.PreparationManifestJ\x04\x08\x04\x10\x05\"\xf9\x01\n\x13PreparationManifest\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x0e\n\x06recipe\x18\x02 \x01(\t\x12\x17\n\x0fsource_identity\x18\x03 \x01(\t\x12\x1d\n\x15\x63heckpoint_repository\x18\x04 \x01(\t\x12\x1b\n\x13\x63heckpoint_revision\x18\x05 \x01(\t\x12\x18\n\x10local_checkpoint\x18\x06 \x01(\x08\x12\x19\n\x11reproduction_args\x18\x07 \x03(\t\x12\x37\n\nparameters\x18\x08 \x03(\x0b\x32#.flare.runtime.PreparationParameter\"\x8c\x01\n\x14PreparationParameter\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x37\n\x05scope\x18\x02 \x01(\x0e\x32(.flare.runtime.PreparationParameterScope\x12.\n\x05value\x18\x03 \x01(\x0b\x32\x1f.flare.runtime.PreparationValue\"\xc6\x01\n\x10PreparationValue\x12\x14\n\nbool_value\x18\x01 \x01(\x08H\x00\x12\x13\n\tint_value\x18\x02 \x01(\x03H\x00\x12\x14\n\nuint_value\x18\x03 \x01(\x04H\x00\x12\x15\n\x0b\x66loat_value\x18\x04 \x01(\x01H\x00\x12\x16\n\x0cstring_value\x18\x05 \x01(\tH\x00\x12\x39\n\nlist_value\x18\x06 \x01(\x0b\x32#.flare.runtime.PreparationValueListH\x00\x42\x07\n\x05value\"G\n\x14PreparationValueList\x12/\n\x06values\x18\x01 \x03(\x0b\x32\x1f.flare.runtime.PreparationValue\"\xdb\x07\n\x0fRebuildManifest\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x0e\n\x06recipe\x18\x02 \x01(\t\x12\x17\n\x0fsource_identity\x18\x03 \x01(\t\x12\x1d\n\x15\x63heckpoint_repository\x18\x04 \x01(\t\x12\x1b\n\x13\x63heckpoint_revision\x18\x05 \x01(\t\x12\x17\n\x0ftensor_parallel\x18\x06 \x01(\r\x12\x17\n\x0fmax_concurrency\x18\x07 \x01(\x04\x12\x15\n\rprefill_chunk\x18\x08 \x01(\x04\x12\x19\n\x11image_concurrency\x18\t \x01(\x04\x12\x18\n\x10\x63ontext_parallel\x18\n \x01(\x08\x12\x16\n\x0estream_overlap\x18\x0b \x01(\x08\x12\x15\n\rmixed_prefill\x18\x0c \x01(\x08\x12%\n\x18\x65xpert_scale_compression\x18\r \x01(\tH\x00\x88\x01\x01\x12\x18\n\x10mla_compute_mode\x18\x0e \x01(\t\x12\x11\n\troce_ring\x18\x0f \x01(\x08\x12\x14\n\x0conline_mxfp8\x18\x10 \x01(\x08\x12\x1b\n\x13language_model_only\x18\x11 \x01(\x08\x12\x36\n\x0bspeculation\x18\x12 \x01(\x0b\x32!.flare.runtime.RebuildSpeculation\x12\x19\n\x11\x63ompiled_forwards\x18\x13 \x01(\x08\x12\x15\n\rreserve_bytes\x18\x14 \x01(\x04\x12\x18\n\x10local_checkpoint\x18\x15 \x01(\x08\x12\x12\n\nroce_chain\x18\x16 \x01(\x08\x12\x1e\n\x16shard_hyperconnections\x18\x18 \x01(\x08\x12\x1c\n\x14\x66orce_moe_decode_a16\x18\x1b \x01(\x08\x12\x19\n\x11row_shard_prefill\x18\x1c \x01(\x08\x12\x1a\n\x12online_mxfp8_scope\x18\x1e \x01(\t\x12\x1d\n\x15\x63ontext_parallel_size\x18\x1f \x01(\r\x12\x17\n\x0fprompt_logprobs\x18 \x01(\x08\x12\x17\n\x0f\x61utotune_effort\x18! \x01(\t\x12 \n\x18native_dense_activations\x18\" \x01(\x08\x12\x17\n\x0flock_gpu_clocks\x18# \x01(\x08\x12\x19\n\x11reproduction_args\x18$ \x03(\t:\x02\x18\x01\x42\x1b\n\x19_expert_scale_compressionJ\x04\x08\x17\x10\x18J\x04\x08\x19\x10\x1aJ\x04\x08\x1a\x10\x1bR\x0cjoint_tuningR\x11\x63ollective_tuningR\x16\x63ollective_ladder_json\"\x82\x04\n\x12RebuildSpeculation\x12\x14\n\x0c\x64raft_tokens\x18\x01 \x01(\r\x12\x10\n\x08\x61\x64\x61ptive\x18\x02 \x01(\x08\x12\x17\n\x0fproposal_source\x18\x03 \x01(\t\x12\x16\n\x0ehistory_drafts\x18\x04 \x01(\x08\x12\x16\n\x0etoken_capacity\x18\x05 \x01(\x04\x12\x1b\n\x13packed_verification\x18\x06 \x01(\x08\x12\x1e\n\x16\x64raft_prefix_selection\x18\x07 \x01(\t\x12$\n\x17\x64raft_head_quantization\x18\x08 \x01(\tH\x00\x88\x01\x01\x12%\n\x18markov_head_quantization\x18\t \x01(\tH\x01\x88\x01\x01\x12\x19\n\x0cgraph_budget\x18\n \x01(\x04H\x02\x88\x01\x01\x12$\n\x1cvocabulary_parallel_sampling\x18\x0b \x01(\x08\x12\x0e\n\x06method\x18\x0c \x01(\t\x12\x10\n\x08mtp_only\x18\r \x01(\x08\x12$\n\x17\x64raft_body_quantization\x18\x0e \x01(\tH\x03\x88\x01\x01:\x02\x18\x01\x42\x1a\n\x18_draft_head_quantizationB\x1b\n\x19_markov_head_quantizationB\x0f\n\r_graph_budgetB\x1a\n\x18_draft_body_quantization\"e\n\x0eRebuildWeights\x12\x0f\n\x07version\x18\x01 \x01(\r\x12-\n\x07tensors\x18\x02 \x03(\x0b\x32\x1c.flare.runtime.RebuildTensor\x12\x13\n\x0bunavailable\x18\x03 \x03(\t\"\xa2\x01\n\rRebuildTensor\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05\x64type\x18\x02 \x01(\t\x12\x15\n\relement_bytes\x18\x03 \x01(\r\x12\r\n\x05shape\x18\x04 \x03(\x04\x12\x0e\n\x06stride\x18\x05 \x03(\x04\x12\x13\n\x0blayout_type\x18\x06 \x01(\t\x12)\n\x07storage\x18\x07 \x01(\x0b\x32\x18.flare.runtime.Reference\"\xcb\x06\n\x0fServingContract\x12\x10\n\x08model_id\x18\x01 \x01(\t\x12\x10\n\x08identity\x18\x02 \x01(\t\x12\x34\n\x0emodel_contract\x18\x03 \x01(\x0b\x32\x1c.flare.runtime.ModelContract\x12\x1b\n\x13max_sequence_tokens\x18\x04 \x01(\x04\x12\x1a\n\x12prefill_chunk_size\x18\x05 \x01(\x04\x12\r\n\x05pages\x18\x06 \x01(\x04\x12\x12\n\nstate_rows\x18\x07 \x01(\x04\x12\x11\n\tsnapshots\x18\x08 \x01(\x04\x12\x13\n\x0bpage_tokens\x18\t \x01(\x04\x12\x1a\n\x12speculative_widths\x18\x0b \x03(\x04\x12$\n\x17speculative_fixed_width\x18\x0c \x01(\x04H\x00\x88\x01\x01\x12\x16\n\x0ehistory_drafts\x18\r \x01(\x08\x12#\n\x1bspeculative_proposal_source\x18\x0e \x01(\t\x12\x1b\n\x0emax_new_tokens\x18\x0f \x01(\x04H\x01\x88\x01\x01\x12\x17\n\nmax_active\x18\x10 \x01(\x04H\x02\x88\x01\x01\x12\x14\n\x0cserved_names\x18\x11 \x03(\t\x12\x1a\n\rreserve_bytes\x18\x12 \x01(\x04H\x03\x88\x01\x01\x12\x1b\n\x0equeue_capacity\x18\x13 \x01(\x04H\x04\x88\x01\x01\x12\x1d\n\x10\x66rontend_workers\x18\x14 \x01(\x04H\x05\x88\x01\x01\x12\x1b\n\x0emax_body_bytes\x18\x15 \x01(\x04H\x06\x88\x01\x01\x12\x14\n\x0c\x63ontext_hint\x18\x16 \x01(\t\x12\x15\n\rcapacity_hint\x18\x17 \x01(\t\x12\"\n\x1aspeculative_token_capacity\x18\x18 \x01(\x04\x12 \n\x13\x64\x65\x63ode_weight_bytes\x18\x19 \x01(\x04H\x07\x88\x01\x01\x42\x1a\n\x18_speculative_fixed_widthB\x11\n\x0f_max_new_tokensB\r\n\x0b_max_activeB\x10\n\x0e_reserve_bytesB\x11\n\x0f_queue_capacityB\x13\n\x11_frontend_workersB\x11\n\x0f_max_body_bytesB\x16\n\x14_decode_weight_bytesJ\x04\x08\n\x10\x0b\"\xc2\x02\n\rModelContract\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x12\n\nvocabulary\x18\x02 \x01(\x04\x12\x18\n\x10input_vocabulary\x18\x03 \x01(\x04\x12-\n\x06vision\x18\x04 \x01(\x0b\x32\x1d.flare.runtime.VisionCapacity\x12+\n\x05\x63\x61\x63he\x18\x05 \x01(\x0b\x32\x1c.flare.runtime.CacheContract\x12,\n\x06graphs\x18\x06 \x03(\x0b\x32\x1c.flare.runtime.GraphContract\x12\x31\n\x08\x66rontend\x18\x07 \x01(\x0b\x32\x1f.flare.runtime.FrontendContract\x12\x35\n\x0f\x63ore_parameters\x18\x08 \x03(\x0b\x32\x1c.flare.runtime.CoreParameter\"}\n\rCoreParameter\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1a\n\rdefault_value\x18\x02 \x01(\x02H\x00\x88\x01\x01\x12\x30\n\x05range\x18\x03 \x01(\x0b\x32!.flare.runtime.CoreParameterRangeB\x10\n\x0e_default_value\"H\n\x12\x43oreParameterRange\x12\x10\n\x03min\x18\x01 \x01(\x02H\x00\x88\x01\x01\x12\x10\n\x03max\x18\x02 \x01(\x02H\x01\x88\x01\x01\x42\x06\n\x04_minB\x06\n\x04_max\"\x90\x01\n\x0eVisionCapacity\x12\x15\n\rfeature_slots\x18\x05 \x01(\x04\x12\x1c\n\x14\x66\x65\x61tures_per_request\x18\x01 \x01(\x04\x12\x12\n\nmax_images\x18\x02 \x01(\x04\x12\x1b\n\x13patches_per_feature\x18\x03 \x01(\x04\x12\x18\n\x10patch_capacities\x18\x04 \x03(\x04\"\xb8\x01\n\rCacheContract\x12\x13\n\x0bpage_tokens\x18\x01 \x01(\x04\x12-\n\x07regions\x18\x02 \x03(\x0b\x32\x1c.flare.runtime.HistoryRegion\x12\x31\n\x0bpage_tables\x18\x03 \x03(\x0b\x32\x1c.flare.runtime.PageTableView\x12\x30\n\x0c\x63odec_layout\x18\x04 \x01(\x0b\x32\x1a.flare.runtime.CodecLayout\"r\n\x0b\x43odecLayout\x12\x10\n\x08revision\x18\x01 \x01(\r\x12)\n\x06\x66ields\x18\x02 \x03(\x0b\x32\x19.flare.runtime.CodecField\x12\x17\n\ngpu_module\x18\x03 \x01(\tH\x00\x88\x01\x01\x42\r\n\x0b_gpu_module\"N\n\nCodecField\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x0e\n\x06offset\x18\x02 \x01(\x04\x12\x0e\n\x06length\x18\x03 \x01(\x04\x12\x10\n\x08\x65ncoding\x18\x04 \x01(\r\"\x96\x01\n\rHistoryRegion\x12(\n\x04kind\x18\x01 \x01(\x0e\x32\x1a.flare.runtime.HistoryKind\x12)\n\x07storage\x18\x02 \x01(\x0b\x32\x18.flare.runtime.StateView\x12\x19\n\x11tokens_per_record\x18\x03 \x01(\x04\x12\x15\n\rwindow_tokens\x18\x04 \x01(\x04\"4\n\rPageTableView\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x13\n\x0bpage_offset\x18\x02 \x01(\x04\"\xc4\x01\n\x0cValueBinding\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12*\n\x06source\x18\x02 \x01(\x0e\x32\x1a.flare.runtime.ValueSource\x12.\n\x08indexing\x18\x03 \x01(\x0e\x32\x1c.flare.runtime.InputIndexing\x12\x14\n\x0cvalue_offset\x18\x04 \x01(\x12\x12\x0f\n\x07padding\x18\x05 \x01(\x12\x12\x0e\n\x06tensor\x18\x06 \x01(\t\x12\x11\n\tparameter\x18\x07 \x01(\t\"K\n\tStateView\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x0e\n\x06offset\x18\x02 \x01(\x04\x12\x0e\n\x06stride\x18\x03 \x01(\x04\x12\x0e\n\x06nbytes\x18\x04 \x01(\x04\"e\n\x0bStateAccess\x12&\n\x04view\x18\x01 \x01(\x0b\x32\x18.flare.runtime.StateView\x12.\n\x06\x61\x63\x63\x65ss\x18\x02 \x01(\x0e\x32\x1e.flare.runtime.StateAccessKind\"O\n\x10\x43ompletionCursor\x12\'\n\x05state\x18\x01 \x01(\x0b\x32\x18.flare.runtime.StateView\x12\x12\n\nlag_tokens\x18\x02 \x01(\x04\"4\n\x0cTunedBinding\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x14\n\x0ctuning_graph\x18\x02 \x01(\t\"\xfa\x02\n\rGraphContract\x12\r\n\x05graph\x18\x01 \x01(\t\x12+\n\x06inputs\x18\x02 \x03(\x0b\x32\x1b.flare.runtime.ValueBinding\x12)\n\x05state\x18\x03 \x03(\x0b\x32\x1a.flare.runtime.StateAccess\x12\x1e\n\x16state_rows_per_request\x18\x04 \x01(\x04\x12\x35\n\x0c\x64raft_cursor\x18\x05 \x01(\x0b\x32\x1f.flare.runtime.CompletionCursor\x12\x18\n\x10\x65mbedding_tables\x18\x06 \x03(\r\x12/\n\rpending_token\x18\x07 \x01(\x0b\x32\x18.flare.runtime.StateView\x12+\n\x04kind\x18\x08 \x01(\x0e\x32\x1d.flare.runtime.GraphOperation\x12\x33\n\x0etuned_bindings\x18\t \x03(\x0b\x32\x1b.flare.runtime.TunedBinding\"\x88\x01\n\nToolParser\x12+\n\x04kind\x18\x01 \x01(\x0e\x32\x1d.flare.runtime.ToolParserKind\x12\x19\n\x11wrapping_newlines\x18\x02 \x01(\r\x12\x15\n\rtag_separator\x18\x03 \x01(\t\x12\x0c\n\x04open\x18\x04 \x01(\t\x12\r\n\x05\x63lose\x18\x05 \x01(\t\"\x95\x01\n\x0fReasoningParser\x12\x30\n\x04kind\x18\x01 \x01(\x0e\x32\".flare.runtime.ReasoningParserKind\x12\x0c\n\x04open\x18\x02 \x01(\t\x12\r\n\x05\x63lose\x18\x03 \x01(\t\x12\x19\n\x11wrapping_newlines\x18\x04 \x01(\r\x12\x18\n\x10terminal_markers\x18\x05 \x03(\t\"\xca\x01\n\x0ePrefixBoundary\x12\r\n\x05roles\x18\x01 \x03(\t\x12\x18\n\x0b\x61ppend_role\x18\x02 \x01(\tH\x00\x88\x01\x01\x12\x1e\n\x16\x63ontinue_final_message\x18\x03 \x01(\x08\x12\x18\n\x10minimum_messages\x18\x04 \x01(\x04\x12\x16\n\x0erequired_start\x18\x05 \x01(\t\x12\x14\n\x0crequired_end\x18\x06 \x01(\t\x12\x17\n\x0frequired_marker\x18\x07 \x01(\tB\x0e\n\x0c_append_role\"y\n\tImageSpan\x12\x13\n\x0bstart_token\x18\x01 \x01(\r\x12\x11\n\tend_token\x18\x02 \x01(\r\x12\x12\n\nmax_tokens\x18\x03 \x01(\x04\x12\x17\n\x0finterior_tokens\x18\x04 \x03(\r\x12\x17\n\x0funscoped_tokens\x18\x05 \x03(\r\"Q\n\x10ImageTokenLayout\x12\x15\n\rfeature_token\x18\x01 \x01(\r\x12&\n\x04span\x18\x02 \x01(\x0b\x32\x18.flare.runtime.ImageSpan\"\xf2\x03\n\x10\x46rontendContract\x12(\n\x05tools\x18\x01 \x01(\x0b\x32\x19.flare.runtime.ToolParser\x12\x31\n\treasoning\x18\x02 \x01(\x0b\x32\x1e.flare.runtime.ReasoningParser\x12\x43\n\x11image_preparation\x18\x03 \x01(\x0e\x32#.flare.runtime.ImagePreparationKindH\x00\x88\x01\x01\x12\x39\n\x0cimage_layout\x18\x04 \x01(\x0e\x32\x1e.flare.runtime.ImageLayoutKindH\x01\x88\x01\x01\x12\x17\n\x0frejected_tokens\x18\x05 \x03(\r\x12\x1b\n\x13position_dimensions\x18\x06 \x01(\r\x12\x18\n\x10\x61ssistant_marker\x18\x07 \x01(\t\x12\x1b\n\x13message_end_markers\x18\x08 \x03(\t\x12\x36\n\x0fprefix_boundary\x18\t \x01(\x0b\x32\x1d.flare.runtime.PrefixBoundary\x12\x35\n\x0cimage_tokens\x18\n \x01(\x0b\x32\x1f.flare.runtime.ImageTokenLayoutB\x14\n\x12_image_preparationB\x0f\n\r_image_layout\"1\n\x07\x43luster\x12\r\n\x05world\x18\x01 \x01(\r\x12\x11\n\texport_id\x18\x03 \x01(\tJ\x04\x08\x02\x10\x03\"\x8c\x03\n\x19\x44\x65\x66\x61ultSamplingParameters\x12\x11\n\x04seed\x18\x01 \x01(\x04H\x00\x88\x01\x01\x12\x18\n\x0btemperature\x18\x02 \x01(\x02H\x01\x88\x01\x01\x12\x12\n\x05top_k\x18\x03 \x01(\x05H\x02\x88\x01\x01\x12\x12\n\x05top_p\x18\x04 \x01(\x02H\x03\x88\x01\x01\x12\x12\n\x05min_p\x18\x05 \x01(\x02H\x04\x88\x01\x01\x12\x1f\n\x12repetition_penalty\x18\x06 \x01(\x02H\x05\x88\x01\x01\x12\x1d\n\x10presence_penalty\x18\x07 \x01(\x02H\x06\x88\x01\x01\x12\x1e\n\x11\x66requency_penalty\x18\x08 \x01(\x02H\x07\x88\x01\x01\x12-\n\x06ranges\x18\t \x01(\x0b\x32\x1d.flare.runtime.SamplingRangesB\x07\n\x05_seedB\x0e\n\x0c_temperatureB\x08\n\x06_top_kB\x08\n\x06_top_pB\x08\n\x06_min_pB\x15\n\x13_repetition_penaltyB\x13\n\x11_presence_penaltyB\x14\n\x12_frequency_penalty\"H\n\x12SamplingFloatRange\x12\x10\n\x03min\x18\x01 \x01(\x02H\x00\x88\x01\x01\x12\x10\n\x03max\x18\x02 \x01(\x02H\x01\x88\x01\x01\x42\x06\n\x04_minB\x06\n\x04_max\"F\n\x10SamplingIntRange\x12\x10\n\x03min\x18\x01 \x01(\x05H\x00\x88\x01\x01\x12\x10\n\x03max\x18\x02 \x01(\x05H\x01\x88\x01\x01\x42\x06\n\x04_minB\x06\n\x04_max\"\x96\x03\n\x0eSamplingRanges\x12\x36\n\x0btemperature\x18\x01 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12.\n\x05top_k\x18\x02 \x01(\x0b\x32\x1f.flare.runtime.SamplingIntRange\x12\x30\n\x05top_p\x18\x03 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12\x30\n\x05min_p\x18\x04 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12=\n\x12repetition_penalty\x18\x05 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12;\n\x10presence_penalty\x18\x06 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12<\n\x11\x66requency_penalty\x18\x07 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\"\xc5\x02\n\x10\x46rontendSettings\x12\x33\n\ttokenizer\x18\x01 \x01(\x0b\x32 .flare.runtime.TokenizerSettings\x12+\n\x05image\x18\x02 \x01(\x0b\x32\x1c.flare.runtime.ImageSettings\x12\x15\n\reos_token_ids\x18\x03 \x03(\r\x12:\n\x11template_encoding\x18\x04 \x01(\x0e\x32\x1f.flare.runtime.TemplateEncoding\x12\x34\n\x0eprompt_encoder\x18\x05 \x01(\x0e\x32\x1c.flare.runtime.PromptEncoder\x12\'\n\x1aimage_placeholder_token_id\x18\x06 \x01(\rH\x00\x88\x01\x01\x42\x1d\n\x1b_image_placeholder_token_id\"\xdc\x02\n\x11TokenizerSettings\x12\x16\n\tbos_token\x18\x01 \x01(\tH\x00\x88\x01\x01\x12\x16\n\teos_token\x18\x02 \x01(\tH\x01\x88\x01\x01\x12\x16\n\tunk_token\x18\x03 \x01(\tH\x02\x88\x01\x01\x12\x16\n\tsep_token\x18\x04 \x01(\tH\x03\x88\x01\x01\x12\x16\n\tpad_token\x18\x05 \x01(\tH\x04\x88\x01\x01\x12\x16\n\tcls_token\x18\x06 \x01(\tH\x05\x88\x01\x01\x12\x17\n\nmask_token\x18\x07 \x01(\tH\x06\x88\x01\x01\x12;\n\x19\x61\x64\x64itional_special_tokens\x18\x08 \x01(\x0b\x32\x18.flare.runtime.TokenListB\x0c\n\n_bos_tokenB\x0c\n\n_eos_tokenB\x0c\n\n_unk_tokenB\x0c\n\n_sep_tokenB\x0c\n\n_pad_tokenB\x0c\n\n_cls_tokenB\r\n\x0b_mask_token\"\x1b\n\tTokenList\x12\x0e\n\x06values\x18\x01 \x03(\t\"\xfc\x03\n\rImageSettings\x12\x30\n\x04qwen\x18\x01 \x01(\x0b\x32 .flare.runtime.QwenImageSettingsH\x00\x12\x30\n\x04mimo\x18\x02 \x01(\x0b\x32 .flare.runtime.MimoImageSettingsH\x00\x12)\n\tdeepseek4\x18\x03 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12\'\n\x07moonvit\x18\x04 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12$\n\x04step\x18\x05 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12%\n\x05radio\x18\x06 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12J\n\x12\x64\x65\x65pseek_row_major\x18\x07 \x01(\x0b\x32,.flare.runtime.DeepseekRowMajorImageSettingsH\x00\x12#\n\x03glm\x18\x08 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12=\n\x0bpatch_merge\x18\t \x01(\x0b\x32&.flare.runtime.PatchMergeImageSettingsH\x00\x12+\n\x0bpadded_grid\x18\n \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x42\t\n\x07profile\"\xb9\x01\n\x17PatchMergeImageSettings\x12\x12\n\npatch_size\x18\x01 \x01(\r\x12\x12\n\nmin_pixels\x18\x02 \x01(\x04\x12\x12\n\nmax_pixels\x18\x03 \x01(\x04\x12\x12\n\nimage_mean\x18\x04 \x03(\x02\x12\x11\n\timage_std\x18\x05 \x03(\x02\x12\x13\n\x0bimage_token\x18\x06 \x01(\t\x12\x13\n\x0bstart_token\x18\x07 \x01(\t\x12\x11\n\tend_token\x18\x08 \x01(\t\"\x87\x01\n\x1d\x44\x65\x65pseekRowMajorImageSettings\x12\x12\n\nmin_pixels\x18\x01 \x01(\x04\x12\x12\n\nmax_tokens\x18\x02 \x01(\x04\x12#\n\x16max_width_height_ratio\x18\x03 \x01(\x04H\x00\x88\x01\x01\x42\x19\n\x17_max_width_height_ratio\"\x82\x01\n\x11QwenImageSettings\x12\x12\n\nmin_pixels\x18\x01 \x01(\x04\x12\x12\n\nmax_pixels\x18\x02 \x01(\x04\x12\x15\n\rposition_side\x18\x03 \x01(\r\x12\x16\n\x0eimage_token_id\x18\x04 \x01(\r\x12\x16\n\x0evideo_token_id\x18\x05 \x01(\r\"b\n\x11MimoImageSettings\x12\x12\n\nmin_pixels\x18\x01 \x01(\x04\x12\x12\n\nmax_pixels\x18\x02 \x01(\x04\x12\x12\n\nimage_mean\x18\x03 \x03(\x02\x12\x11\n\timage_std\x18\x04 \x03(\x02\"|\n\x06\x45ngram\x12\x11\n\ttoken_map\x18\x01 \x03(\r\x12\x14\n\x0cpad_token_id\x18\x02 \x01(\r\x12\x1d\n\x15\x63ompressed_vocabulary\x18\x03 \x01(\r\x12*\n\x06tables\x18\x04 \x03(\x0b\x32\x1a.flare.runtime.EngramTable\"\xa3\x04\n\x0b\x45ngramTable\x12\r\n\x05layer\x18\x01 \x01(\r\x12\x0c\n\x04rows\x18\x02 \x01(\x04\x12\x17\n\x0f\x65mbedding_width\x18\x03 \x01(\r\x12\x13\n\x0bscale_block\x18\x04 \x01(\r\x12$\n\x07weights\x18\x05 \x01(\x0b\x32\x13.flare.runtime.Span\x12#\n\x06scales\x18\x06 \x01(\x0b\x32\x13.flare.runtime.Span\x12\'\n\x04hash\x18\x07 \x01(\x0b\x32\x19.flare.runtime.EngramHash\x12\x15\n\rweight_buffer\x18\x08 \x01(\t\x12\x14\n\x0cscale_buffer\x18\t \x01(\t\x12\x13\n\x0bhash_buffer\x18\n \x01(\t\x12\x13\n\x0bready_event\x18\x0b \x01(\t\x12\x35\n\x08\x65ncoding\x18\x0c \x01(\x0e\x32#.flare.runtime.EngramTable.Encoding\x12\x16\n\x0erequest_buffer\x18\r \x01(\t\x12\x14\n\x0cglobal_scale\x18\x0e \x01(\x02\x12/\n\x06shards\x18\x0f \x03(\x0b\x32\x1f.flare.runtime.EngramTableShard\x12\x17\n\x0fprefetch_buffer\x18\x10 \x01(\t\"O\n\x08\x45ncoding\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x11\n\rFP8_E4M3_E8M0\x10\x01\x12\x15\n\x11NVFP4_E4M3_GLOBAL\x10\x02\x12\x08\n\x04\x42\x46\x31\x36\x10\x03\"\x8c\x01\n\x10\x45ngramTableShard\x12\x0c\n\x04rank\x18\x01 \x01(\r\x12\x11\n\tfirst_row\x18\x02 \x01(\x04\x12\x0c\n\x04rows\x18\x03 \x01(\x04\x12$\n\x07weights\x18\x04 \x01(\x0b\x32\x13.flare.runtime.Span\x12#\n\x06scales\x18\x05 \x01(\x0b\x32\x13.flare.runtime.Span\"\xd1\x01\n\nEngramHash\x12\x30\n\x06method\x18\x01 \x01(\x0e\x32 .flare.runtime.EngramHash.Method\x12\x0e\n\x06orders\x18\x02 \x03(\r\x12\x13\n\x0bmultipliers\x18\x03 \x03(\x04\x12\x0e\n\x06primes\x18\x04 \x03(\x04\x12\x0f\n\x07offsets\x18\x05 \x03(\x04\"K\n\x06Method\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nXOR_MODULO\x10\x01\x12\x12\n\x0e\x45OS_XOR_MODULO\x10\x02\x12\x0c\n\x08IDENTITY\x10\x03\"K\n\x05\x41sset\x12\x0c\n\x04name\x18\x01 \x01(\t\x12$\n\x07payload\x18\x02 \x01(\x0b\x32\x13.flare.runtime.Span\x12\x0e\n\x06sha256\x18\x03 \x01(\t\"\xd3\x04\n\x0b\x42undleIndex\x12\x14\n\x0c\x61rchitecture\x18\x01 \x03(\x05\x12.\n\x0b\x61llocations\x18\x02 \x03(\x0b\x32\x19.flare.runtime.Allocation\x12&\n\x07modules\x18\x03 \x03(\x0b\x32\x15.flare.runtime.Module\x12*\n\tfunctions\x18\x04 \x03(\x0b\x32\x17.flare.runtime.Function\x12)\n\x06graphs\x18\x05 \x03(\x0b\x32\x19.flare.runtime.GraphIndex\x12\x30\n\x0creservations\x18\x06 \x03(\x0b\x32\x1a.flare.runtime.Reservation\x12+\n\texecution\x18\x07 \x01(\x0b\x32\x18.flare.runtime.Execution\x12\'\n\x07\x63ontext\x18\x08 \x01(\x0b\x32\x16.flare.runtime.Context\x12<\n\tresources\x18\t \x03(\x0b\x32).flare.runtime.BundleIndex.ResourcesEntry\x12\x0e\n\x06\x65vents\x18\n \x03(\t\x12*\n\x04roce\x18\x0b \x01(\x0b\x32\x1c.flare.runtime.RoceTransport\x12\x36\n\x0frebuild_weights\x18\x0c \x01(\x0b\x32\x1d.flare.runtime.RebuildWeights\x1a\x45\n\x0eResourcesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\"\n\x05value\x18\x02 \x01(\x0b\x32\x13.flare.runtime.Span:\x02\x38\x01\"\xf8\x01\n\rRoceTransport\x12\x11\n\tproxy_abi\x18\x01 \x01(\r\x12\r\n\x05world\x18\x02 \x01(\r\x12\x0c\n\x04rank\x18\x03 \x01(\r\x12\x16\n\x0eregion_address\x18\x04 \x01(\x04\x12\x14\n\x0cregion_bytes\x18\x05 \x01(\x04\x12\x18\n\x10\x63ounters_address\x18\x06 \x01(\x04\x12\x16\n\x0e\x63ounters_bytes\x18\x07 \x01(\x04\x12\x12\n\nslot_bytes\x18\x08 \x01(\x04\x12\x12\n\npipe_bytes\x18\t \x01(\x04\x12\x13\n\x0b\x63trl_offset\x18\n \x01(\x04\x12\x14\n\x0cvarlen_bytes\x18\x10 \x01(\x04J\x04\x08\x0b\x10\x10\"v\n\nGraphIndex\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05\x66lags\x18\x02 \x01(\x04\x12\x10\n\x08resource\x18\x03 \x01(\t\x12\x12\n\nnode_count\x18\x04 \x01(\x04\x12\x12\n\nedge_count\x18\x05 \x01(\x04\x12\x11\n\tfunctions\x18\x06 \x03(\x04\"M\n\nPeerMemory\x12\r\n\x05owner\x18\x01 \x01(\r\x12\x0f\n\x07\x61\x64\x64ress\x18\x02 \x01(\x04\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04\x12\x0f\n\x07readers\x18\x04 \x03(\r\"M\n\x07\x43ontext\x12\r\n\x05\x66lags\x18\x01 \x01(\r\x12\r\n\x05\x63\x61\x63he\x18\x02 \x01(\x05\x12$\n\x06limits\x18\x03 \x03(\x0b\x32\x14.flare.runtime.Limit\"\"\n\x05Limit\x12\n\n\x02id\x18\x01 \x01(\x04\x12\r\n\x05value\x18\x02 \x01(\x04\".\n\x0bReservation\x12\x0f\n\x07\x61\x64\x64ress\x18\x01 \x01(\x04\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\"8\n\x04Span\x12\x0e\n\x06offset\x18\x01 \x01(\x04\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\x12\x10\n\x08\x66ilename\x18\x03 \x01(\t\"\xa2\x02\n\nAllocation\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\x12\x11\n\talignment\x18\x03 \x01(\x04\x12\x11\n\x04\x66ile\x18\x04 \x01(\tH\x00\x88\x01\x01\x12\'\n\ndata_spans\x18\x05 \x03(\x0b\x32\x13.flare.runtime.Span\x12.\n\x0brelocations\x18\x06 \x03(\x0b\x32\x19.flare.runtime.Relocation\x12\x14\n\x07\x61\x64\x64ress\x18\x07 \x01(\x04H\x01\x88\x01\x01\x12%\n\x06memory\x18\x08 \x01(\x0e\x32\x15.flare.runtime.Memory\x12%\n\x06sizing\x18\t \x01(\x0b\x32\x15.flare.runtime.SizingB\x07\n\x05_fileB\n\n\x08_address\"X\n\x06Sizing\x12)\n\x08\x63\x61pacity\x18\x01 \x01(\x0e\x32\x17.flare.runtime.Capacity\x12\x12\n\nunit_bytes\x18\x02 \x01(\x04\x12\x0f\n\x07maximum\x18\x03 \x01(\x04\"L\n\x06Module\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04\x66ile\x18\x02 \x01(\t\x12&\n\x07globals\x18\x03 \x03(\x0b\x32\x15.flare.runtime.Global\"f\n\x06Global\x12\x0e\n\x06symbol\x18\x01 \x01(\t\x12\x0c\n\x04\x66ile\x18\x02 \x01(\t\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04\x12.\n\x0brelocations\x18\x04 \x03(\x0b\x32\x19.flare.runtime.Relocation\"y\n\x08\x46unction\x12\x0e\n\x06module\x18\x01 \x01(\t\x12\x0e\n\x06symbol\x18\x02 \x01(\t\x12\x17\n\x0fparameter_sizes\x18\x03 \x03(\x04\x12\x34\n\nattributes\x18\x04 \x03(\x0b\x32 .flare.runtime.FunctionAttribute\".\n\x11\x46unctionAttribute\x12\n\n\x02id\x18\x01 \x01(\x05\x12\r\n\x05value\x18\x02 \x01(\x05\"/\n\tReference\x12\x12\n\nallocation\x18\x01 \x01(\t\x12\x0e\n\x06offset\x18\x02 \x01(\x04\"s\n\nRelocation\x12\x0e\n\x06offset\x18\x01 \x01(\x04\x12(\n\x06target\x18\x02 \x01(\x0b\x32\x18.flare.runtime.Reference\x12+\n\x04kind\x18\x03 \x01(\x0e\x32\x1d.flare.runtime.RelocationKind\"D\n\x04\x42lob\x12\x0c\n\x04\x64\x61ta\x18\x01 \x01(\x0c\x12.\n\x0brelocations\x18\x02 \x03(\x0b\x32\x19.flare.runtime.Relocation\";\n\tAttribute\x12\n\n\x02id\x18\x01 \x01(\x05\x12\"\n\x05value\x18\x02 \x01(\x0b\x32\x13.flare.runtime.Blob\"\x9d\x01\n\x06Kernel\x12\x10\n\x08\x66unction\x18\x01 \x01(\x04\x12\x0c\n\x04grid\x18\x02 \x03(\r\x12\r\n\x05\x62lock\x18\x03 \x03(\r\x12\x0e\n\x06shared\x18\x04 \x01(\r\x12&\n\targuments\x18\x05 \x03(\x0b\x32\x13.flare.runtime.Blob\x12,\n\nattributes\x18\x06 \x03(\x0b\x32\x18.flare.runtime.Attribute\"\x8a\x01\n\x06Memset\x12-\n\x0b\x64\x65stination\x18\x01 \x01(\x0b\x32\x18.flare.runtime.Reference\x12\r\n\x05pitch\x18\x02 \x01(\x04\x12\r\n\x05value\x18\x03 \x01(\r\x12\x14\n\x0c\x65lement_size\x18\x04 \x01(\r\x12\r\n\x05width\x18\x05 \x01(\x04\x12\x0e\n\x06height\x18\x06 \x01(\x04\"o\n\x04\x43opy\x12(\n\x06source\x18\x01 \x01(\x0b\x32\x18.flare.runtime.Reference\x12-\n\x0b\x64\x65stination\x18\x02 \x01(\x0b\x32\x18.flare.runtime.Reference\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04\"\x07\n\x05\x45mpty\"\x1a\n\tEventWait\x12\r\n\x05\x65vent\x18\x01 \x01(\t\"\xe1\x01\n\x04Node\x12\'\n\x06kernel\x18\x01 \x01(\x0b\x32\x15.flare.runtime.KernelH\x00\x12\'\n\x06memset\x18\x02 \x01(\x0b\x32\x15.flare.runtime.MemsetH\x00\x12#\n\x04\x63opy\x18\x03 \x01(\x0b\x32\x13.flare.runtime.CopyH\x00\x12%\n\x05\x65mpty\x18\x04 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12.\n\nevent_wait\x18\x05 \x01(\x0b\x32\x18.flare.runtime.EventWaitH\x00\x42\x0b\n\toperation\"9\n\x04\x45\x64ge\x12\x0e\n\x06source\x18\x01 \x01(\x04\x12\x13\n\x0b\x64\x65stination\x18\x02 \x01(\x04\x12\x0c\n\x04\x64\x61ta\x18\x03 \x01(\x0c\"\xf0\x02\n\tExecution\x12\x13\n\x0b\x61\x62i_version\x18\x01 \x01(\r\x12\x12\n\nmax_active\x18\x02 \x01(\x04\x12\x19\n\x11input_frame_bytes\x18\x03 \x01(\x04\x12&\n\x07\x62uffers\x18\x04 \x03(\x0b\x32\x15.flare.runtime.Buffer\x12-\n\x06graphs\x18\x05 \x03(\x0b\x32\x1d.flare.runtime.ExecutionGraph\x12\x31\n\rtuning_graphs\x18\x06 \x03(\x0b\x32\x1a.flare.runtime.TuningGraph\x12!\n\x19\x63ompletion_token_capacity\x18\x07 \x01(\r\x12;\n\x12persistent_workers\x18\x08 \x03(\x0b\x32\x1f.flare.runtime.PersistentWorker\x12\x35\n\x0f\x61sync_transfers\x18\t \x03(\x0b\x32\x1c.flare.runtime.AsyncTransfer\"\xb1\x02\n\rAsyncTransfer\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x0b\x64\x65vice_pool\x18\x02 \x01(\t\x12)\n\x07\x63ontrol\x18\x03 \x01(\x0b\x32\x18.flare.runtime.Reference\x12\x15\n\rcontrol_bytes\x18\x04 \x01(\x04\x12\x34\n\x12\x64\x65vice_completions\x18\x05 \x01(\x0b\x32\x18.flare.runtime.Reference\x12\x18\n\x10\x63ompletion_slots\x18\x06 \x01(\r\x12\x15\n\rring_capacity\x18\x07 \x01(\r\x12\x1b\n\x13max_host_pool_bytes\x18\x08 \x01(\x04\x12\x11\n\talignment\x18\t \x01(\r\x12$\n\x07\x65xtents\x18\n \x03(\x0b\x32\x13.flare.runtime.Span\"\xa9\x01\n\x10PersistentWorker\x12\x17\n\x0fworker_sm_count\x18\x01 \x01(\r\x12\r\n\x05graph\x18\x02 \x01(\t\x12+\n\tstop_flag\x18\x03 \x01(\x0b\x32\x18.flare.runtime.Reference\x12)\n\x07metrics\x18\x04 \x01(\x0b\x32\x18.flare.runtime.Reference\x12\x15\n\rmetrics_count\x18\x05 \x01(\r\"C\n\x0bTuningGraph\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07outputs\x18\x02 \x03(\t\x12\x15\n\rstatus_buffer\x18\x03 \x01(\t\"\x82\x01\n\x06\x42uffer\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\x12\r\n\x05\x64type\x18\x03 \x01(\t\x12\r\n\x05shape\x18\x04 \x03(\x04\x12\x0f\n\x07strides\x18\x05 \x03(\x04\x12+\n\treference\x18\x06 \x01(\x0b\x32\x18.flare.runtime.Reference\"\x95\x04\n\x0e\x45xecutionGraph\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04kind\x18\x02 \x01(\t\x12\x15\n\rsampling_mode\x18\x03 \x01(\t\x12\x16\n\x0e\x62\x61tch_capacity\x18\x04 \x01(\x04\x12\x16\n\x0etoken_capacity\x18\x05 \x01(\x04\x12\x33\n\x0einput_bindings\x18\x06 \x03(\x0b\x32\x1b.flare.runtime.InputBinding\x12\x19\n\x0c\x64raft_tokens\x18\x07 \x01(\rH\x00\x88\x01\x01\x12\x1a\n\rverify_tokens\x18\x08 \x01(\rH\x01\x88\x01\x01\x12\x30\n\x0c\x64raft_source\x18\t \x01(\x0e\x32\x1a.flare.runtime.DraftSource\x12 \n\x13speculation_enabled\x18\n \x01(\x08H\x02\x88\x01\x01\x12\x1d\n\x15\x65stimated_duration_ns\x18\x0b \x01(\x04\x12\x18\n\x10prefill_capacity\x18\x0c \x01(\x04\x12\x1d\n\x15packed_token_capacity\x18\r \x01(\x04\x12\x18\n\x10\x63onfidence_width\x18\x0e \x01(\r\x12\x33\n\x0etuned_bindings\x18\x0f \x03(\x0b\x32\x1b.flare.runtime.TunedBindingB\x0f\n\r_draft_tokensB\x10\n\x0e_verify_tokensB\x16\n\x14_speculation_enabled\"H\n\x0cInputBinding\x12\x13\n\x0b\x62uffer_name\x18\x01 \x01(\t\x12\x13\n\x0bhost_offset\x18\x02 \x01(\x04\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04*\xfa\x01\n\x19PreparationParameterScope\x12+\n\'PREPARATION_PARAMETER_SCOPE_UNSPECIFIED\x10\x00\x12*\n&PREPARATION_PARAMETER_SCOPE_DEPLOYMENT\x10\x01\x12\'\n#PREPARATION_PARAMETER_SCOPE_COMBINE\x10\x02\x12-\n)PREPARATION_PARAMETER_SCOPE_TARGET_WEIGHT\x10\x03\x12,\n(PREPARATION_PARAMETER_SCOPE_DRAFT_WEIGHT\x10\x04*\x8e\x01\n\x0bHistoryKind\x12\x17\n\x13HISTORY_UNSPECIFIED\x10\x00\x12\x13\n\x0fPAGED_KEY_VALUE\x10\x01\x12\x10\n\x0cPAGED_LATENT\x10\x02\x12\x12\n\x0eSLIDING_WINDOW\x10\x03\x12\x13\n\x0fRECURRENT_STATE\x10\x04\x12\x16\n\x12\x43ONTINUATION_STATE\x10\x05*\xc7\x07\n\x0bValueSource\x12\x15\n\x11VALUE_UNSPECIFIED\x10\x00\x12\x0c\n\x08\x43ONSTANT\x10\x01\x12\x10\n\x0cREQUEST_SLOT\x10\x02\x12\x16\n\x12REQUEST_GENERATION\x10\x03\x12\r\n\tLIVE_ROWS\x10\x04\x12\x10\n\x0cQUERY_LENGTH\x10\x05\x12\x12\n\x0eSAMPLE_ENABLED\x10\x06\x12\x10\n\x0cPROMPT_TOKEN\x10\x07\x12\x11\n\rPENDING_TOKEN\x10\x08\x12\x1c\n\x18PROMPT_AND_PENDING_TOKEN\x10\t\x12\x13\n\x0fPROMPT_POSITION\x10\n\x12\x17\n\x13IMAGE_FEATURE_INDEX\x10\x0b\x12\x16\n\x12IMAGE_LEFT_CONTEXT\x10\x0c\x12\x17\n\x13IMAGE_RIGHT_CONTEXT\x10\r\x12\x0e\n\nPAGE_TABLE\x10\x0e\x12\x13\n\x0fLIVE_STATE_ROWS\x10\x0f\x12\x12\n\x0eLIVE_STATE_ROW\x10\x10\x12\x14\n\x10PREFIX_STATE_ROW\x10\x11\x12\x16\n\x12SNAPSHOT_STATE_ROW\x10\x12\x12\x13\n\x0f\x43ONSUMED_TOKENS\x10\x13\x12\x1c\n\x18SNAPSHOT_CONSUMED_TOKENS\x10\x14\x12\x0f\n\x0bPREFILL_ROW\x10\x15\x12\x11\n\rSAMPLING_SEED\x10\x16\x12\x17\n\x13SAMPLING_PARAMETERS\x10\x17\x12\x12\n\x0eSAMPLING_TOP_K\x10\x18\x12\x12\n\x0eMAX_NEW_TOKENS\x10\x19\x12\x11\n\rEOS_TOKEN_IDS\x10\x1a\x12\r\n\tEOS_COUNT\x10\x1b\x12\x14\n\x10PROMPT_HISTOGRAM\x10\x1c\x12\x10\n\x0cGRAMMAR_MASK\x10\x1d\x12\x13\n\x0fGRAMMAR_ENABLED\x10\x1e\x12\x12\n\x0e\x43OPY_TOKEN_IDS\x10\x1f\x12\x14\n\x10\x43OPY_TOKEN_COUNT\x10 \x12\x18\n\x14\x43OPY_CONSUMED_TOKENS\x10!\x12\x13\n\x0f\x43OPY_GENERATION\x10\"\x12\x15\n\x11\x43OPY_GRAMMAR_MASK\x10#\x12\x16\n\x12\x43OPY_GRAMMAR_COUNT\x10$\x12\x10\n\x0cIMAGE_TENSOR\x10%\x12\x16\n\x12IMAGE_FEATURE_SLOT\x10&\x12\x17\n\x13PROMPT_TARGET_TOKEN\x10\'\x12\x1c\n\x18SPECULATIVE_PREFIX_LIMIT\x10(\x12\x1a\n\x16PROMPT_LOOKAHEAD_TOKEN\x10)\x12\x1b\n\x17PROMPT_LOOKAHEAD_LENGTH\x10*\x12\x12\n\x0e\x43ORE_PARAMETER\x10+*|\n\rInputIndexing\x12\x18\n\x14INDEXING_UNSPECIFIED\x10\x00\x12\n\n\x06SCALAR\x10\x01\x12\x12\n\x0eSUBMISSION_ROW\x10\x02\x12\x0f\n\x0bREQUEST_ROW\x10\x03\x12\x10\n\x0cPACKED_TOKEN\x10\x04\x12\x0e\n\nACTIVE_ROW\x10\x05*T\n\x0fStateAccessKind\x12\x1c\n\x18STATE_ACCESS_UNSPECIFIED\x10\x00\x12\x08\n\x04READ\x10\x01\x12\t\n\x05WRITE\x10\x02\x12\x0e\n\nREAD_WRITE\x10\x03*\x8b\x02\n\x0eGraphOperation\x12\x1f\n\x1bGRAPH_OPERATION_UNSPECIFIED\x10\x00\x12\x08\n\x04INIT\x10\x01\x12\x0b\n\x07RESTORE\x10\x02\x12\x0c\n\x08SNAPSHOT\x10\x03\x12\x0b\n\x07PREFILL\x10\x04\x12\n\n\x06\x44\x45\x43ODE\x10\x05\x12\n\n\x06RESUME\x10\x06\x12\n\n\x06VISION\x10\x07\x12\x0f\n\x0bSPECULATIVE\x10\x08\x12\t\n\x05MIXED\x10\t\x12\x12\n\x0eSCORED_PREFILL\x10\x0c\x12\x14\n\x10TERMINAL_PREFILL\x10\x0e\"\x04\x08\n\x10\n\"\x04\x08\x0b\x10\x0b\"\x04\x08\r\x10\r*\x08PROPOSAL*\x0cVERIFICATION*\x12PACKED_SPECULATIVE*\xb2\x01\n\x0eToolParserKind\x12\x1b\n\x17TOOL_PARSER_UNSPECIFIED\x10\x00\x12\x0e\n\nQWEN_CODER\x10\x01\x12\x15\n\x11GLM_ARGUMENT_TAGS\x10\x02\x12\x08\n\x04\x44SML\x10\x03\x12\x08\n\x04XTML\x10\x04\x12\x0f\n\x0bMINIMAX_XML\x10\x05\x12\x0e\n\nGEMMA_CALL\x10\x06\x12\x08\n\x04\x41TEM\x10\x07\x12\x0c\n\x08TML_JSON\x10\x08\x12\x0f\n\x0bTAGGED_JSON\x10\t*\xa6\x01\n\x13ReasoningParserKind\x12 \n\x1cREASONING_PARSER_UNSPECIFIED\x10\x00\x12\x0e\n\nTHINK_TAGS\x10\x01\x12\x0e\n\nXTML_THINK\x10\x02\x12\x0c\n\x08MM_THINK\x10\x03\x12\x13\n\x0f\x43HANNEL_THOUGHT\x10\x04\x12\x15\n\x11RECIPIENT_HEADERS\x10\x05\x12\x13\n\x0f\x43ONTENT_HEADERS\x10\x06*\xf4\x02\n\x14ImagePreparationKind\x12!\n\x1dIMAGE_PREPARATION_UNSPECIFIED\x10\x00\x12\x1a\n\x16QWEN_IMAGE_PREPARATION\x10\x01\x12\x1a\n\x16MIMO_IMAGE_PREPARATION\x10\x02\x12\x1e\n\x1a\x44\x45\x45PSEEK_IMAGE_PREPARATION\x10\x03\x12\x1d\n\x19MOONVIT_IMAGE_PREPARATION\x10\x04\x12\x1a\n\x16STEP_IMAGE_PREPARATION\x10\x05\x12\x1b\n\x17RADIO_IMAGE_PREPARATION\x10\x06\x12(\n$DEEPSEEK_ROW_MAJOR_IMAGE_PREPARATION\x10\x07\x12\x19\n\x15GLM_IMAGE_PREPARATION\x10\x08\x12!\n\x1dPATCH_MERGE_IMAGE_PREPARATION\x10\t\x12!\n\x1dPADDED_GRID_IMAGE_PREPARATION\x10\n*\xb6\x02\n\x0fImageLayoutKind\x12\x1c\n\x18IMAGE_LAYOUT_UNSPECIFIED\x10\x00\x12\x15\n\x11QWEN_IMAGE_LAYOUT\x10\x01\x12\x15\n\x11MIMO_IMAGE_LAYOUT\x10\x02\x12\x19\n\x15\x44\x45\x45PSEEK_IMAGE_LAYOUT\x10\x03\x12\x18\n\x14MOONVIT_IMAGE_LAYOUT\x10\x04\x12\x15\n\x11STEP_IMAGE_LAYOUT\x10\x05\x12\x16\n\x12RADIO_IMAGE_LAYOUT\x10\x06\x12#\n\x1f\x44\x45\x45PSEEK_ROW_MAJOR_IMAGE_LAYOUT\x10\x07\x12\x14\n\x10GLM_IMAGE_LAYOUT\x10\x08\x12\x1a\n\x16\x42RACKETED_IMAGE_LAYOUT\x10\t\x12\x1c\n\x18\x43LASS_TOKEN_IMAGE_LAYOUT\x10\n*P\n\rPromptEncoder\x12\x10\n\x0cPROMPT_JINJA\x10\x00\x12\x0f\n\x0b\x44\x45\x45PSEEK_V4\x10\x01\x12\x10\n\x0c\x44\x45\x45PSEEK_V41\x10\x02\x12\n\n\x06TML_V0\x10\x03*B\n\x10TemplateEncoding\x12\x11\n\rTEMPLATE_TEXT\x10\x00\x12\x1b\n\x17TEMPLATE_TOKEN_SEGMENTS\x10\x01*/\n\x06Memory\x12\n\n\x06\x44\x45VICE\x10\x00\x12\x0f\n\x0bMAPPED_HOST\x10\x01\x12\x08\n\x04PEER\x10\x02*9\n\x08\x43\x61pacity\x12\x0e\n\nSTATE_ROWS\x10\x00\x12\x0c\n\x08KV_PAGES\x10\x01\x12\x0f\n\x0b\x44\x45VICE_POOL\x10\x02*-\n\x0eRelocationKind\x12\x0b\n\x07POINTER\x10\x00\x12\x0e\n\nTENSOR_MAP\x10\x01*4\n\x0b\x44raftSource\x12\x0c\n\x08NO_DRAFT\x10\x00\x12\x07\n\x03MTP\x10\x01\x12\x0e\n\nCOPY_DRAFT\x10\x02\x62\x06proto3') +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x12runtime_core.proto\x12\rflare.runtime\"\x99\x01\n\x0eProtectedIndex\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x0f\n\x07\x63ore_id\x18\x02 \x01(\x0c\x12\x0e\n\x06signer\x18\x03 \x01(\x0c\x12*\n\x06groups\x18\x04 \x03(\x0b\x32\x1a.flare.runtime.SignedGroup\x12)\n\x05ranks\x18\x05 \x03(\x0b\x32\x1a.flare.runtime.SignedGroup\"<\n\x0bSignedGroup\x12\x0c\n\x04kind\x18\x01 \x01(\r\x12\x0c\n\x04\x62ody\x18\x02 \x01(\x0c\x12\x11\n\tsignature\x18\x03 \x01(\x0c\"\xcc\x01\n\x11PublisherMetadata\x12(\n\x05index\x18\x01 \x01(\x0b\x32\x19.flare.runtime.ModelIndex\x12\x11\n\tnamespace\x18\x02 \x01(\t\x12\x17\n\x0fofficial_source\x18\x03 \x01(\t\x12\x14\n\x0cgroup_hashes\x18\x04 \x03(\x0c\x12\x13\n\x0b\x64\x65velopment\x18\x05 \x01(\x08\x12\r\n\x05ranks\x18\x06 \x01(\r\x12\'\n\x07license\x18\x07 \x01(\x0b\x32\x16.flare.runtime.License\"%\n\x07License\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04link\x18\x02 \x01(\t\"F\n\x0fResourceCatalog\x12\x33\n\tresources\x18\x01 \x03(\x0b\x32 .flare.runtime.ProtectedResource\"^\n\x11ProtectedResource\x12\x0e\n\x06offset\x18\x01 \x01(\x04\x12\x14\n\x0cstored_bytes\x18\x02 \x01(\x04\x12\x13\n\x0bplain_bytes\x18\x03 \x01(\x04\x12\x0e\n\x06sha256\x18\x04 \x03(\x0c\"`\n\nStoredData\x12\x0e\n\x06nbytes\x18\x01 \x01(\x04\x12\x0e\n\x06sha256\x18\x02 \x01(\x0c\x12\x0e\n\x06offset\x18\x03 \x01(\x04\x12\"\n\x05parts\x18\x04 \x03(\x0b\x32\x13.flare.runtime.Span\"\xd9\x01\n\x0eRankProtection\x12\x0c\n\x04rank\x18\x01 \x01(\r\x12*\n\x06\x62undle\x18\x02 \x01(\x0b\x32\x1a.flare.runtime.BundleIndex\x12\x33\n\x0b\x65xecutables\x18\x03 \x01(\x0b\x32\x1e.flare.runtime.ResourceCatalog\x12/\n\x07support\x18\x04 \x01(\x0b\x32\x1e.flare.runtime.ResourceCatalog\x12\'\n\x04\x64\x61ta\x18\x05 \x01(\x0b\x32\x19.flare.runtime.StoredData\"\x8c\x04\n\nModelIndex\x12\x0f\n\x07version\x18\x01 \x01(\r\x12)\n\x05ranks\x18\x02 \x03(\x0b\x32\x1a.flare.runtime.BundleIndex\x12.\n\x0bpeer_memory\x18\x03 \x03(\x0b\x32\x19.flare.runtime.PeerMemory\x12$\n\x06\x61ssets\x18\x05 \x03(\x0b\x32\x14.flare.runtime.Asset\x12%\n\x06\x65ngram\x18\x06 \x01(\x0b\x32\x15.flare.runtime.Engram\x12\x43\n\x11sampling_defaults\x18\x07 \x01(\x0b\x32(.flare.runtime.DefaultSamplingParameters\x12\x31\n\x08\x66rontend\x18\x08 \x01(\x0b\x32\x1f.flare.runtime.FrontendSettings\x12\'\n\x07\x63luster\x18\t \x01(\x0b\x32\x16.flare.runtime.Cluster\x12\x30\n\x08\x63ontract\x18\n \x01(\x0b\x32\x1e.flare.runtime.ServingContract\x12\x33\n\x07rebuild\x18\x0b \x01(\x0b\x32\x1e.flare.runtime.RebuildManifestB\x02\x18\x01\x12\x37\n\x0bpreparation\x18\x0c \x01(\x0b\x32\".flare.runtime.PreparationManifestJ\x04\x08\x04\x10\x05\"\xf9\x01\n\x13PreparationManifest\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x0e\n\x06recipe\x18\x02 \x01(\t\x12\x17\n\x0fsource_identity\x18\x03 \x01(\t\x12\x1d\n\x15\x63heckpoint_repository\x18\x04 \x01(\t\x12\x1b\n\x13\x63heckpoint_revision\x18\x05 \x01(\t\x12\x18\n\x10local_checkpoint\x18\x06 \x01(\x08\x12\x19\n\x11reproduction_args\x18\x07 \x03(\t\x12\x37\n\nparameters\x18\x08 \x03(\x0b\x32#.flare.runtime.PreparationParameter\"\x8c\x01\n\x14PreparationParameter\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x37\n\x05scope\x18\x02 \x01(\x0e\x32(.flare.runtime.PreparationParameterScope\x12.\n\x05value\x18\x03 \x01(\x0b\x32\x1f.flare.runtime.PreparationValue\"\xc6\x01\n\x10PreparationValue\x12\x14\n\nbool_value\x18\x01 \x01(\x08H\x00\x12\x13\n\tint_value\x18\x02 \x01(\x03H\x00\x12\x14\n\nuint_value\x18\x03 \x01(\x04H\x00\x12\x15\n\x0b\x66loat_value\x18\x04 \x01(\x01H\x00\x12\x16\n\x0cstring_value\x18\x05 \x01(\tH\x00\x12\x39\n\nlist_value\x18\x06 \x01(\x0b\x32#.flare.runtime.PreparationValueListH\x00\x42\x07\n\x05value\"G\n\x14PreparationValueList\x12/\n\x06values\x18\x01 \x03(\x0b\x32\x1f.flare.runtime.PreparationValue\"\xdb\x07\n\x0fRebuildManifest\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x0e\n\x06recipe\x18\x02 \x01(\t\x12\x17\n\x0fsource_identity\x18\x03 \x01(\t\x12\x1d\n\x15\x63heckpoint_repository\x18\x04 \x01(\t\x12\x1b\n\x13\x63heckpoint_revision\x18\x05 \x01(\t\x12\x17\n\x0ftensor_parallel\x18\x06 \x01(\r\x12\x17\n\x0fmax_concurrency\x18\x07 \x01(\x04\x12\x15\n\rprefill_chunk\x18\x08 \x01(\x04\x12\x19\n\x11image_concurrency\x18\t \x01(\x04\x12\x18\n\x10\x63ontext_parallel\x18\n \x01(\x08\x12\x16\n\x0estream_overlap\x18\x0b \x01(\x08\x12\x15\n\rmixed_prefill\x18\x0c \x01(\x08\x12%\n\x18\x65xpert_scale_compression\x18\r \x01(\tH\x00\x88\x01\x01\x12\x18\n\x10mla_compute_mode\x18\x0e \x01(\t\x12\x11\n\troce_ring\x18\x0f \x01(\x08\x12\x14\n\x0conline_mxfp8\x18\x10 \x01(\x08\x12\x1b\n\x13language_model_only\x18\x11 \x01(\x08\x12\x36\n\x0bspeculation\x18\x12 \x01(\x0b\x32!.flare.runtime.RebuildSpeculation\x12\x19\n\x11\x63ompiled_forwards\x18\x13 \x01(\x08\x12\x15\n\rreserve_bytes\x18\x14 \x01(\x04\x12\x18\n\x10local_checkpoint\x18\x15 \x01(\x08\x12\x12\n\nroce_chain\x18\x16 \x01(\x08\x12\x1e\n\x16shard_hyperconnections\x18\x18 \x01(\x08\x12\x1c\n\x14\x66orce_moe_decode_a16\x18\x1b \x01(\x08\x12\x19\n\x11row_shard_prefill\x18\x1c \x01(\x08\x12\x1a\n\x12online_mxfp8_scope\x18\x1e \x01(\t\x12\x1d\n\x15\x63ontext_parallel_size\x18\x1f \x01(\r\x12\x17\n\x0fprompt_logprobs\x18 \x01(\x08\x12\x17\n\x0f\x61utotune_effort\x18! \x01(\t\x12 \n\x18native_dense_activations\x18\" \x01(\x08\x12\x17\n\x0flock_gpu_clocks\x18# \x01(\x08\x12\x19\n\x11reproduction_args\x18$ \x03(\t:\x02\x18\x01\x42\x1b\n\x19_expert_scale_compressionJ\x04\x08\x17\x10\x18J\x04\x08\x19\x10\x1aJ\x04\x08\x1a\x10\x1bR\x0cjoint_tuningR\x11\x63ollective_tuningR\x16\x63ollective_ladder_json\"\x82\x04\n\x12RebuildSpeculation\x12\x14\n\x0c\x64raft_tokens\x18\x01 \x01(\r\x12\x10\n\x08\x61\x64\x61ptive\x18\x02 \x01(\x08\x12\x17\n\x0fproposal_source\x18\x03 \x01(\t\x12\x16\n\x0ehistory_drafts\x18\x04 \x01(\x08\x12\x16\n\x0etoken_capacity\x18\x05 \x01(\x04\x12\x1b\n\x13packed_verification\x18\x06 \x01(\x08\x12\x1e\n\x16\x64raft_prefix_selection\x18\x07 \x01(\t\x12$\n\x17\x64raft_head_quantization\x18\x08 \x01(\tH\x00\x88\x01\x01\x12%\n\x18markov_head_quantization\x18\t \x01(\tH\x01\x88\x01\x01\x12\x19\n\x0cgraph_budget\x18\n \x01(\x04H\x02\x88\x01\x01\x12$\n\x1cvocabulary_parallel_sampling\x18\x0b \x01(\x08\x12\x0e\n\x06method\x18\x0c \x01(\t\x12\x10\n\x08mtp_only\x18\r \x01(\x08\x12$\n\x17\x64raft_body_quantization\x18\x0e \x01(\tH\x03\x88\x01\x01:\x02\x18\x01\x42\x1a\n\x18_draft_head_quantizationB\x1b\n\x19_markov_head_quantizationB\x0f\n\r_graph_budgetB\x1a\n\x18_draft_body_quantization\"e\n\x0eRebuildWeights\x12\x0f\n\x07version\x18\x01 \x01(\r\x12-\n\x07tensors\x18\x02 \x03(\x0b\x32\x1c.flare.runtime.RebuildTensor\x12\x13\n\x0bunavailable\x18\x03 \x03(\t\"\xa2\x01\n\rRebuildTensor\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05\x64type\x18\x02 \x01(\t\x12\x15\n\relement_bytes\x18\x03 \x01(\r\x12\r\n\x05shape\x18\x04 \x03(\x04\x12\x0e\n\x06stride\x18\x05 \x03(\x04\x12\x13\n\x0blayout_type\x18\x06 \x01(\t\x12)\n\x07storage\x18\x07 \x01(\x0b\x32\x18.flare.runtime.Reference\"\xcb\x06\n\x0fServingContract\x12\x10\n\x08model_id\x18\x01 \x01(\t\x12\x10\n\x08identity\x18\x02 \x01(\t\x12\x34\n\x0emodel_contract\x18\x03 \x01(\x0b\x32\x1c.flare.runtime.ModelContract\x12\x1b\n\x13max_sequence_tokens\x18\x04 \x01(\x04\x12\x1a\n\x12prefill_chunk_size\x18\x05 \x01(\x04\x12\r\n\x05pages\x18\x06 \x01(\x04\x12\x12\n\nstate_rows\x18\x07 \x01(\x04\x12\x11\n\tsnapshots\x18\x08 \x01(\x04\x12\x13\n\x0bpage_tokens\x18\t \x01(\x04\x12\x1a\n\x12speculative_widths\x18\x0b \x03(\x04\x12$\n\x17speculative_fixed_width\x18\x0c \x01(\x04H\x00\x88\x01\x01\x12\x16\n\x0ehistory_drafts\x18\r \x01(\x08\x12#\n\x1bspeculative_proposal_source\x18\x0e \x01(\t\x12\x1b\n\x0emax_new_tokens\x18\x0f \x01(\x04H\x01\x88\x01\x01\x12\x17\n\nmax_active\x18\x10 \x01(\x04H\x02\x88\x01\x01\x12\x14\n\x0cserved_names\x18\x11 \x03(\t\x12\x1a\n\rreserve_bytes\x18\x12 \x01(\x04H\x03\x88\x01\x01\x12\x1b\n\x0equeue_capacity\x18\x13 \x01(\x04H\x04\x88\x01\x01\x12\x1d\n\x10\x66rontend_workers\x18\x14 \x01(\x04H\x05\x88\x01\x01\x12\x1b\n\x0emax_body_bytes\x18\x15 \x01(\x04H\x06\x88\x01\x01\x12\x14\n\x0c\x63ontext_hint\x18\x16 \x01(\t\x12\x15\n\rcapacity_hint\x18\x17 \x01(\t\x12\"\n\x1aspeculative_token_capacity\x18\x18 \x01(\x04\x12 \n\x13\x64\x65\x63ode_weight_bytes\x18\x19 \x01(\x04H\x07\x88\x01\x01\x42\x1a\n\x18_speculative_fixed_widthB\x11\n\x0f_max_new_tokensB\r\n\x0b_max_activeB\x10\n\x0e_reserve_bytesB\x11\n\x0f_queue_capacityB\x13\n\x11_frontend_workersB\x11\n\x0f_max_body_bytesB\x16\n\x14_decode_weight_bytesJ\x04\x08\n\x10\x0b\"\xc2\x02\n\rModelContract\x12\x0f\n\x07version\x18\x01 \x01(\r\x12\x12\n\nvocabulary\x18\x02 \x01(\x04\x12\x18\n\x10input_vocabulary\x18\x03 \x01(\x04\x12-\n\x06vision\x18\x04 \x01(\x0b\x32\x1d.flare.runtime.VisionCapacity\x12+\n\x05\x63\x61\x63he\x18\x05 \x01(\x0b\x32\x1c.flare.runtime.CacheContract\x12,\n\x06graphs\x18\x06 \x03(\x0b\x32\x1c.flare.runtime.GraphContract\x12\x31\n\x08\x66rontend\x18\x07 \x01(\x0b\x32\x1f.flare.runtime.FrontendContract\x12\x35\n\x0f\x63ore_parameters\x18\x08 \x03(\x0b\x32\x1c.flare.runtime.CoreParameter\"}\n\rCoreParameter\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1a\n\rdefault_value\x18\x02 \x01(\x02H\x00\x88\x01\x01\x12\x30\n\x05range\x18\x03 \x01(\x0b\x32!.flare.runtime.CoreParameterRangeB\x10\n\x0e_default_value\"H\n\x12\x43oreParameterRange\x12\x10\n\x03min\x18\x01 \x01(\x02H\x00\x88\x01\x01\x12\x10\n\x03max\x18\x02 \x01(\x02H\x01\x88\x01\x01\x42\x06\n\x04_minB\x06\n\x04_max\"\x90\x01\n\x0eVisionCapacity\x12\x15\n\rfeature_slots\x18\x05 \x01(\x04\x12\x1c\n\x14\x66\x65\x61tures_per_request\x18\x01 \x01(\x04\x12\x12\n\nmax_images\x18\x02 \x01(\x04\x12\x1b\n\x13patches_per_feature\x18\x03 \x01(\x04\x12\x18\n\x10patch_capacities\x18\x04 \x03(\x04\"\xb8\x01\n\rCacheContract\x12\x13\n\x0bpage_tokens\x18\x01 \x01(\x04\x12-\n\x07regions\x18\x02 \x03(\x0b\x32\x1c.flare.runtime.HistoryRegion\x12\x31\n\x0bpage_tables\x18\x03 \x03(\x0b\x32\x1c.flare.runtime.PageTableView\x12\x30\n\x0c\x63odec_layout\x18\x04 \x01(\x0b\x32\x1a.flare.runtime.CodecLayout\"r\n\x0b\x43odecLayout\x12\x10\n\x08revision\x18\x01 \x01(\r\x12)\n\x06\x66ields\x18\x02 \x03(\x0b\x32\x19.flare.runtime.CodecField\x12\x17\n\ngpu_module\x18\x03 \x01(\tH\x00\x88\x01\x01\x42\r\n\x0b_gpu_module\"N\n\nCodecField\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x0e\n\x06offset\x18\x02 \x01(\x04\x12\x0e\n\x06length\x18\x03 \x01(\x04\x12\x10\n\x08\x65ncoding\x18\x04 \x01(\r\"\x96\x01\n\rHistoryRegion\x12(\n\x04kind\x18\x01 \x01(\x0e\x32\x1a.flare.runtime.HistoryKind\x12)\n\x07storage\x18\x02 \x01(\x0b\x32\x18.flare.runtime.StateView\x12\x19\n\x11tokens_per_record\x18\x03 \x01(\x04\x12\x15\n\rwindow_tokens\x18\x04 \x01(\x04\"4\n\rPageTableView\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x13\n\x0bpage_offset\x18\x02 \x01(\x04\"\xc4\x01\n\x0cValueBinding\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12*\n\x06source\x18\x02 \x01(\x0e\x32\x1a.flare.runtime.ValueSource\x12.\n\x08indexing\x18\x03 \x01(\x0e\x32\x1c.flare.runtime.InputIndexing\x12\x14\n\x0cvalue_offset\x18\x04 \x01(\x12\x12\x0f\n\x07padding\x18\x05 \x01(\x12\x12\x0e\n\x06tensor\x18\x06 \x01(\t\x12\x11\n\tparameter\x18\x07 \x01(\t\"K\n\tStateView\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x0e\n\x06offset\x18\x02 \x01(\x04\x12\x0e\n\x06stride\x18\x03 \x01(\x04\x12\x0e\n\x06nbytes\x18\x04 \x01(\x04\"e\n\x0bStateAccess\x12&\n\x04view\x18\x01 \x01(\x0b\x32\x18.flare.runtime.StateView\x12.\n\x06\x61\x63\x63\x65ss\x18\x02 \x01(\x0e\x32\x1e.flare.runtime.StateAccessKind\"O\n\x10\x43ompletionCursor\x12\'\n\x05state\x18\x01 \x01(\x0b\x32\x18.flare.runtime.StateView\x12\x12\n\nlag_tokens\x18\x02 \x01(\x04\"4\n\x0cTunedBinding\x12\x0e\n\x06\x62uffer\x18\x01 \x01(\t\x12\x14\n\x0ctuning_graph\x18\x02 \x01(\t\"\xfa\x02\n\rGraphContract\x12\r\n\x05graph\x18\x01 \x01(\t\x12+\n\x06inputs\x18\x02 \x03(\x0b\x32\x1b.flare.runtime.ValueBinding\x12)\n\x05state\x18\x03 \x03(\x0b\x32\x1a.flare.runtime.StateAccess\x12\x1e\n\x16state_rows_per_request\x18\x04 \x01(\x04\x12\x35\n\x0c\x64raft_cursor\x18\x05 \x01(\x0b\x32\x1f.flare.runtime.CompletionCursor\x12\x18\n\x10\x65mbedding_tables\x18\x06 \x03(\r\x12/\n\rpending_token\x18\x07 \x01(\x0b\x32\x18.flare.runtime.StateView\x12+\n\x04kind\x18\x08 \x01(\x0e\x32\x1d.flare.runtime.GraphOperation\x12\x33\n\x0etuned_bindings\x18\t \x03(\x0b\x32\x1b.flare.runtime.TunedBinding\"\x88\x01\n\nToolParser\x12+\n\x04kind\x18\x01 \x01(\x0e\x32\x1d.flare.runtime.ToolParserKind\x12\x19\n\x11wrapping_newlines\x18\x02 \x01(\r\x12\x15\n\rtag_separator\x18\x03 \x01(\t\x12\x0c\n\x04open\x18\x04 \x01(\t\x12\r\n\x05\x63lose\x18\x05 \x01(\t\"\x95\x01\n\x0fReasoningParser\x12\x30\n\x04kind\x18\x01 \x01(\x0e\x32\".flare.runtime.ReasoningParserKind\x12\x0c\n\x04open\x18\x02 \x01(\t\x12\r\n\x05\x63lose\x18\x03 \x01(\t\x12\x19\n\x11wrapping_newlines\x18\x04 \x01(\r\x12\x18\n\x10terminal_markers\x18\x05 \x03(\t\"\xca\x01\n\x0ePrefixBoundary\x12\r\n\x05roles\x18\x01 \x03(\t\x12\x18\n\x0b\x61ppend_role\x18\x02 \x01(\tH\x00\x88\x01\x01\x12\x1e\n\x16\x63ontinue_final_message\x18\x03 \x01(\x08\x12\x18\n\x10minimum_messages\x18\x04 \x01(\x04\x12\x16\n\x0erequired_start\x18\x05 \x01(\t\x12\x14\n\x0crequired_end\x18\x06 \x01(\t\x12\x17\n\x0frequired_marker\x18\x07 \x01(\tB\x0e\n\x0c_append_role\"y\n\tImageSpan\x12\x13\n\x0bstart_token\x18\x01 \x01(\r\x12\x11\n\tend_token\x18\x02 \x01(\r\x12\x12\n\nmax_tokens\x18\x03 \x01(\x04\x12\x17\n\x0finterior_tokens\x18\x04 \x03(\r\x12\x17\n\x0funscoped_tokens\x18\x05 \x03(\r\"Q\n\x10ImageTokenLayout\x12\x15\n\rfeature_token\x18\x01 \x01(\r\x12&\n\x04span\x18\x02 \x01(\x0b\x32\x18.flare.runtime.ImageSpan\"\xf2\x03\n\x10\x46rontendContract\x12(\n\x05tools\x18\x01 \x01(\x0b\x32\x19.flare.runtime.ToolParser\x12\x31\n\treasoning\x18\x02 \x01(\x0b\x32\x1e.flare.runtime.ReasoningParser\x12\x43\n\x11image_preparation\x18\x03 \x01(\x0e\x32#.flare.runtime.ImagePreparationKindH\x00\x88\x01\x01\x12\x39\n\x0cimage_layout\x18\x04 \x01(\x0e\x32\x1e.flare.runtime.ImageLayoutKindH\x01\x88\x01\x01\x12\x17\n\x0frejected_tokens\x18\x05 \x03(\r\x12\x1b\n\x13position_dimensions\x18\x06 \x01(\r\x12\x18\n\x10\x61ssistant_marker\x18\x07 \x01(\t\x12\x1b\n\x13message_end_markers\x18\x08 \x03(\t\x12\x36\n\x0fprefix_boundary\x18\t \x01(\x0b\x32\x1d.flare.runtime.PrefixBoundary\x12\x35\n\x0cimage_tokens\x18\n \x01(\x0b\x32\x1f.flare.runtime.ImageTokenLayoutB\x14\n\x12_image_preparationB\x0f\n\r_image_layout\"1\n\x07\x43luster\x12\r\n\x05world\x18\x01 \x01(\r\x12\x11\n\texport_id\x18\x03 \x01(\tJ\x04\x08\x02\x10\x03\"\x8c\x03\n\x19\x44\x65\x66\x61ultSamplingParameters\x12\x11\n\x04seed\x18\x01 \x01(\x04H\x00\x88\x01\x01\x12\x18\n\x0btemperature\x18\x02 \x01(\x02H\x01\x88\x01\x01\x12\x12\n\x05top_k\x18\x03 \x01(\x05H\x02\x88\x01\x01\x12\x12\n\x05top_p\x18\x04 \x01(\x02H\x03\x88\x01\x01\x12\x12\n\x05min_p\x18\x05 \x01(\x02H\x04\x88\x01\x01\x12\x1f\n\x12repetition_penalty\x18\x06 \x01(\x02H\x05\x88\x01\x01\x12\x1d\n\x10presence_penalty\x18\x07 \x01(\x02H\x06\x88\x01\x01\x12\x1e\n\x11\x66requency_penalty\x18\x08 \x01(\x02H\x07\x88\x01\x01\x12-\n\x06ranges\x18\t \x01(\x0b\x32\x1d.flare.runtime.SamplingRangesB\x07\n\x05_seedB\x0e\n\x0c_temperatureB\x08\n\x06_top_kB\x08\n\x06_top_pB\x08\n\x06_min_pB\x15\n\x13_repetition_penaltyB\x13\n\x11_presence_penaltyB\x14\n\x12_frequency_penalty\"H\n\x12SamplingFloatRange\x12\x10\n\x03min\x18\x01 \x01(\x02H\x00\x88\x01\x01\x12\x10\n\x03max\x18\x02 \x01(\x02H\x01\x88\x01\x01\x42\x06\n\x04_minB\x06\n\x04_max\"F\n\x10SamplingIntRange\x12\x10\n\x03min\x18\x01 \x01(\x05H\x00\x88\x01\x01\x12\x10\n\x03max\x18\x02 \x01(\x05H\x01\x88\x01\x01\x42\x06\n\x04_minB\x06\n\x04_max\"\x96\x03\n\x0eSamplingRanges\x12\x36\n\x0btemperature\x18\x01 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12.\n\x05top_k\x18\x02 \x01(\x0b\x32\x1f.flare.runtime.SamplingIntRange\x12\x30\n\x05top_p\x18\x03 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12\x30\n\x05min_p\x18\x04 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12=\n\x12repetition_penalty\x18\x05 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12;\n\x10presence_penalty\x18\x06 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\x12<\n\x11\x66requency_penalty\x18\x07 \x01(\x0b\x32!.flare.runtime.SamplingFloatRange\"\xc5\x02\n\x10\x46rontendSettings\x12\x33\n\ttokenizer\x18\x01 \x01(\x0b\x32 .flare.runtime.TokenizerSettings\x12+\n\x05image\x18\x02 \x01(\x0b\x32\x1c.flare.runtime.ImageSettings\x12\x15\n\reos_token_ids\x18\x03 \x03(\r\x12:\n\x11template_encoding\x18\x04 \x01(\x0e\x32\x1f.flare.runtime.TemplateEncoding\x12\x34\n\x0eprompt_encoder\x18\x05 \x01(\x0e\x32\x1c.flare.runtime.PromptEncoder\x12\'\n\x1aimage_placeholder_token_id\x18\x06 \x01(\rH\x00\x88\x01\x01\x42\x1d\n\x1b_image_placeholder_token_id\"\xdc\x02\n\x11TokenizerSettings\x12\x16\n\tbos_token\x18\x01 \x01(\tH\x00\x88\x01\x01\x12\x16\n\teos_token\x18\x02 \x01(\tH\x01\x88\x01\x01\x12\x16\n\tunk_token\x18\x03 \x01(\tH\x02\x88\x01\x01\x12\x16\n\tsep_token\x18\x04 \x01(\tH\x03\x88\x01\x01\x12\x16\n\tpad_token\x18\x05 \x01(\tH\x04\x88\x01\x01\x12\x16\n\tcls_token\x18\x06 \x01(\tH\x05\x88\x01\x01\x12\x17\n\nmask_token\x18\x07 \x01(\tH\x06\x88\x01\x01\x12;\n\x19\x61\x64\x64itional_special_tokens\x18\x08 \x01(\x0b\x32\x18.flare.runtime.TokenListB\x0c\n\n_bos_tokenB\x0c\n\n_eos_tokenB\x0c\n\n_unk_tokenB\x0c\n\n_sep_tokenB\x0c\n\n_pad_tokenB\x0c\n\n_cls_tokenB\r\n\x0b_mask_token\"\x1b\n\tTokenList\x12\x0e\n\x06values\x18\x01 \x03(\t\"\xfc\x03\n\rImageSettings\x12\x30\n\x04qwen\x18\x01 \x01(\x0b\x32 .flare.runtime.QwenImageSettingsH\x00\x12\x30\n\x04mimo\x18\x02 \x01(\x0b\x32 .flare.runtime.MimoImageSettingsH\x00\x12)\n\tdeepseek4\x18\x03 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12\'\n\x07moonvit\x18\x04 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12$\n\x04step\x18\x05 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12%\n\x05radio\x18\x06 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12J\n\x12\x64\x65\x65pseek_row_major\x18\x07 \x01(\x0b\x32,.flare.runtime.DeepseekRowMajorImageSettingsH\x00\x12#\n\x03glm\x18\x08 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12=\n\x0bpatch_merge\x18\t \x01(\x0b\x32&.flare.runtime.PatchMergeImageSettingsH\x00\x12+\n\x0bpadded_grid\x18\n \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x42\t\n\x07profile\"\xb9\x01\n\x17PatchMergeImageSettings\x12\x12\n\npatch_size\x18\x01 \x01(\r\x12\x12\n\nmin_pixels\x18\x02 \x01(\x04\x12\x12\n\nmax_pixels\x18\x03 \x01(\x04\x12\x12\n\nimage_mean\x18\x04 \x03(\x02\x12\x11\n\timage_std\x18\x05 \x03(\x02\x12\x13\n\x0bimage_token\x18\x06 \x01(\t\x12\x13\n\x0bstart_token\x18\x07 \x01(\t\x12\x11\n\tend_token\x18\x08 \x01(\t\"\x87\x01\n\x1d\x44\x65\x65pseekRowMajorImageSettings\x12\x12\n\nmin_pixels\x18\x01 \x01(\x04\x12\x12\n\nmax_tokens\x18\x02 \x01(\x04\x12#\n\x16max_width_height_ratio\x18\x03 \x01(\x04H\x00\x88\x01\x01\x42\x19\n\x17_max_width_height_ratio\"\x82\x01\n\x11QwenImageSettings\x12\x12\n\nmin_pixels\x18\x01 \x01(\x04\x12\x12\n\nmax_pixels\x18\x02 \x01(\x04\x12\x15\n\rposition_side\x18\x03 \x01(\r\x12\x16\n\x0eimage_token_id\x18\x04 \x01(\r\x12\x16\n\x0evideo_token_id\x18\x05 \x01(\r\"b\n\x11MimoImageSettings\x12\x12\n\nmin_pixels\x18\x01 \x01(\x04\x12\x12\n\nmax_pixels\x18\x02 \x01(\x04\x12\x12\n\nimage_mean\x18\x03 \x03(\x02\x12\x11\n\timage_std\x18\x04 \x03(\x02\"|\n\x06\x45ngram\x12\x11\n\ttoken_map\x18\x01 \x03(\r\x12\x14\n\x0cpad_token_id\x18\x02 \x01(\r\x12\x1d\n\x15\x63ompressed_vocabulary\x18\x03 \x01(\r\x12*\n\x06tables\x18\x04 \x03(\x0b\x32\x1a.flare.runtime.EngramTable\"\xa3\x04\n\x0b\x45ngramTable\x12\r\n\x05layer\x18\x01 \x01(\r\x12\x0c\n\x04rows\x18\x02 \x01(\x04\x12\x17\n\x0f\x65mbedding_width\x18\x03 \x01(\r\x12\x13\n\x0bscale_block\x18\x04 \x01(\r\x12$\n\x07weights\x18\x05 \x01(\x0b\x32\x13.flare.runtime.Span\x12#\n\x06scales\x18\x06 \x01(\x0b\x32\x13.flare.runtime.Span\x12\'\n\x04hash\x18\x07 \x01(\x0b\x32\x19.flare.runtime.EngramHash\x12\x15\n\rweight_buffer\x18\x08 \x01(\t\x12\x14\n\x0cscale_buffer\x18\t \x01(\t\x12\x13\n\x0bhash_buffer\x18\n \x01(\t\x12\x13\n\x0bready_event\x18\x0b \x01(\t\x12\x35\n\x08\x65ncoding\x18\x0c \x01(\x0e\x32#.flare.runtime.EngramTable.Encoding\x12\x16\n\x0erequest_buffer\x18\r \x01(\t\x12\x14\n\x0cglobal_scale\x18\x0e \x01(\x02\x12/\n\x06shards\x18\x0f \x03(\x0b\x32\x1f.flare.runtime.EngramTableShard\x12\x17\n\x0fprefetch_buffer\x18\x10 \x01(\t\"O\n\x08\x45ncoding\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x11\n\rFP8_E4M3_E8M0\x10\x01\x12\x15\n\x11NVFP4_E4M3_GLOBAL\x10\x02\x12\x08\n\x04\x42\x46\x31\x36\x10\x03\"\x8c\x01\n\x10\x45ngramTableShard\x12\x0c\n\x04rank\x18\x01 \x01(\r\x12\x11\n\tfirst_row\x18\x02 \x01(\x04\x12\x0c\n\x04rows\x18\x03 \x01(\x04\x12$\n\x07weights\x18\x04 \x01(\x0b\x32\x13.flare.runtime.Span\x12#\n\x06scales\x18\x05 \x01(\x0b\x32\x13.flare.runtime.Span\"\xd1\x01\n\nEngramHash\x12\x30\n\x06method\x18\x01 \x01(\x0e\x32 .flare.runtime.EngramHash.Method\x12\x0e\n\x06orders\x18\x02 \x03(\r\x12\x13\n\x0bmultipliers\x18\x03 \x03(\x04\x12\x0e\n\x06primes\x18\x04 \x03(\x04\x12\x0f\n\x07offsets\x18\x05 \x03(\x04\"K\n\x06Method\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nXOR_MODULO\x10\x01\x12\x12\n\x0e\x45OS_XOR_MODULO\x10\x02\x12\x0c\n\x08IDENTITY\x10\x03\"K\n\x05\x41sset\x12\x0c\n\x04name\x18\x01 \x01(\t\x12$\n\x07payload\x18\x02 \x01(\x0b\x32\x13.flare.runtime.Span\x12\x0e\n\x06sha256\x18\x03 \x01(\t\"\xd3\x04\n\x0b\x42undleIndex\x12\x14\n\x0c\x61rchitecture\x18\x01 \x03(\x05\x12.\n\x0b\x61llocations\x18\x02 \x03(\x0b\x32\x19.flare.runtime.Allocation\x12&\n\x07modules\x18\x03 \x03(\x0b\x32\x15.flare.runtime.Module\x12*\n\tfunctions\x18\x04 \x03(\x0b\x32\x17.flare.runtime.Function\x12)\n\x06graphs\x18\x05 \x03(\x0b\x32\x19.flare.runtime.GraphIndex\x12\x30\n\x0creservations\x18\x06 \x03(\x0b\x32\x1a.flare.runtime.Reservation\x12+\n\texecution\x18\x07 \x01(\x0b\x32\x18.flare.runtime.Execution\x12\'\n\x07\x63ontext\x18\x08 \x01(\x0b\x32\x16.flare.runtime.Context\x12<\n\tresources\x18\t \x03(\x0b\x32).flare.runtime.BundleIndex.ResourcesEntry\x12\x0e\n\x06\x65vents\x18\n \x03(\t\x12*\n\x04roce\x18\x0b \x01(\x0b\x32\x1c.flare.runtime.RoceTransport\x12\x36\n\x0frebuild_weights\x18\x0c \x01(\x0b\x32\x1d.flare.runtime.RebuildWeights\x1a\x45\n\x0eResourcesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\"\n\x05value\x18\x02 \x01(\x0b\x32\x13.flare.runtime.Span:\x02\x38\x01\"\xf8\x01\n\rRoceTransport\x12\x11\n\tproxy_abi\x18\x01 \x01(\r\x12\r\n\x05world\x18\x02 \x01(\r\x12\x0c\n\x04rank\x18\x03 \x01(\r\x12\x16\n\x0eregion_address\x18\x04 \x01(\x04\x12\x14\n\x0cregion_bytes\x18\x05 \x01(\x04\x12\x18\n\x10\x63ounters_address\x18\x06 \x01(\x04\x12\x16\n\x0e\x63ounters_bytes\x18\x07 \x01(\x04\x12\x12\n\nslot_bytes\x18\x08 \x01(\x04\x12\x12\n\npipe_bytes\x18\t \x01(\x04\x12\x13\n\x0b\x63trl_offset\x18\n \x01(\x04\x12\x14\n\x0cvarlen_bytes\x18\x10 \x01(\x04J\x04\x08\x0b\x10\x10\"\xa9\x01\n\nGraphIndex\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05\x66lags\x18\x02 \x01(\x04\x12\x10\n\x08resource\x18\x03 \x01(\t\x12\x12\n\nnode_count\x18\x04 \x01(\x04\x12\x12\n\nedge_count\x18\x05 \x01(\x04\x12\x11\n\tfunctions\x18\x06 \x03(\x04\x12\x17\n\x0fmin_compute_sms\x18\x07 \x01(\r\x12\x18\n\x10max_cluster_size\x18\x08 \x01(\r\"M\n\nPeerMemory\x12\r\n\x05owner\x18\x01 \x01(\r\x12\x0f\n\x07\x61\x64\x64ress\x18\x02 \x01(\x04\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04\x12\x0f\n\x07readers\x18\x04 \x03(\r\"M\n\x07\x43ontext\x12\r\n\x05\x66lags\x18\x01 \x01(\r\x12\r\n\x05\x63\x61\x63he\x18\x02 \x01(\x05\x12$\n\x06limits\x18\x03 \x03(\x0b\x32\x14.flare.runtime.Limit\"\"\n\x05Limit\x12\n\n\x02id\x18\x01 \x01(\x04\x12\r\n\x05value\x18\x02 \x01(\x04\".\n\x0bReservation\x12\x0f\n\x07\x61\x64\x64ress\x18\x01 \x01(\x04\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\"8\n\x04Span\x12\x0e\n\x06offset\x18\x01 \x01(\x04\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\x12\x10\n\x08\x66ilename\x18\x03 \x01(\t\"\xa2\x02\n\nAllocation\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\x12\x11\n\talignment\x18\x03 \x01(\x04\x12\x11\n\x04\x66ile\x18\x04 \x01(\tH\x00\x88\x01\x01\x12\'\n\ndata_spans\x18\x05 \x03(\x0b\x32\x13.flare.runtime.Span\x12.\n\x0brelocations\x18\x06 \x03(\x0b\x32\x19.flare.runtime.Relocation\x12\x14\n\x07\x61\x64\x64ress\x18\x07 \x01(\x04H\x01\x88\x01\x01\x12%\n\x06memory\x18\x08 \x01(\x0e\x32\x15.flare.runtime.Memory\x12%\n\x06sizing\x18\t \x01(\x0b\x32\x15.flare.runtime.SizingB\x07\n\x05_fileB\n\n\x08_address\"X\n\x06Sizing\x12)\n\x08\x63\x61pacity\x18\x01 \x01(\x0e\x32\x17.flare.runtime.Capacity\x12\x12\n\nunit_bytes\x18\x02 \x01(\x04\x12\x0f\n\x07maximum\x18\x03 \x01(\x04\"L\n\x06Module\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04\x66ile\x18\x02 \x01(\t\x12&\n\x07globals\x18\x03 \x03(\x0b\x32\x15.flare.runtime.Global\"f\n\x06Global\x12\x0e\n\x06symbol\x18\x01 \x01(\t\x12\x0c\n\x04\x66ile\x18\x02 \x01(\t\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04\x12.\n\x0brelocations\x18\x04 \x03(\x0b\x32\x19.flare.runtime.Relocation\"y\n\x08\x46unction\x12\x0e\n\x06module\x18\x01 \x01(\t\x12\x0e\n\x06symbol\x18\x02 \x01(\t\x12\x17\n\x0fparameter_sizes\x18\x03 \x03(\x04\x12\x34\n\nattributes\x18\x04 \x03(\x0b\x32 .flare.runtime.FunctionAttribute\".\n\x11\x46unctionAttribute\x12\n\n\x02id\x18\x01 \x01(\x05\x12\r\n\x05value\x18\x02 \x01(\x05\"/\n\tReference\x12\x12\n\nallocation\x18\x01 \x01(\t\x12\x0e\n\x06offset\x18\x02 \x01(\x04\"s\n\nRelocation\x12\x0e\n\x06offset\x18\x01 \x01(\x04\x12(\n\x06target\x18\x02 \x01(\x0b\x32\x18.flare.runtime.Reference\x12+\n\x04kind\x18\x03 \x01(\x0e\x32\x1d.flare.runtime.RelocationKind\"D\n\x04\x42lob\x12\x0c\n\x04\x64\x61ta\x18\x01 \x01(\x0c\x12.\n\x0brelocations\x18\x02 \x03(\x0b\x32\x19.flare.runtime.Relocation\";\n\tAttribute\x12\n\n\x02id\x18\x01 \x01(\x05\x12\"\n\x05value\x18\x02 \x01(\x0b\x32\x13.flare.runtime.Blob\"\x9d\x01\n\x06Kernel\x12\x10\n\x08\x66unction\x18\x01 \x01(\x04\x12\x0c\n\x04grid\x18\x02 \x03(\r\x12\r\n\x05\x62lock\x18\x03 \x03(\r\x12\x0e\n\x06shared\x18\x04 \x01(\r\x12&\n\targuments\x18\x05 \x03(\x0b\x32\x13.flare.runtime.Blob\x12,\n\nattributes\x18\x06 \x03(\x0b\x32\x18.flare.runtime.Attribute\"\x8a\x01\n\x06Memset\x12-\n\x0b\x64\x65stination\x18\x01 \x01(\x0b\x32\x18.flare.runtime.Reference\x12\r\n\x05pitch\x18\x02 \x01(\x04\x12\r\n\x05value\x18\x03 \x01(\r\x12\x14\n\x0c\x65lement_size\x18\x04 \x01(\r\x12\r\n\x05width\x18\x05 \x01(\x04\x12\x0e\n\x06height\x18\x06 \x01(\x04\"o\n\x04\x43opy\x12(\n\x06source\x18\x01 \x01(\x0b\x32\x18.flare.runtime.Reference\x12-\n\x0b\x64\x65stination\x18\x02 \x01(\x0b\x32\x18.flare.runtime.Reference\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04\"\x07\n\x05\x45mpty\"\x1a\n\tEventWait\x12\r\n\x05\x65vent\x18\x01 \x01(\t\"\xe1\x01\n\x04Node\x12\'\n\x06kernel\x18\x01 \x01(\x0b\x32\x15.flare.runtime.KernelH\x00\x12\'\n\x06memset\x18\x02 \x01(\x0b\x32\x15.flare.runtime.MemsetH\x00\x12#\n\x04\x63opy\x18\x03 \x01(\x0b\x32\x13.flare.runtime.CopyH\x00\x12%\n\x05\x65mpty\x18\x04 \x01(\x0b\x32\x14.flare.runtime.EmptyH\x00\x12.\n\nevent_wait\x18\x05 \x01(\x0b\x32\x18.flare.runtime.EventWaitH\x00\x42\x0b\n\toperation\"9\n\x04\x45\x64ge\x12\x0e\n\x06source\x18\x01 \x01(\x04\x12\x13\n\x0b\x64\x65stination\x18\x02 \x01(\x04\x12\x0c\n\x04\x64\x61ta\x18\x03 \x01(\x0c\"\xf0\x02\n\tExecution\x12\x13\n\x0b\x61\x62i_version\x18\x01 \x01(\r\x12\x12\n\nmax_active\x18\x02 \x01(\x04\x12\x19\n\x11input_frame_bytes\x18\x03 \x01(\x04\x12&\n\x07\x62uffers\x18\x04 \x03(\x0b\x32\x15.flare.runtime.Buffer\x12-\n\x06graphs\x18\x05 \x03(\x0b\x32\x1d.flare.runtime.ExecutionGraph\x12\x31\n\rtuning_graphs\x18\x06 \x03(\x0b\x32\x1a.flare.runtime.TuningGraph\x12!\n\x19\x63ompletion_token_capacity\x18\x07 \x01(\r\x12;\n\x12persistent_workers\x18\x08 \x03(\x0b\x32\x1f.flare.runtime.PersistentWorker\x12\x35\n\x0f\x61sync_transfers\x18\t \x03(\x0b\x32\x1c.flare.runtime.AsyncTransfer\"\xb1\x02\n\rAsyncTransfer\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x0b\x64\x65vice_pool\x18\x02 \x01(\t\x12)\n\x07\x63ontrol\x18\x03 \x01(\x0b\x32\x18.flare.runtime.Reference\x12\x15\n\rcontrol_bytes\x18\x04 \x01(\x04\x12\x34\n\x12\x64\x65vice_completions\x18\x05 \x01(\x0b\x32\x18.flare.runtime.Reference\x12\x18\n\x10\x63ompletion_slots\x18\x06 \x01(\r\x12\x15\n\rring_capacity\x18\x07 \x01(\r\x12\x1b\n\x13max_host_pool_bytes\x18\x08 \x01(\x04\x12\x11\n\talignment\x18\t \x01(\r\x12$\n\x07\x65xtents\x18\n \x03(\x0b\x32\x13.flare.runtime.Span\"\xa9\x01\n\x10PersistentWorker\x12\x17\n\x0fworker_sm_count\x18\x01 \x01(\r\x12\r\n\x05graph\x18\x02 \x01(\t\x12+\n\tstop_flag\x18\x03 \x01(\x0b\x32\x18.flare.runtime.Reference\x12)\n\x07metrics\x18\x04 \x01(\x0b\x32\x18.flare.runtime.Reference\x12\x15\n\rmetrics_count\x18\x05 \x01(\r\"C\n\x0bTuningGraph\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07outputs\x18\x02 \x03(\t\x12\x15\n\rstatus_buffer\x18\x03 \x01(\t\"\x82\x01\n\x06\x42uffer\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06nbytes\x18\x02 \x01(\x04\x12\r\n\x05\x64type\x18\x03 \x01(\t\x12\r\n\x05shape\x18\x04 \x03(\x04\x12\x0f\n\x07strides\x18\x05 \x03(\x04\x12+\n\treference\x18\x06 \x01(\x0b\x32\x18.flare.runtime.Reference\"\x95\x04\n\x0e\x45xecutionGraph\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04kind\x18\x02 \x01(\t\x12\x15\n\rsampling_mode\x18\x03 \x01(\t\x12\x16\n\x0e\x62\x61tch_capacity\x18\x04 \x01(\x04\x12\x16\n\x0etoken_capacity\x18\x05 \x01(\x04\x12\x33\n\x0einput_bindings\x18\x06 \x03(\x0b\x32\x1b.flare.runtime.InputBinding\x12\x19\n\x0c\x64raft_tokens\x18\x07 \x01(\rH\x00\x88\x01\x01\x12\x1a\n\rverify_tokens\x18\x08 \x01(\rH\x01\x88\x01\x01\x12\x30\n\x0c\x64raft_source\x18\t \x01(\x0e\x32\x1a.flare.runtime.DraftSource\x12 \n\x13speculation_enabled\x18\n \x01(\x08H\x02\x88\x01\x01\x12\x1d\n\x15\x65stimated_duration_ns\x18\x0b \x01(\x04\x12\x18\n\x10prefill_capacity\x18\x0c \x01(\x04\x12\x1d\n\x15packed_token_capacity\x18\r \x01(\x04\x12\x18\n\x10\x63onfidence_width\x18\x0e \x01(\r\x12\x33\n\x0etuned_bindings\x18\x0f \x03(\x0b\x32\x1b.flare.runtime.TunedBindingB\x0f\n\r_draft_tokensB\x10\n\x0e_verify_tokensB\x16\n\x14_speculation_enabled\"H\n\x0cInputBinding\x12\x13\n\x0b\x62uffer_name\x18\x01 \x01(\t\x12\x13\n\x0bhost_offset\x18\x02 \x01(\x04\x12\x0e\n\x06nbytes\x18\x03 \x01(\x04*\xfa\x01\n\x19PreparationParameterScope\x12+\n\'PREPARATION_PARAMETER_SCOPE_UNSPECIFIED\x10\x00\x12*\n&PREPARATION_PARAMETER_SCOPE_DEPLOYMENT\x10\x01\x12\'\n#PREPARATION_PARAMETER_SCOPE_COMBINE\x10\x02\x12-\n)PREPARATION_PARAMETER_SCOPE_TARGET_WEIGHT\x10\x03\x12,\n(PREPARATION_PARAMETER_SCOPE_DRAFT_WEIGHT\x10\x04*\x8e\x01\n\x0bHistoryKind\x12\x17\n\x13HISTORY_UNSPECIFIED\x10\x00\x12\x13\n\x0fPAGED_KEY_VALUE\x10\x01\x12\x10\n\x0cPAGED_LATENT\x10\x02\x12\x12\n\x0eSLIDING_WINDOW\x10\x03\x12\x13\n\x0fRECURRENT_STATE\x10\x04\x12\x16\n\x12\x43ONTINUATION_STATE\x10\x05*\xc7\x07\n\x0bValueSource\x12\x15\n\x11VALUE_UNSPECIFIED\x10\x00\x12\x0c\n\x08\x43ONSTANT\x10\x01\x12\x10\n\x0cREQUEST_SLOT\x10\x02\x12\x16\n\x12REQUEST_GENERATION\x10\x03\x12\r\n\tLIVE_ROWS\x10\x04\x12\x10\n\x0cQUERY_LENGTH\x10\x05\x12\x12\n\x0eSAMPLE_ENABLED\x10\x06\x12\x10\n\x0cPROMPT_TOKEN\x10\x07\x12\x11\n\rPENDING_TOKEN\x10\x08\x12\x1c\n\x18PROMPT_AND_PENDING_TOKEN\x10\t\x12\x13\n\x0fPROMPT_POSITION\x10\n\x12\x17\n\x13IMAGE_FEATURE_INDEX\x10\x0b\x12\x16\n\x12IMAGE_LEFT_CONTEXT\x10\x0c\x12\x17\n\x13IMAGE_RIGHT_CONTEXT\x10\r\x12\x0e\n\nPAGE_TABLE\x10\x0e\x12\x13\n\x0fLIVE_STATE_ROWS\x10\x0f\x12\x12\n\x0eLIVE_STATE_ROW\x10\x10\x12\x14\n\x10PREFIX_STATE_ROW\x10\x11\x12\x16\n\x12SNAPSHOT_STATE_ROW\x10\x12\x12\x13\n\x0f\x43ONSUMED_TOKENS\x10\x13\x12\x1c\n\x18SNAPSHOT_CONSUMED_TOKENS\x10\x14\x12\x0f\n\x0bPREFILL_ROW\x10\x15\x12\x11\n\rSAMPLING_SEED\x10\x16\x12\x17\n\x13SAMPLING_PARAMETERS\x10\x17\x12\x12\n\x0eSAMPLING_TOP_K\x10\x18\x12\x12\n\x0eMAX_NEW_TOKENS\x10\x19\x12\x11\n\rEOS_TOKEN_IDS\x10\x1a\x12\r\n\tEOS_COUNT\x10\x1b\x12\x14\n\x10PROMPT_HISTOGRAM\x10\x1c\x12\x10\n\x0cGRAMMAR_MASK\x10\x1d\x12\x13\n\x0fGRAMMAR_ENABLED\x10\x1e\x12\x12\n\x0e\x43OPY_TOKEN_IDS\x10\x1f\x12\x14\n\x10\x43OPY_TOKEN_COUNT\x10 \x12\x18\n\x14\x43OPY_CONSUMED_TOKENS\x10!\x12\x13\n\x0f\x43OPY_GENERATION\x10\"\x12\x15\n\x11\x43OPY_GRAMMAR_MASK\x10#\x12\x16\n\x12\x43OPY_GRAMMAR_COUNT\x10$\x12\x10\n\x0cIMAGE_TENSOR\x10%\x12\x16\n\x12IMAGE_FEATURE_SLOT\x10&\x12\x17\n\x13PROMPT_TARGET_TOKEN\x10\'\x12\x1c\n\x18SPECULATIVE_PREFIX_LIMIT\x10(\x12\x1a\n\x16PROMPT_LOOKAHEAD_TOKEN\x10)\x12\x1b\n\x17PROMPT_LOOKAHEAD_LENGTH\x10*\x12\x12\n\x0e\x43ORE_PARAMETER\x10+*|\n\rInputIndexing\x12\x18\n\x14INDEXING_UNSPECIFIED\x10\x00\x12\n\n\x06SCALAR\x10\x01\x12\x12\n\x0eSUBMISSION_ROW\x10\x02\x12\x0f\n\x0bREQUEST_ROW\x10\x03\x12\x10\n\x0cPACKED_TOKEN\x10\x04\x12\x0e\n\nACTIVE_ROW\x10\x05*T\n\x0fStateAccessKind\x12\x1c\n\x18STATE_ACCESS_UNSPECIFIED\x10\x00\x12\x08\n\x04READ\x10\x01\x12\t\n\x05WRITE\x10\x02\x12\x0e\n\nREAD_WRITE\x10\x03*\x8b\x02\n\x0eGraphOperation\x12\x1f\n\x1bGRAPH_OPERATION_UNSPECIFIED\x10\x00\x12\x08\n\x04INIT\x10\x01\x12\x0b\n\x07RESTORE\x10\x02\x12\x0c\n\x08SNAPSHOT\x10\x03\x12\x0b\n\x07PREFILL\x10\x04\x12\n\n\x06\x44\x45\x43ODE\x10\x05\x12\n\n\x06RESUME\x10\x06\x12\n\n\x06VISION\x10\x07\x12\x0f\n\x0bSPECULATIVE\x10\x08\x12\t\n\x05MIXED\x10\t\x12\x12\n\x0eSCORED_PREFILL\x10\x0c\x12\x14\n\x10TERMINAL_PREFILL\x10\x0e\"\x04\x08\n\x10\n\"\x04\x08\x0b\x10\x0b\"\x04\x08\r\x10\r*\x08PROPOSAL*\x0cVERIFICATION*\x12PACKED_SPECULATIVE*\xb2\x01\n\x0eToolParserKind\x12\x1b\n\x17TOOL_PARSER_UNSPECIFIED\x10\x00\x12\x0e\n\nQWEN_CODER\x10\x01\x12\x15\n\x11GLM_ARGUMENT_TAGS\x10\x02\x12\x08\n\x04\x44SML\x10\x03\x12\x08\n\x04XTML\x10\x04\x12\x0f\n\x0bMINIMAX_XML\x10\x05\x12\x0e\n\nGEMMA_CALL\x10\x06\x12\x08\n\x04\x41TEM\x10\x07\x12\x0c\n\x08TML_JSON\x10\x08\x12\x0f\n\x0bTAGGED_JSON\x10\t*\xa6\x01\n\x13ReasoningParserKind\x12 \n\x1cREASONING_PARSER_UNSPECIFIED\x10\x00\x12\x0e\n\nTHINK_TAGS\x10\x01\x12\x0e\n\nXTML_THINK\x10\x02\x12\x0c\n\x08MM_THINK\x10\x03\x12\x13\n\x0f\x43HANNEL_THOUGHT\x10\x04\x12\x15\n\x11RECIPIENT_HEADERS\x10\x05\x12\x13\n\x0f\x43ONTENT_HEADERS\x10\x06*\xf4\x02\n\x14ImagePreparationKind\x12!\n\x1dIMAGE_PREPARATION_UNSPECIFIED\x10\x00\x12\x1a\n\x16QWEN_IMAGE_PREPARATION\x10\x01\x12\x1a\n\x16MIMO_IMAGE_PREPARATION\x10\x02\x12\x1e\n\x1a\x44\x45\x45PSEEK_IMAGE_PREPARATION\x10\x03\x12\x1d\n\x19MOONVIT_IMAGE_PREPARATION\x10\x04\x12\x1a\n\x16STEP_IMAGE_PREPARATION\x10\x05\x12\x1b\n\x17RADIO_IMAGE_PREPARATION\x10\x06\x12(\n$DEEPSEEK_ROW_MAJOR_IMAGE_PREPARATION\x10\x07\x12\x19\n\x15GLM_IMAGE_PREPARATION\x10\x08\x12!\n\x1dPATCH_MERGE_IMAGE_PREPARATION\x10\t\x12!\n\x1dPADDED_GRID_IMAGE_PREPARATION\x10\n*\xb6\x02\n\x0fImageLayoutKind\x12\x1c\n\x18IMAGE_LAYOUT_UNSPECIFIED\x10\x00\x12\x15\n\x11QWEN_IMAGE_LAYOUT\x10\x01\x12\x15\n\x11MIMO_IMAGE_LAYOUT\x10\x02\x12\x19\n\x15\x44\x45\x45PSEEK_IMAGE_LAYOUT\x10\x03\x12\x18\n\x14MOONVIT_IMAGE_LAYOUT\x10\x04\x12\x15\n\x11STEP_IMAGE_LAYOUT\x10\x05\x12\x16\n\x12RADIO_IMAGE_LAYOUT\x10\x06\x12#\n\x1f\x44\x45\x45PSEEK_ROW_MAJOR_IMAGE_LAYOUT\x10\x07\x12\x14\n\x10GLM_IMAGE_LAYOUT\x10\x08\x12\x1a\n\x16\x42RACKETED_IMAGE_LAYOUT\x10\t\x12\x1c\n\x18\x43LASS_TOKEN_IMAGE_LAYOUT\x10\n*P\n\rPromptEncoder\x12\x10\n\x0cPROMPT_JINJA\x10\x00\x12\x0f\n\x0b\x44\x45\x45PSEEK_V4\x10\x01\x12\x10\n\x0c\x44\x45\x45PSEEK_V41\x10\x02\x12\n\n\x06TML_V0\x10\x03*B\n\x10TemplateEncoding\x12\x11\n\rTEMPLATE_TEXT\x10\x00\x12\x1b\n\x17TEMPLATE_TOKEN_SEGMENTS\x10\x01*/\n\x06Memory\x12\n\n\x06\x44\x45VICE\x10\x00\x12\x0f\n\x0bMAPPED_HOST\x10\x01\x12\x08\n\x04PEER\x10\x02*9\n\x08\x43\x61pacity\x12\x0e\n\nSTATE_ROWS\x10\x00\x12\x0c\n\x08KV_PAGES\x10\x01\x12\x0f\n\x0b\x44\x45VICE_POOL\x10\x02*-\n\x0eRelocationKind\x12\x0b\n\x07POINTER\x10\x00\x12\x0e\n\nTENSOR_MAP\x10\x01*4\n\x0b\x44raftSource\x12\x0c\n\x08NO_DRAFT\x10\x00\x12\x07\n\x03MTP\x10\x01\x12\x0e\n\nCOPY_DRAFT\x10\x02\x62\x06proto3') _globals = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) @@ -39,38 +39,38 @@ _globals['_REBUILDSPECULATION']._serialized_options = b'\030\001' _globals['_BUNDLEINDEX_RESOURCESENTRY']._loaded_options = None _globals['_BUNDLEINDEX_RESOURCESENTRY']._serialized_options = b'8\001' - _globals['_PREPARATIONPARAMETERSCOPE']._serialized_start=16760 - _globals['_PREPARATIONPARAMETERSCOPE']._serialized_end=17010 - _globals['_HISTORYKIND']._serialized_start=17013 - _globals['_HISTORYKIND']._serialized_end=17155 - _globals['_VALUESOURCE']._serialized_start=17158 - _globals['_VALUESOURCE']._serialized_end=18125 - _globals['_INPUTINDEXING']._serialized_start=18127 - _globals['_INPUTINDEXING']._serialized_end=18251 - _globals['_STATEACCESSKIND']._serialized_start=18253 - _globals['_STATEACCESSKIND']._serialized_end=18337 - _globals['_GRAPHOPERATION']._serialized_start=18340 - _globals['_GRAPHOPERATION']._serialized_end=18607 - _globals['_TOOLPARSERKIND']._serialized_start=18610 - _globals['_TOOLPARSERKIND']._serialized_end=18788 - _globals['_REASONINGPARSERKIND']._serialized_start=18791 - _globals['_REASONINGPARSERKIND']._serialized_end=18957 - _globals['_IMAGEPREPARATIONKIND']._serialized_start=18960 - _globals['_IMAGEPREPARATIONKIND']._serialized_end=19332 - _globals['_IMAGELAYOUTKIND']._serialized_start=19335 - _globals['_IMAGELAYOUTKIND']._serialized_end=19645 - _globals['_PROMPTENCODER']._serialized_start=19647 - _globals['_PROMPTENCODER']._serialized_end=19727 - _globals['_TEMPLATEENCODING']._serialized_start=19729 - _globals['_TEMPLATEENCODING']._serialized_end=19795 - _globals['_MEMORY']._serialized_start=19797 - _globals['_MEMORY']._serialized_end=19844 - _globals['_CAPACITY']._serialized_start=19846 - _globals['_CAPACITY']._serialized_end=19903 - _globals['_RELOCATIONKIND']._serialized_start=19905 - _globals['_RELOCATIONKIND']._serialized_end=19950 - _globals['_DRAFTSOURCE']._serialized_start=19952 - _globals['_DRAFTSOURCE']._serialized_end=20004 + _globals['_PREPARATIONPARAMETERSCOPE']._serialized_start=16812 + _globals['_PREPARATIONPARAMETERSCOPE']._serialized_end=17062 + _globals['_HISTORYKIND']._serialized_start=17065 + _globals['_HISTORYKIND']._serialized_end=17207 + _globals['_VALUESOURCE']._serialized_start=17210 + _globals['_VALUESOURCE']._serialized_end=18177 + _globals['_INPUTINDEXING']._serialized_start=18179 + _globals['_INPUTINDEXING']._serialized_end=18303 + _globals['_STATEACCESSKIND']._serialized_start=18305 + _globals['_STATEACCESSKIND']._serialized_end=18389 + _globals['_GRAPHOPERATION']._serialized_start=18392 + _globals['_GRAPHOPERATION']._serialized_end=18659 + _globals['_TOOLPARSERKIND']._serialized_start=18662 + _globals['_TOOLPARSERKIND']._serialized_end=18840 + _globals['_REASONINGPARSERKIND']._serialized_start=18843 + _globals['_REASONINGPARSERKIND']._serialized_end=19009 + _globals['_IMAGEPREPARATIONKIND']._serialized_start=19012 + _globals['_IMAGEPREPARATIONKIND']._serialized_end=19384 + _globals['_IMAGELAYOUTKIND']._serialized_start=19387 + _globals['_IMAGELAYOUTKIND']._serialized_end=19697 + _globals['_PROMPTENCODER']._serialized_start=19699 + _globals['_PROMPTENCODER']._serialized_end=19779 + _globals['_TEMPLATEENCODING']._serialized_start=19781 + _globals['_TEMPLATEENCODING']._serialized_end=19847 + _globals['_MEMORY']._serialized_start=19849 + _globals['_MEMORY']._serialized_end=19896 + _globals['_CAPACITY']._serialized_start=19898 + _globals['_CAPACITY']._serialized_end=19955 + _globals['_RELOCATIONKIND']._serialized_start=19957 + _globals['_RELOCATIONKIND']._serialized_end=20002 + _globals['_DRAFTSOURCE']._serialized_start=20004 + _globals['_DRAFTSOURCE']._serialized_end=20056 _globals['_PROTECTEDINDEX']._serialized_start=38 _globals['_PROTECTEDINDEX']._serialized_end=191 _globals['_SIGNEDGROUP']._serialized_start=193 @@ -195,64 +195,64 @@ _globals['_BUNDLEINDEX_RESOURCESENTRY']._serialized_end=12652 _globals['_ROCETRANSPORT']._serialized_start=12655 _globals['_ROCETRANSPORT']._serialized_end=12903 - _globals['_GRAPHINDEX']._serialized_start=12905 - _globals['_GRAPHINDEX']._serialized_end=13023 - _globals['_PEERMEMORY']._serialized_start=13025 - _globals['_PEERMEMORY']._serialized_end=13102 - _globals['_CONTEXT']._serialized_start=13104 - _globals['_CONTEXT']._serialized_end=13181 - _globals['_LIMIT']._serialized_start=13183 - _globals['_LIMIT']._serialized_end=13217 - _globals['_RESERVATION']._serialized_start=13219 - _globals['_RESERVATION']._serialized_end=13265 - _globals['_SPAN']._serialized_start=13267 - _globals['_SPAN']._serialized_end=13323 - _globals['_ALLOCATION']._serialized_start=13326 - _globals['_ALLOCATION']._serialized_end=13616 - _globals['_SIZING']._serialized_start=13618 - _globals['_SIZING']._serialized_end=13706 - _globals['_MODULE']._serialized_start=13708 - _globals['_MODULE']._serialized_end=13784 - _globals['_GLOBAL']._serialized_start=13786 - _globals['_GLOBAL']._serialized_end=13888 - _globals['_FUNCTION']._serialized_start=13890 - _globals['_FUNCTION']._serialized_end=14011 - _globals['_FUNCTIONATTRIBUTE']._serialized_start=14013 - _globals['_FUNCTIONATTRIBUTE']._serialized_end=14059 - _globals['_REFERENCE']._serialized_start=14061 - _globals['_REFERENCE']._serialized_end=14108 - _globals['_RELOCATION']._serialized_start=14110 - _globals['_RELOCATION']._serialized_end=14225 - _globals['_BLOB']._serialized_start=14227 - _globals['_BLOB']._serialized_end=14295 - _globals['_ATTRIBUTE']._serialized_start=14297 - _globals['_ATTRIBUTE']._serialized_end=14356 - _globals['_KERNEL']._serialized_start=14359 - _globals['_KERNEL']._serialized_end=14516 - _globals['_MEMSET']._serialized_start=14519 - _globals['_MEMSET']._serialized_end=14657 - _globals['_COPY']._serialized_start=14659 - _globals['_COPY']._serialized_end=14770 - _globals['_EMPTY']._serialized_start=14772 - _globals['_EMPTY']._serialized_end=14779 - _globals['_EVENTWAIT']._serialized_start=14781 - _globals['_EVENTWAIT']._serialized_end=14807 - _globals['_NODE']._serialized_start=14810 - _globals['_NODE']._serialized_end=15035 - _globals['_EDGE']._serialized_start=15037 - _globals['_EDGE']._serialized_end=15094 - _globals['_EXECUTION']._serialized_start=15097 - _globals['_EXECUTION']._serialized_end=15465 - _globals['_ASYNCTRANSFER']._serialized_start=15468 - _globals['_ASYNCTRANSFER']._serialized_end=15773 - _globals['_PERSISTENTWORKER']._serialized_start=15776 - _globals['_PERSISTENTWORKER']._serialized_end=15945 - _globals['_TUNINGGRAPH']._serialized_start=15947 - _globals['_TUNINGGRAPH']._serialized_end=16014 - _globals['_BUFFER']._serialized_start=16017 - _globals['_BUFFER']._serialized_end=16147 - _globals['_EXECUTIONGRAPH']._serialized_start=16150 - _globals['_EXECUTIONGRAPH']._serialized_end=16683 - _globals['_INPUTBINDING']._serialized_start=16685 - _globals['_INPUTBINDING']._serialized_end=16757 + _globals['_GRAPHINDEX']._serialized_start=12906 + _globals['_GRAPHINDEX']._serialized_end=13075 + _globals['_PEERMEMORY']._serialized_start=13077 + _globals['_PEERMEMORY']._serialized_end=13154 + _globals['_CONTEXT']._serialized_start=13156 + _globals['_CONTEXT']._serialized_end=13233 + _globals['_LIMIT']._serialized_start=13235 + _globals['_LIMIT']._serialized_end=13269 + _globals['_RESERVATION']._serialized_start=13271 + _globals['_RESERVATION']._serialized_end=13317 + _globals['_SPAN']._serialized_start=13319 + _globals['_SPAN']._serialized_end=13375 + _globals['_ALLOCATION']._serialized_start=13378 + _globals['_ALLOCATION']._serialized_end=13668 + _globals['_SIZING']._serialized_start=13670 + _globals['_SIZING']._serialized_end=13758 + _globals['_MODULE']._serialized_start=13760 + _globals['_MODULE']._serialized_end=13836 + _globals['_GLOBAL']._serialized_start=13838 + _globals['_GLOBAL']._serialized_end=13940 + _globals['_FUNCTION']._serialized_start=13942 + _globals['_FUNCTION']._serialized_end=14063 + _globals['_FUNCTIONATTRIBUTE']._serialized_start=14065 + _globals['_FUNCTIONATTRIBUTE']._serialized_end=14111 + _globals['_REFERENCE']._serialized_start=14113 + _globals['_REFERENCE']._serialized_end=14160 + _globals['_RELOCATION']._serialized_start=14162 + _globals['_RELOCATION']._serialized_end=14277 + _globals['_BLOB']._serialized_start=14279 + _globals['_BLOB']._serialized_end=14347 + _globals['_ATTRIBUTE']._serialized_start=14349 + _globals['_ATTRIBUTE']._serialized_end=14408 + _globals['_KERNEL']._serialized_start=14411 + _globals['_KERNEL']._serialized_end=14568 + _globals['_MEMSET']._serialized_start=14571 + _globals['_MEMSET']._serialized_end=14709 + _globals['_COPY']._serialized_start=14711 + _globals['_COPY']._serialized_end=14822 + _globals['_EMPTY']._serialized_start=14824 + _globals['_EMPTY']._serialized_end=14831 + _globals['_EVENTWAIT']._serialized_start=14833 + _globals['_EVENTWAIT']._serialized_end=14859 + _globals['_NODE']._serialized_start=14862 + _globals['_NODE']._serialized_end=15087 + _globals['_EDGE']._serialized_start=15089 + _globals['_EDGE']._serialized_end=15146 + _globals['_EXECUTION']._serialized_start=15149 + _globals['_EXECUTION']._serialized_end=15517 + _globals['_ASYNCTRANSFER']._serialized_start=15520 + _globals['_ASYNCTRANSFER']._serialized_end=15825 + _globals['_PERSISTENTWORKER']._serialized_start=15828 + _globals['_PERSISTENTWORKER']._serialized_end=15997 + _globals['_TUNINGGRAPH']._serialized_start=15999 + _globals['_TUNINGGRAPH']._serialized_end=16066 + _globals['_BUFFER']._serialized_start=16069 + _globals['_BUFFER']._serialized_end=16199 + _globals['_EXECUTIONGRAPH']._serialized_start=16202 + _globals['_EXECUTIONGRAPH']._serialized_end=16735 + _globals['_INPUTBINDING']._serialized_start=16737 + _globals['_INPUTBINDING']._serialized_end=16809 # @@protoc_insertion_point(module_scope) diff --git a/ignition/preparation/scratch.py b/ignition/preparation/scratch.py index 9aac04cb3..78b321fed 100644 --- a/ignition/preparation/scratch.py +++ b/ignition/preparation/scratch.py @@ -49,6 +49,11 @@ def scratch_views(backing, shapes): return tuple(views) +def _validate_reserve_sms(value, name="reserve_sms"): + if type(value) is not int or value < 0: + raise ValueError(f"{name} must be a nonnegative integer") + + class ScratchArena: """Share tuning workspace and retire declaration storage before compilation. @@ -56,9 +61,10 @@ class ScratchArena: no concurrent plans. Serving forwards allocate their own temporary tensors. """ - def __init__(self, device, *, overlap=True, allocation_pool=None): + def __init__(self, device, *, overlap=True, allocation_pool=None, min_reserve_sms=0): if type(overlap) is not bool: raise TypeError("overlap must be a boolean") + _validate_reserve_sms(min_reserve_sms, "min_reserve_sms") self.tensor = torch.empty(0, dtype=torch.uint8, device=device) self.allocation_pool = allocation_pool self.overlap = overlap @@ -67,6 +73,10 @@ def __init__(self, device, *, overlap=True, allocation_pool=None): self._finalizers = [] self._preparation_releases = [] self._parallel_plans = [] + self._min_reserve_sms = min_reserve_sms + self._max_parallel_reserve_sms = 0 + self._parallel_reserve_sms = {} + self._cooperative_plans = {} self._auxiliary_stream = None self._recorded_views = None self._binding_views = None @@ -104,7 +114,55 @@ def auxiliary_stream(self): self._auxiliary_stream = stream return self._auxiliary_stream - def register_parallel(self, *plans): + @property + def reserve_sms_floor(self) -> int: + """Minimum SMs cooperative kernels on this arena must leave unscheduled.""" + if not self.overlap: + return 0 + return max(self._min_reserve_sms, self._max_parallel_reserve_sms) + + def require_reserve_sms(self, count: int) -> None: + """Raise the arena-wide cooperative SM reservation floor.""" + _validate_reserve_sms(count) + if count == 0: + return + if not self.overlap: + raise RuntimeError("stream overlap is disabled; cooperative SM reservation requires overlap") + if self.frozen: + raise RuntimeError("scratch declarations are frozen") + for declared in self._cooperative_plans.values(): + if declared < count: + raise ValueError( + f"cooperative plan registered with reserve_sms={declared}, below required floor {count}" + ) + self._min_reserve_sms = max(self._min_reserve_sms, count) + + def resolve_reserve_sms(self, requested: int = 0) -> int: + """Return at least ``requested`` and any active overlap SM floor.""" + _validate_reserve_sms(requested) + if not self.overlap: + return requested + return max(requested, self.reserve_sms_floor) + + def register_cooperative_plan(self, plan, *, reserve_sms: int) -> None: + """Record a cooperative plan's reserved SM count and verify overlap floors.""" + _validate_reserve_sms(reserve_sms) + if plan is None: + return + if self.frozen: + raise RuntimeError("scratch declarations are frozen") + key = id(plan) + if self.overlap: + required = max(self._min_reserve_sms, self._parallel_reserve_sms.get(key, 0)) + if reserve_sms < required: + raise ValueError( + f"cooperative plan requires reserve_sms >= {required} for active overlap, got {reserve_sms}" + ) + prev = self._cooperative_plans.get(key) + # Keep the weakest-link headroom guaranteed across all cooperative ops sharing `plan`. + self._cooperative_plans[key] = reserve_sms if prev is None else min(prev, reserve_sms) + + def register_parallel(self, *plans, reserve_sms: int = 0): """Declare plans that need disjoint workspace during preparation.""" if not self.overlap: raise RuntimeError("stream overlap is disabled; serial plans share scratch") @@ -112,6 +170,19 @@ def register_parallel(self, *plans): raise RuntimeError("scratch declarations are frozen") if len(plans) < 2: raise ValueError("parallel scratch requires at least two plans") + _validate_reserve_sms(reserve_sms) + if reserve_sms > 0: + for plan in plans: + declared = self._cooperative_plans.get(id(plan)) + if declared is not None and declared < reserve_sms: + raise ValueError( + f"cooperative plan registered with reserve_sms={declared}, " + f"but parallel overlap requires at least {reserve_sms} reserved SMs" + ) + for plan in plans: + key = id(plan) + self._parallel_reserve_sms[key] = max(self._parallel_reserve_sms.get(key, 0), reserve_sms) + self._max_parallel_reserve_sms = max(self._max_parallel_reserve_sms, reserve_sms) self._parallel_plans.append(plans) def parallel_nbytes(self, requirement): @@ -157,6 +228,10 @@ def release_preparation(self): self._preparation_releases.clear() self.tensor = torch.empty(0, dtype=torch.uint8, device=self.device) self._parallel_plans.clear() + self._parallel_reserve_sms.clear() + self._cooperative_plans.clear() + self._min_reserve_sms = 0 + self._max_parallel_reserve_sms = 0 self._released = True def register_preparation_release(self, callback): diff --git a/selene/src/codec_copy.rs b/selene/src/codec_copy.rs index a5dc86344..1d6790c00 100644 --- a/selene/src/codec_copy.rs +++ b/selene/src/codec_copy.rs @@ -181,8 +181,24 @@ impl CaptureWindow { let mut row_dir = std::mem::take(&mut st.row_dir); page_dir.sort_by_key(|(u, _)| (u.kind, u.logical_index, u.stored_rank)); row_dir.sort_by_key(|(u, _)| (u.kind, u.logical_index, u.stored_rank)); - let page_keep = st.page_offset.div_ceil(target.slab_bytes); - let row_keep = st.row_offset.div_ceil(target.slab_bytes); + // SAFETY: `take_direct` runs only after all transfer threads drain and before the + // record is published, so this call holds exclusive access to `target` slabs. + let page_keep = unsafe { + dedup_and_compact_slabs( + &target.page_addrs, + target.slab_bytes, + &mut page_dir, + st.page_offset, + ) + }; + let row_keep = unsafe { + dedup_and_compact_slabs( + &target.row_addrs, + target.slab_bytes, + &mut row_dir, + st.row_offset, + ) + }; Some(Ok((page_dir, page_keep, row_dir, row_keep))) } @@ -294,6 +310,170 @@ pub fn receive_profiles(_geometry: &[crate::CacheGeometry]) -> Vec<[u8; 32]> { Vec::new() } +/// Return whether two packed units for the same logical item carry identical metadata and checksums. +pub(crate) fn units_metadata_match(a: &PackedUnit, b: &PackedUnit) -> bool { + a.kind == b.kind + && a.logical_index == b.logical_index + && a.representation == b.representation + && a.profile == b.profile + && a.original_length == b.original_length + && a.stored_length == b.stored_length + && a.stored_crc == b.stored_crc + && a.original_crc == b.original_crc + && a.raw_xxh3 == b.raw_xxh3 +} + +/// Fold `duplicate`'s rank coverage into `target.replicas`, keeping ranks strictly ascending. +pub(crate) fn merge_replicas(target: &mut PackedUnit, duplicate: &PackedUnit) { + target.replicas.push(duplicate.stored_rank); + target.replicas.extend_from_slice(&duplicate.replicas); + target.replicas.sort_unstable(); + target.replicas.dedup(); +} + +/// Deduplicate byte-identical per-rank [`CaptureSlot`] entries sorted by +/// `(kind, logical_index, stored_rank)`, recording dropped ranks in `PackedUnit.replicas`. +pub(crate) fn dedup_capture_slots(slots: &mut Vec) { + if slots.len() <= 1 { + return; + } + let mut kept: Vec = Vec::with_capacity(slots.len()); + let mut group_start = 0usize; + for slot in std::mem::take(slots) { + if kept + .get(group_start) + .is_some_and(|first| { + first.unit.kind != slot.unit.kind + || first.unit.logical_index != slot.unit.logical_index + }) + { + group_start = kept.len(); + } + if let Some(existing) = kept[group_start..] + .iter_mut() + .find(|k| units_metadata_match(&k.unit, &slot.unit) && k.bytes == slot.bytes) + { + merge_replicas(&mut existing.unit, &slot.unit); + } else { + kept.push(slot); + } + } + *slots = kept; +} + +unsafe fn slabs_equal( + addrs: &[usize], + slab_bytes: usize, + mut off_a: usize, + mut off_b: usize, + mut len: usize, +) -> bool { + while len > 0 { + let idx_a = off_a / slab_bytes; + let within_a = off_a % slab_bytes; + let idx_b = off_b / slab_bytes; + let within_b = off_b % slab_bytes; + let take = len + .min(slab_bytes - within_a) + .min(slab_bytes - within_b); + // SAFETY: caller owns immutable read access across both ranges inside `addrs`. + let a = + unsafe { std::slice::from_raw_parts((addrs[idx_a] + within_a) as *const u8, take) }; + let b = + unsafe { std::slice::from_raw_parts((addrs[idx_b] + within_b) as *const u8, take) }; + if a != b { + return false; + } + off_a += take; + off_b += take; + len -= take; + } + true +} + +unsafe fn read_from_slabs(addrs: &[usize], slab_bytes: usize, mut src_off: usize, dst: &mut [u8]) { + let mut dst_pos = 0usize; + let mut remaining = dst.len(); + while remaining > 0 { + let idx = src_off / slab_bytes; + let within = src_off % slab_bytes; + let take = remaining.min(slab_bytes - within); + // SAFETY: caller owns read access to `[src_off, src_off + dst.len())` inside `addrs`. + let src = unsafe { std::slice::from_raw_parts((addrs[idx] + within) as *const u8, take) }; + dst[dst_pos..dst_pos + take].copy_from_slice(src); + src_off += take; + dst_pos += take; + remaining -= take; + } +} + +/// Deduplicate byte-identical per-rank packed units inside `addrs` (with `dir` already sorted by +/// `(kind, logical_index, stored_rank)`), compacting kept payloads tightly from offset 0 when any +/// duplicate was eliminated, and returning the number of slabs required. +/// +/// # Safety +/// The caller must hold exclusive mutable ownership of `addrs` covering `[0, written_end)`. +unsafe fn dedup_and_compact_slabs( + addrs: &[usize], + slab_bytes: usize, + dir: &mut Vec<(PackedUnit, usize)>, + written_end: usize, +) -> usize { + if dir.len() <= 1 || slab_bytes == 0 { + return if slab_bytes == 0 { + 0 + } else { + written_end.div_ceil(slab_bytes) + }; + } + let original_len = dir.len(); + let mut kept: Vec<(PackedUnit, usize)> = Vec::with_capacity(original_len); + let mut group_start = 0usize; + for (unit, offset) in dir.drain(..) { + if kept + .get(group_start) + .is_some_and(|(first, _)| { + first.kind != unit.kind || first.logical_index != unit.logical_index + }) + { + group_start = kept.len(); + } + let duplicate = kept[group_start..].iter_mut().find(|(k, k_off)| { + units_metadata_match(k, &unit) + && unsafe { + slabs_equal(addrs, slab_bytes, *k_off, offset, unit.stored_length as usize) + } + }); + if let Some((existing, _)) = duplicate { + merge_replicas(existing, &unit); + } else { + kept.push((unit, offset)); + } + } + if kept.len() == original_len { + *dir = kept; + return written_end.div_ceil(slab_bytes); + } + let total_bytes: usize = kept.iter().map(|(u, _)| u.stored_length as usize).sum(); + let mut compact = vec![0u8; total_bytes]; + let mut cursor = 0usize; + for (unit, offset) in &mut kept { + let len = unit.stored_length as usize; + // SAFETY: all original offsets remain untouched until every kept unit is copied out. + unsafe { + read_from_slabs(addrs, slab_bytes, *offset, &mut compact[cursor..cursor + len]); + } + *offset = cursor; + cursor += len; + } + // SAFETY: reads from `addrs` have finished and `total_bytes <= written_end <= capacity`. + unsafe { + write_to_slabs(addrs, slab_bytes, 0, &compact); + } + *dir = kept; + total_bytes.div_ceil(slab_bytes) +} + /// Copy `bytes` into `addrs` starting at byte offset `dst_off` across fixed-size slabs. /// /// # Safety @@ -340,3 +520,137 @@ pub fn reader_caps_many(profiles: &[[u8; 32]]) -> crate::shared::wire::CodecCaps } caps } + +#[cfg(test)] +mod tests { + use super::*; + use crate::shared::{ + packed::Layout as PackedLayout, + record::RankSizes, + wire::{ + PackedOffer, + packed_unit::{Kind, Representation}, + }, + }; + + fn packet_unit(kind: Kind, index: u64, rank: u32, payload: &[u8], orig_len: u64) -> PackedUnit { + PackedUnit { + kind: kind as i32, + logical_index: index, + stored_rank: rank, + representation: Representation::Packet as i32, + profile: vec![0x77; 32], + original_length: orig_len, + stored_length: payload.len() as u64, + replicas: Vec::new(), + stored_crc: packed::crc32(payload), + original_crc: 0x1234_5678, + raw_xxh3: 0, + } + } + + #[test] + fn direct_slab_capture_deduplicates_identical_and_pairwise_rank_packets() { + const SLAB_BYTES: usize = 64; + const ORIG: u64 = 4096; + let mut page_slabs: Vec> = (0..16).map(|_| vec![0u8; SLAB_BYTES]).collect(); + let mut row_slabs: Vec> = (0..4).map(|_| vec![0u8; SLAB_BYTES]).collect(); + let page_addrs: Vec = page_slabs.iter_mut().map(|s| s.as_mut_ptr() as usize).collect(); + let row_addrs: Vec = row_slabs.iter_mut().map(|s| s.as_mut_ptr() as usize).collect(); + + let win = CaptureWindow::with_slabs(page_addrs.clone(), row_addrs.clone(), SLAB_BYTES); + let mla_pkt = vec![0xAAu8; 40]; + let gqa_a = vec![0xB1u8; 36]; + let gqa_b = vec![0xB2u8; 36]; + let row_pkt = vec![0xCCu8; 30]; + + // Push out of rank order (3, 1, 0, 2) just like concurrent per-rank transfer threads. + for &rank in &[3u32, 1, 0, 2] { + // Page 0: all 4 ranks identical (4:1 MLA dedup). + win.push_slice(packet_unit(Kind::Page, 0, rank, &mla_pkt, ORIG), &mla_pkt); + // Page 1: ranks {0, 1} identical and {2, 3} identical (2:1 GQA dedup). + let p1 = if rank < 2 { &gqa_a } else { &gqa_b }; + win.push_slice(packet_unit(Kind::Page, 1, rank, p1, ORIG), p1); + // Page 2: all 4 ranks distinct. + let p2 = vec![0xD0u8 + rank as u8; 24]; + win.push_slice(packet_unit(Kind::Page, 2, rank, &p2, ORIG), &p2); + // Row: all 4 ranks identical. + win.push_slice(packet_unit(Kind::Row, 0, rank, &row_pkt, ORIG), &row_pkt); + } + + let (page_dir, page_keep, row_dir, row_keep) = win.take_direct().unwrap().unwrap(); + // Kept page bytes: 40 (p0) + 36*2 (p1) + 24*4 (p2) = 208 bytes -> 4 slabs (vs 400 -> 7 slabs). + assert_eq!(page_dir.len(), 1 + 2 + 4); + assert_eq!(page_keep, 208usize.div_ceil(SLAB_BYTES)); + assert_eq!(page_dir[0].0.stored_rank, 0); + assert_eq!(page_dir[0].0.replicas, vec![1, 2, 3]); + assert_eq!(page_dir[1].0.stored_rank, 0); + assert_eq!(page_dir[1].0.replicas, vec![1]); + assert_eq!(page_dir[2].0.stored_rank, 2); + assert_eq!(page_dir[2].0.replicas, vec![3]); + for (i, (u, _)) in page_dir[3..].iter().enumerate() { + assert_eq!(u.stored_rank, i as u32); + assert!(u.replicas.is_empty()); + } + // Kept row bytes: 30 bytes -> 1 slab (vs 120 -> 2 slabs). + assert_eq!(row_dir.len(), 1); + assert_eq!(row_keep, 1); + assert_eq!(row_dir[0].0.stored_rank, 0); + assert_eq!(row_dir[0].0.replicas, vec![1, 2, 3]); + + // Verify compacted bytes and v4 PackedLayout validity across all 4 ranks. + let mut buf = vec![0u8; 40]; + unsafe { read_from_slabs(&page_addrs, SLAB_BYTES, page_dir[0].1, &mut buf) }; + assert_eq!(buf, mla_pkt); + let mut buf2 = vec![0u8; 36]; + unsafe { read_from_slabs(&page_addrs, SLAB_BYTES, page_dir[2].1, &mut buf2) }; + assert_eq!(buf2, gqa_b); + let mut rbuf = vec![0u8; 30]; + unsafe { read_from_slabs(&row_addrs, SLAB_BYTES, row_dir[0].1, &mut rbuf) }; + assert_eq!(rbuf, row_pkt); + + let mut units: Vec = page_dir.into_iter().map(|(u, _)| u).collect(); + units.extend(row_dir.into_iter().map(|(u, _)| u)); + let rank_sizes = vec![ + RankSizes { + planes: vec![ORIG], + row_bytes: ORIG, + }; + 4 + ]; + PackedLayout::new(PackedOffer { first_page: 0, units }, &rank_sizes, 0, 3).unwrap(); + } + + #[test] + fn dedup_capture_slots_merges_identical_ranks_and_validates_layout() { + const ORIG: u64 = 4096; + let payload = vec![0x55u8; 48]; + let mut slots: Vec = (0..4u32) + .map(|r| CaptureSlot { + unit: packet_unit(Kind::Page, 0, r, &payload, ORIG), + bytes: payload.clone(), + }) + .collect(); + dedup_capture_slots(&mut slots); + assert_eq!(slots.len(), 1); + assert_eq!(slots[0].unit.stored_rank, 0); + assert_eq!(slots[0].unit.replicas, vec![1, 2, 3]); + let rank_sizes = vec![ + RankSizes { + planes: vec![ORIG], + row_bytes: ORIG, + }; + 4 + ]; + PackedLayout::new( + PackedOffer { + first_page: 0, + units: vec![slots[0].unit.clone()], + }, + &rank_sizes, + 0, + 1, + ) + .unwrap(); + } +} diff --git a/selene/src/disk_store.rs b/selene/src/disk_store.rs index 7cf80a6d5..5f6205a5b 100644 --- a/selene/src/disk_store.rs +++ b/selene/src/disk_store.rs @@ -392,6 +392,7 @@ fn build_packed_write( packed_unit::{Kind, Representation}, }; slots.sort_by_key(|s| (s.unit.kind, s.unit.logical_index, s.unit.stored_rank)); + crate::codec_copy::dedup_capture_slots(&mut slots); let any_packet = slots .iter() .any(|s| s.unit.representation == Representation::Packet as i32); diff --git a/selene/src/memory.rs b/selene/src/memory.rs index d5bae6d7e..e7bc718a6 100644 --- a/selene/src/memory.rs +++ b/selene/src/memory.rs @@ -1897,7 +1897,13 @@ impl Core { self.pack_shares(key); } let r = self.index[key].location.replication; - if r.pages || r.row { + let packed_dedup = self.index[key].location.packed.as_ref().is_some_and(|p| { + p.pages.iter().any(|(u, _)| !u.replicas.is_empty()) + || p.row + .as_ref() + .is_some_and(|rows| rows.iter().any(|(u, _)| !u.replicas.is_empty())) + }); + if r.pages || r.row || packed_dedup { self.stats.packed_records[0] += 1; } else { self.stats.per_rank_records[0] += 1; @@ -3157,12 +3163,33 @@ fn encode_host_task( }) .collect(); let mut writes: Vec<(usize, usize, usize)> = Vec::with_capacity(cur_jobs); - for (idx, res) in results.into_iter().enumerate() { - let (unit, used) = res?; - stored_bytes += unit.stored_length; - page_dir.push((unit, out_offset)); - writes.push((idx, out_offset, used)); - out_offset += used; + let mut page_kept: Vec<(usize, PackedUnit, usize)> = Vec::with_capacity(ranks); + let mut results_iter = results.into_iter().enumerate(); + for _ in wave_start..wave_end { + page_kept.clear(); + for _ in 0..ranks { + let (idx, res) = results_iter.next().unwrap(); + let (unit, used) = res?; + if ranks > 1 + && let Some((_, existing, _)) = + page_kept.iter_mut().find(|(k_idx, k_unit, k_used)| { + *k_used == used + && crate::codec_copy::units_metadata_match(k_unit, &unit) + && scratch.page_out[*k_idx][..*k_used] + == scratch.page_out[idx][..used] + }) + { + crate::codec_copy::merge_replicas(existing, &unit); + } else { + page_kept.push((idx, unit, used)); + } + } + for (idx, unit, used) in page_kept.drain(..) { + stored_bytes += unit.stored_length; + page_dir.push((unit, out_offset)); + writes.push((idx, out_offset, used)); + out_offset += used; + } } debug_assert!(out_offset <= wave_end * slab_bytes); writes.par_iter().for_each(|&(idx, start, used)| { @@ -3224,8 +3251,17 @@ fn encode_host_task( .row .encode_capture(base, &encoder.profile, &row_raw, &mut row_buf, Some(pool)) .map_err(|e| e.to_string())?; - stored_bytes += unit.stored_length; - encoded_rows.push((unit, row_buf[..used].to_vec())); + if ranks > 1 + && let Some((existing, _)) = encoded_rows.iter_mut().find(|(k_unit, k_bytes)| { + crate::codec_copy::units_metadata_match(k_unit, &unit) + && k_bytes.as_slice() == &row_buf[..used] + }) + { + crate::codec_copy::merge_replicas(existing, &unit); + } else { + stored_bytes += unit.stored_length; + encoded_rows.push((unit, row_buf[..used].to_vec())); + } } drop(row_raw); drop(row_buf); @@ -9017,4 +9053,186 @@ mod tests { store.close().unwrap(); } } + + #[cfg(feature = "codec")] + #[test] + fn packed_multi_rank_mla_capture_deduplicates_slabs_stats_and_pool_export() { + use crate::shared::{ + codec::{Encoding, Field, Plan}, + packed::Layout as PackedLayout, + record::RankSizes, + wire::{ + PackedUnit, + packed_unit::{Kind, Representation}, + }, + }; + use crate::store::TierStore; + + const RANKS: usize = 4; + const RANK_PAGE: u64 = 16_384; + const RANK_ROW: u64 = 16_384; + let geometry: Vec<_> = (0..RANKS) + .map(|_| geometry(PT, &[("kv", RANK_PAGE)], RANK_ROW)) + .collect(); + let layout = Layout::new(&geometry).unwrap(); + let page_plan = Arc::new( + Plan::new( + RANK_PAGE as usize, + &[Field { + offset: 0, + length: RANK_PAGE as usize, + encoding: Encoding::Bfloat16, + }], + ) + .unwrap(), + ); + let row_plan = Arc::new( + Plan::new( + RANK_ROW as usize, + &[Field { + offset: 0, + length: RANK_ROW as usize, + encoding: Encoding::Bfloat16, + }], + ) + .unwrap(), + ); + let profile = [0x44u8; 32]; + + // Multi-rank direct slab capture (matching `--lossless-kv-compression gpu`) pushing + // identical MLA packets across all 4 ranks must deduplicate 4:1, release excess DRAM + // slabs, increment `packed_records`, keep `replication` clear for pool announcements, + // and emit a valid 4-rank PackedOffer. + struct DirectMultiRankCopier { + layout: Layout, + profile: [u8; 32], + page_plan: Arc, + row_plan: Arc, + replies: Vec, + } + impl crate::copier::PageCopier for DirectMultiRankCopier { + fn layout(&self) -> &Layout { + &self.layout + } + fn codec_profile(&self) -> Option<[u8; 32]> { + Some(self.profile) + } + fn submit(&mut self, job: Job) -> Result<()> { + let win = job.codec.as_ref().expect("packed direct capture window"); + let cap = win.capture.as_ref().expect("direct capture target"); + let mut buf = vec![0u8; self.page_plan.max_packet().max(self.row_plan.max_packet())]; + let mut bytes = 0u64; + for (i, _) in job.pages.iter().enumerate() { + let raw: Vec = (0..RANK_PAGE as usize) + .map(|b| ((i * 13 + (b % 37)) & 0xff) as u8) + .collect(); + for rank in 0..RANKS as u32 { + let base = PackedUnit { + kind: Kind::Page as i32, + logical_index: win.first + i as u64, + stored_rank: rank, + original_length: RANK_PAGE, + ..Default::default() + }; + let (unit, n) = self + .page_plan + .encode_capture(base, &self.profile, &raw, &mut buf, None) + .unwrap(); + assert_eq!(unit.representation, Representation::Packet as i32); + cap.push_slice(unit, &buf[..n]); + bytes += n as u64; + } + } + if job.row.is_some() { + let raw = vec![0x3Cu8; RANK_ROW as usize]; + for rank in 0..RANKS as u32 { + let base = PackedUnit { + kind: Kind::Row as i32, + logical_index: 0, + stored_rank: rank, + original_length: RANK_ROW, + ..Default::default() + }; + let (unit, n) = self + .row_plan + .encode_capture(base, &self.profile, &raw, &mut buf, None) + .unwrap(); + cap.push_slice(unit, &buf[..n]); + bytes += n as u64; + } + } + self.replies.push(Reply { + id: job.id, + window: job.window, + direction: job.direction, + result: Ok(()), + bytes, + elapsed: Duration::from_micros(1), + }); + Ok(()) + } + fn poll(&mut self, out: &mut Vec) { + out.append(&mut self.replies); + } + fn in_flight(&self) -> usize { + self.replies.len() + } + fn close(&mut self) -> Result<()> { + Ok(()) + } + } + + let copier: SharedCopier = Arc::new(std::sync::Mutex::new(DirectMultiRankCopier { + layout: layout.clone(), + profile, + page_plan: page_plan.clone(), + row_plan: row_plan.clone(), + replies: Vec::new(), + })); + let pool = SlabPool::new(layout.page_record_bytes, 32, 0).unwrap(); + let mut store = MemoryStore::new(IDENTITY, pool, copier).unwrap(); + store.announce_to(Announcer::new(Arc::new(tokio::sync::Notify::new()))); + let h = history(PT * 8, 99); + let cp = published(&h, PT * 8, None, 0, 1); + assert_eq!(store.store(&cp).unwrap(), StoreOutcome::Queued); + let deadline = Instant::now() + Duration::from_secs(5); + poll_until(&mut store, deadline, |e| { + matches!(e, StoreEvent::Stored { result: Ok(_), .. }) + }); + let rec = store.record(&cp.key).unwrap(); + let packed = rec.packed.as_ref().expect("packed direct capture"); + assert_eq!(packed.page_count, 8); + assert_eq!(packed.pages.len(), 8, "4 identical ranks must collapse to 1 unit/page"); + for (u, _) in &packed.pages { + assert_eq!(u.stored_rank, 0); + assert_eq!(u.replicas, vec![1, 2, 3]); + } + let row_units = packed.row.as_ref().expect("packed row"); + assert_eq!(row_units.len(), 1); + assert_eq!(row_units[0].0.stored_rank, 0); + assert_eq!(row_units[0].0.replicas, vec![1, 2, 3]); + assert!( + rec.pages.len() <= 2, + "deduplicated packed pages should release excess slabs, kept {}", + rec.pages.len() + ); + assert_eq!(rec.replication, Default::default()); + assert_eq!(store.stats().packed_records, [1, 0]); + assert_eq!(store.stats().per_rank_records, [0, 0]); + + let pin = store.pin_export(PoolTier::Dram, cp.key, 0, true).unwrap(); + let offer = pin.packed_offer().expect("pool export packed offer"); + assert_eq!(offer.units.len(), 9); + let rank_sizes = vec![ + RankSizes { + planes: vec![RANK_PAGE], + row_bytes: RANK_ROW, + }; + RANKS + ]; + PackedLayout::new(offer, &rank_sizes, 0, 8).unwrap(); + drop(pin); + assert_clean_slots(&store.core); + store.close().unwrap(); + } } diff --git a/tests/preparation/test_capture_graph_metadata.py b/tests/preparation/test_capture_graph_metadata.py index cf23b9257..08ca337a3 100644 --- a/tests/preparation/test_capture_graph_metadata.py +++ b/tests/preparation/test_capture_graph_metadata.py @@ -593,3 +593,60 @@ def test_capture_forwards_integrated_storage_skips_probe_and_reseal_on_windows(m warmup_storage=storage, ) assert events == ["serving_capture"] + + +def test_capture_forwards_records_min_compute_sms_and_emits_only_when_nonzero(monkeypatch, recorder): + from b12x._lib.utils.device import record_min_compute_sms + + stream = SimpleNamespace(wait_stream=lambda other: None, synchronize=lambda: None) + storage = SimpleNamespace( + pool=SimpleNamespace(id=(0, 1)), + graph_pool=SimpleNamespace(id=(0, 2)), + transient=nullcontext, + retain_transient_backing=nullcontext, + ) + _patch_export_capture(monkeypatch, stream) + + def clustered_forward(): + record_min_compute_sms(8) + record_min_compute_sms(32) + record_min_compute_sms(16) + + graphs, _ = capture.capture_forwards( + {"plain": lambda: None, "clustered": clustered_forward}, + {"plain": SimpleNamespace(kind="decode"), "clustered": SimpleNamespace(kind="decode")}, + session=SimpleNamespace(capture=nullcontext), + device="cpu", + stream=stream, + pool=(0, 2), + compile_decoder=False, + retain_graphs=True, + warmup_storage=storage, + ) + assert not hasattr(graphs["plain"], "_flare_min_compute_sms") + assert graphs["clustered"]._flare_min_compute_sms == 32 + expected_flags = ( + CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH + | CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY + ) + assert _graphs(graphs) == [ + dict(name="plain", graph=11, instantiate_flags=expected_flags), + dict(name="clustered", graph=11, instantiate_flags=expected_flags, min_compute_sms=32), + ] + + recorded = RecordedExportGraph(recorder, 7, 100, ()) + recorded._flare_min_compute_sms = 24 + assert _graphs({"rec": recorded}, recorder=recorder) == [ + dict(name="rec", recorded=7, min_compute_sms=24) + ] + recorded_zero = RecordedExportGraph(recorder, 8, 100, ()) + assert _graphs({"zero": recorded_zero}, recorder=recorder) == [ + dict(name="zero", recorded=8) + ] + + graphs["plain"]._flare_min_compute_sms = -1 + with pytest.raises(ValueError, match="min_compute_sms must be a nonnegative integer"): + _graphs({"plain": graphs["plain"]}) + graphs["plain"]._flare_min_compute_sms = True + with pytest.raises(ValueError, match="min_compute_sms must be a nonnegative integer"): + _graphs({"plain": graphs["plain"]}) diff --git a/tests/preparation/test_scratch.py b/tests/preparation/test_scratch.py index 908e37d05..2b03f7dcb 100644 --- a/tests/preparation/test_scratch.py +++ b/tests/preparation/test_scratch.py @@ -543,3 +543,72 @@ def test_priming_owners_retain_arena_instead_of_transient_views(): assert prime_owners(scratch, scratch, binding) == (scratch, binding) assert prime_owners(None, scratch, binding) == (scratch, binding) assert prime_owners(None) == () + + +def test_arena_reserve_sms_floor_and_bidirectional_parallel_enforcement(): + arena = ScratchArena("cpu", min_reserve_sms=2) + assert arena.reserve_sms_floor == 2 + assert arena.resolve_reserve_sms(0) == 2 + assert arena.resolve_reserve_sms(6) == 6 + + plan_a, plan_b, plan_c = SimpleNamespace(name="a"), SimpleNamespace(name="b"), SimpleNamespace(name="c") + # Parallel overlap before cooperative registration raises the floor and rejects undersized plans. + arena.register_parallel(plan_a, plan_b, reserve_sms=4) + assert arena.reserve_sms_floor == 4 + assert arena.resolve_reserve_sms(0) == 4 + with pytest.raises(ValueError, match="requires reserve_sms >= 4"): + arena.register_cooperative_plan(plan_a, reserve_sms=2) + arena.register_cooperative_plan(plan_a, reserve_sms=4) + + # Multiple cooperative ops sharing a plan keep the weakest-link headroom. + plan_d = SimpleNamespace(name="d") + arena.register_cooperative_plan(plan_d, reserve_sms=8) + arena.register_cooperative_plan(plan_d, reserve_sms=4) + with pytest.raises(ValueError, match="requires at least 6 reserved SMs"): + arena.register_parallel(plan_d, plan_b, reserve_sms=6) + + # Cooperative registration before parallel overlap fails closed when a later overlap needs more SMs. + arena.register_cooperative_plan(plan_c, reserve_sms=4) + arena.register_parallel(plan_c, plan_b, reserve_sms=0) + arena.register_parallel(plan_c, plan_b, reserve_sms=4) + with pytest.raises(ValueError, match="requires at least 8 reserved SMs"): + arena.register_parallel(plan_c, plan_b, reserve_sms=8) + + # Raising the arena-wide floor also rejects existing undersized cooperative plans. + with pytest.raises(ValueError, match="below required floor 6"): + arena.require_reserve_sms(6) + arena.require_reserve_sms(4) + assert arena.reserve_sms_floor == 4 + + arena.freeze() + with pytest.raises(RuntimeError, match="frozen"): + arena.require_reserve_sms(4) + with pytest.raises(RuntimeError, match="frozen"): + arena.register_cooperative_plan(SimpleNamespace(), reserve_sms=4) + arena.finalize() + arena.release_preparation() + assert not arena._cooperative_plans and not arena._parallel_reserve_sms + assert arena.reserve_sms_floor == 0 + + +def test_arena_reserve_sms_validation_and_serial_mode(): + serial = ScratchArena("cpu", overlap=False, min_reserve_sms=4) + assert serial.reserve_sms_floor == 0 + assert serial.resolve_reserve_sms(0) == 0 + assert serial.resolve_reserve_sms(3) == 3 + serial.register_cooperative_plan(SimpleNamespace(), reserve_sms=0) + with pytest.raises(RuntimeError, match="stream overlap is disabled"): + serial.require_reserve_sms(2) + + arena = ScratchArena("cpu") + for bad in (-1, True, False, 1.5, "4"): + with pytest.raises(ValueError, match="nonnegative integer"): + ScratchArena("cpu", min_reserve_sms=bad) + with pytest.raises(ValueError, match="nonnegative integer"): + arena.require_reserve_sms(bad) + with pytest.raises(ValueError, match="nonnegative integer"): + arena.resolve_reserve_sms(bad) + with pytest.raises(ValueError, match="nonnegative integer"): + arena.register_cooperative_plan(SimpleNamespace(), reserve_sms=bad) + with pytest.raises(ValueError, match="nonnegative integer"): + arena.register_parallel(SimpleNamespace(), SimpleNamespace(), reserve_sms=bad)