diff --git a/docs/api.md b/docs/api.md index e2729a101..3eb869522 100644 --- a/docs/api.md +++ b/docs/api.md @@ -400,6 +400,20 @@ uncommitted reservations for parked or in-flight writes ranking estimates, leaving `flare_host_cache_inbound_bytes_per_second` for the local store's measured restore rate. +When a loaded core declares `Execution.async_transfers` channels, `/metrics` +also exports lock-free per-channel gauges and counters labeled by `channel` and +`rank`: `flare_async_transfer_device_pool_bytes`, +`flare_async_transfer_host_pool_bytes`, +`flare_async_transfer_submitted_cmds_total`, +`flare_async_transfer_completed_cmds_total`, +`flare_async_transfer_canceled_cmds_total`, +`flare_async_transfer_rejected_cmds_total`, +`flare_async_transfer_bytes_disk_to_host_total`, +`flare_async_transfer_bytes_host_to_dev_total`, +`flare_async_transfer_bytes_disk_to_dev_total`, and +`flare_async_transfer_last_error`. Cores without async transfer channels omit +these series. + Dashboard DEPTH is the change in `verification_drafts` divided by the change in `verification_rounds` over the sampling window. It averages each request's planned draft-prefix length, including zero-draft rounds, rather than graph width or batch diff --git a/docs/cli-design.md b/docs/cli-design.md index e0b209176..696883a5a 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -757,6 +757,8 @@ Help exits with status 0; usage errors go to stderr with status 2. Its options a | `--max-concurrency N` | Reduce concurrency within captured batch capacities | Model/default configuration, otherwise core default | | `--kv-cache-limit concurrency\|context\|memory` | Bound shared KV history by prepared context times selected concurrency, one prepared context, or available memory | `memory` | | `--memory-limit LIMIT` | Per-GPU occupied size (`30G`), free-memory reserve (`-30G`, including `-0G`), or fraction of total memory (`0.8`) | `[memory] reserve`, otherwise core serving reserve | +| `--pool-vram-memory LIMIT` | Per-GPU ceiling for runtime-sized `Capacity::DEVICE_POOL` allocations on cores declaring async transfer pools: nonnegative size (`0`, `12G`), free-memory reserve (`-8G`), or fraction of total GPU memory (`0.25`); ignored on cores without `DEVICE_POOL` allocations | `[memory] pool_vram`, otherwise available VRAM above minimum KV reserve | +| `--pool-ram-memory LIMIT` | Per-rank ceiling for runtime-sized pinned `AsyncTransfer` host pools on cores declaring `Execution.async_transfers`: nonnegative size (`0`, `32G`), free-memory reserve (`-16G`), or fraction of total host RAM (`0.5`); ignored on cores without async transfer channels | `[memory] pool_ram`, otherwise available host RAM | | `--mtp-draft-tokens N` | Reduce the maximum draft count; zero selects ordinary execution without draft generation, absorption, or draft-state maintenance | Core default | | `--mtp-adaptive-verification` / `--no-mtp-adaptive-verification` | Adaptive or fixed selection among captured widths | Core default | | `--mtp-adaptive-verification-alpha ALPHA` | Positive finite exponent on completed prefix-survival scheduling scores; below 1 favors longer verification prefixes | `1.0` | diff --git a/docs/core-format-design.md b/docs/core-format-design.md index 71aecef0a..1c41a17ab 100644 --- a/docs/core-format-design.md +++ b/docs/core-format-design.md @@ -210,7 +210,7 @@ not substitutes for identifiers. | --- | --- | | `CoreBody` | Format version, core identity, publisher identity, shared frontend contract and payload descriptors, deployment IDs and commitments to their serialized bodies. | | `DeploymentBody` | Deployment ID, target architecture, TP topology, prepared contract and capacities, rank IDs and commitments to their serialized bodies. | -| `RankBody` | Rank ID, context and address reservations, allocations, initializers, modules, functions, graph catalog, events, peer/transport bindings, referenced payload descriptors, and optional prepared-weight catalog. | +| `RankBody` | Rank ID, context and address reservations, allocations, initializers, modules, functions, graph catalog, events, peer/transport bindings, referenced payload descriptors, optional prepared-weight catalog, and optional `external_extents` tables. | | `PayloadDescriptor` | Content ID equal to SHA-256 of exact stored bytes and byte length. Conflicting lengths for one ID are rejected. | | `PayloadSlice` | Payload ID, byte offset within the payload tensor, and byte length. | | `PayloadUse` | One `PayloadSlice` and its use role: weights, tuned weights, initial state, kernels, graphs, or frontend. | @@ -220,6 +220,7 @@ not substitutes for identifiers. | `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. | | `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. | Payload descriptors are authenticated wherever consumed, with equality enforced across shared and rank bodies. Each body is signed over its exact serialized diff --git a/docs/runtime-core-design.md b/docs/runtime-core-design.md index 865da8923..3a9337cfa 100644 --- a/docs/runtime-core-design.md +++ b/docs/runtime-core-design.md @@ -685,6 +685,30 @@ green context), virtual-address reservations, and the primary context. Before CUDA initialization or serving worker threads, Flare restricts `CUDA_VISIBLE_DEVICES` to `--gpus`, resolving indices within an inherited mask. + +When a core declares `Capacity::DEVICE_POOL` allocations and +`Execution.async_transfers` channels, `allocate_caches` first reserves +`pinned_bytes.div_ceil(512) + 256 MiB` of VRAM per rank for `cuMemHostRegister_v2` +GPU MMU page tables and worker streams (covering each channel's planned pinned +`HOST_POOL` and bounded internal bounce pool, which is disabled when channel +alignment exceeds 32 MiB), then sizes and maps each `DEVICE_POOL` at its fixed +reserved CUDA virtual address before computing KV page capacity (leaving space +for execution state rows and the minimum KV cache requirement, bounded by +`--pool-vram-memory` / `[memory] pool_vram`). Across tensor-parallel ranks, +`DEVICE_POOL` physical byte capacity is agreed as the minimum across ranks, and +`Execution.buffers` views backed by that allocation are rewritten to +`floor(agreed_bytes / row_bytes)` leading rows (truncating any partial trailing +row). `NativeResources::prepare_async_transfers` authenticates and opens the +4 KiB-aligned `RankBody.external_extents` payload segments directly (`O_DIRECT` +on Linux), allocates each channel's runtime-sized pinned `HOST_POOL` (clamped to +the planned per-rank host ceiling from `allocate_caches`, with an internal +pinned bounce pool when enabled), writes immutable startup geometry into the +mapped-host `ControlHeader`, and starts the channel workers before executing +`Execution.tuning_graphs`. Shutdown stops and drains all async transfer +channels after compute streams drain and before unmapping device or mapped-host +storage; unconfirmed drain transitions the channel to `FailedDrain` and retains +pinned memory and CUDA handles until process exit. Cores without +`Execution.async_transfers` channels bypass this path completely. When omitted, the list contains the first N visible GPUs for the core's N local ranks, or one GPU per host for a multi-host core. Core loading finishes its progress threads before setting visibility. Hub revision detection queries diff --git a/flare-cli/src/cli.rs b/flare-cli/src/cli.rs index 8981d380f..9acad3372 100644 --- a/flare-cli/src/cli.rs +++ b/flare-cli/src/cli.rs @@ -18,7 +18,7 @@ use flare_helios::{ KvCompression, PoolOptions, PrefixCacheOffload, parse_drain_on_shutdown, parse_max_age, parse_pool_address, parse_size, }, - runtime_core::{KvCacheLimit, LoadOptions, MemoryLimit}, + runtime_core::{KvCacheLimit, LoadOptions, MemoryLimit, PoolMemoryLimit}, }; /// The serving option that routes every peer over subnets every rank holds. @@ -942,6 +942,26 @@ pub struct ServingOptions { )] pub memory_limit: Option, + /// Per-GPU byte pool budget for runtime-sized device pools: size (12G), zero (0), + /// free reserve (-8G), or fraction of GPU memory (0.2). + #[arg( + long, + allow_hyphen_values = true, + value_name = "LIMIT", + help_heading = "Serving options" + )] + pub pool_vram_memory: Option, + + /// Per-host pinned RAM pool budget for async extent transfers: size (32G), zero (0), + /// free reserve (-16G), or fraction of system RAM (0.5). + #[arg( + long, + allow_hyphen_values = true, + value_name = "LIMIT", + help_heading = "Serving options" + )] + pub pool_ram_memory: Option, + /// Route RoCE rails and fabric transfers only over subnets every rank holds, as on a switch /// alone, leaving direct cables between ranks unused. #[arg(long, help_heading = "Multi-host options")] @@ -1150,6 +1170,12 @@ impl ServingOptions { if let Some(limit) = self.memory_limit { options.push(format!("--memory-limit={limit}")); } + if let Some(limit) = self.pool_vram_memory { + options.push(format!("--pool-vram-memory={limit}")); + } + if let Some(limit) = self.pool_ram_memory { + options.push(format!("--pool-ram-memory={limit}")); + } match shape { Shape::Mesh => {} Shape::Ring => options.push("--roce-ring".into()), @@ -1267,6 +1293,8 @@ impl ServingOptions { LoadOptions { kv_cache_limit: self.kv_cache_limit, memory_limit: self.memory_limit, + pool_vram_limit: self.pool_vram_memory, + pool_ram_limit: self.pool_ram_memory, embedding_table_storage: self.embedding_table_storage, embedding_table_cache_bytes: self.embedding_table_cache_size, embedding_table_resident_scales: if self.embedding_table_resident_scales { @@ -2418,6 +2446,63 @@ mod tests { ); } + #[test] + fn pool_memory_limits_accept_zero_sizes_reserves_fractions_and_reach_every_rank() { + for (vram, ram) in [ + ("12G", "0"), + ("0", "32G"), + ("-8G", "0.5"), + ("0.25", "-16G"), + ("0G", "0G"), + ] { + let args = run(&[ + "flare", + "run", + "model.safetensors", + "--pool-vram-memory", + vram, + "--pool-ram-memory", + ram, + ]); + assert_eq!( + args.load_options().pool_vram_limit, + Some(vram.parse().unwrap()) + ); + assert_eq!( + args.load_options().pool_ram_limit, + Some(ram.parse().unwrap()) + ); + let forwarded = args.rank_options(); + let mut peer = vec!["flare", "run", "model.safetensors"]; + peer.extend(forwarded.iter().map(String::as_str)); + let peer = run(&peer).load_options(); + assert_eq!(peer.pool_vram_limit, args.load_options().pool_vram_limit); + assert_eq!(peer.pool_ram_limit, args.load_options().pool_ram_limit); + } + for bad in ["-0.5", "1.5", "NaN", "1e-1"] { + assert!( + Cli::try_parse_from([ + "flare", + "run", + "model.safetensors", + "--pool-vram-memory", + bad + ]) + .is_err() + ); + assert!( + Cli::try_parse_from([ + "flare", + "run", + "model.safetensors", + "--pool-ram-memory", + bad + ]) + .is_err() + ); + } + } + #[test] fn debian_man_page_documents_every_visible_subcommand() { use clap::CommandFactory; diff --git a/flare-cli/src/config.rs b/flare-cli/src/config.rs index 373cb0158..aa410a63a 100644 --- a/flare-cli/src/config.rs +++ b/flare-cli/src/config.rs @@ -13,7 +13,7 @@ use std::path::PathBuf; use clap::{ArgMatches, parser::ValueSource}; use flare_helios::{ offload::{parse_drain_on_shutdown, parse_max_age}, - runtime_core::MemoryLimit, + runtime_core::{MemoryLimit, PoolMemoryLimit}, }; use crate::cli; @@ -78,6 +78,24 @@ impl Configuration { serving.memory_limit = size(self.memory.reserve.as_deref(), "memory.reserve")? .map(MemoryLimit::Reserve); } + if serving.pool_vram_memory.is_none() { + serving.pool_vram_memory = nonempty(self.memory.pool_vram.as_deref()) + .map(|value| { + value + .parse::() + .map_err(|error| format!("memory.pool_vram: {error}")) + }) + .transpose()?; + } + if serving.pool_ram_memory.is_none() { + serving.pool_ram_memory = nonempty(self.memory.pool_ram.as_deref()) + .map(|value| { + value + .parse::() + .map_err(|error| format!("memory.pool_ram: {error}")) + }) + .transpose()?; + } if serving.prefix_cache_memory.is_none() { serving.prefix_cache_memory = size( nonempty(self.prefix_cache.memory.as_deref()), diff --git a/flare-cli/src/main.rs b/flare-cli/src/main.rs index 0261de211..19db02a58 100644 --- a/flare-cli/src/main.rs +++ b/flare-cli/src/main.rs @@ -652,7 +652,10 @@ fn serve( peers, ) } { - Ok(server) => server, + Ok(server) => { + server.attach_async_transfers(owner.async_transfer_handles()); + server + } Err(error) => { if !error.drained { std::mem::forget(transport); diff --git a/flare/src/configuration.rs b/flare/src/configuration.rs index 8407379b7..4d06f73ee 100644 --- a/flare/src/configuration.rs +++ b/flare/src/configuration.rs @@ -1,6 +1,7 @@ //! Typed host configuration independent of frontend argument parsing. -use flare_helios::offload::{ - KvCompression, parse_drain_on_shutdown, parse_max_age, parse_size, +use flare_helios::{ + offload::{KvCompression, parse_drain_on_shutdown, parse_max_age, parse_size}, + runtime_core::PoolMemoryLimit, }; use serde::Deserialize; use std::{ @@ -46,6 +47,8 @@ pub struct Model { #[serde(default)] pub struct Memory { pub reserve: Option, + pub pool_vram: Option, + pub pool_ram: Option, } #[derive(Default, Deserialize)] @@ -86,6 +89,16 @@ impl Configuration { return Err("server.scheduler_checkpoint_extra_work_fraction must be finite and between zero and one".into()); } size(configuration.memory.reserve.as_deref(), "memory.reserve")?; + if let Some(value) = nonempty(configuration.memory.pool_vram.as_deref()) { + value + .parse::() + .map_err(|error| format!("memory.pool_vram: {error}"))?; + } + if let Some(value) = nonempty(configuration.memory.pool_ram.as_deref()) { + value + .parse::() + .map_err(|error| format!("memory.pool_ram: {error}"))?; + } size( nonempty(configuration.prefix_cache.memory.as_deref()), "prefix_cache.memory", diff --git a/flare/src/runtime_settings.rs b/flare/src/runtime_settings.rs index 81b811f6b..5abe7b3dd 100644 --- a/flare/src/runtime_settings.rs +++ b/flare/src/runtime_settings.rs @@ -3,7 +3,7 @@ use flare_helios::{ engram::Storage, offload::{parse_drain_on_shutdown, parse_max_age, parse_size}, - runtime_core::{KvCacheLimit, LoadOptions, MemoryLimit}, + runtime_core::{KvCacheLimit, LoadOptions, MemoryLimit, PoolMemoryLimit}, }; use serde::{Deserialize, Serialize}; use std::{ @@ -15,6 +15,8 @@ use std::{ pub struct RuntimeSettings { pub gpu: i32, pub memory_limit: String, + pub pool_vram_memory: String, + pub pool_ram_memory: String, pub kv_cache_limit: String, pub host: String, pub port: u16, @@ -36,6 +38,8 @@ impl Default for RuntimeSettings { Self { gpu: 0, memory_limit: String::new(), + pool_vram_memory: String::new(), + pool_ram_memory: String::new(), kv_cache_limit: "context".into(), host: "127.0.0.1".into(), port: 8000, @@ -84,6 +88,8 @@ impl RuntimeSettings { self.bind()?; for (name, value) in [ ("memory limit", &self.memory_limit), + ("VRAM pool memory", &self.pool_vram_memory), + ("RAM pool memory", &self.pool_ram_memory), ("KV limit", &self.kv_cache_limit), ("prefix memory", &self.prefix_cache_memory), ("prefix disk limit", &self.prefix_cache_disk_limit), @@ -105,6 +111,12 @@ impl RuntimeSettings { if !self.memory_limit.trim().is_empty() { base.memory_limit = Some(self.memory_limit.parse::()?); } + if !self.pool_vram_memory.trim().is_empty() { + base.pool_vram_limit = Some(self.pool_vram_memory.parse::()?); + } + if !self.pool_ram_memory.trim().is_empty() { + base.pool_ram_limit = Some(self.pool_ram_memory.parse::()?); + } base.kv_cache_limit = self.kv_cache_limit.trim().parse::()?; if let Some(n) = self.max_concurrency { base.max_concurrency = Some(n); @@ -166,6 +178,8 @@ pub(crate) struct RuntimeIdentity { verify_weights: bool, kv_cache_limit: KvCacheLimit, memory_limit: Option, + pool_vram_limit: Option, + pool_ram_limit: Option, max_concurrency: Option, mtp_draft_tokens: Option, adaptive_verification: Option, @@ -181,6 +195,8 @@ impl RuntimeIdentity { verify_weights: runtime.verify_weights, kv_cache_limit: options.kv_cache_limit, memory_limit: options.memory_limit, + pool_vram_limit: options.pool_vram_limit, + pool_ram_limit: options.pool_ram_limit, max_concurrency: options.max_concurrency, mtp_draft_tokens: options.mtp_draft_tokens, adaptive_verification: options.adaptive_verification, diff --git a/heliopause/src/export/binding.rs b/heliopause/src/export/binding.rs index e1338e1c5..8c30aae9c 100644 --- a/heliopause/src/export/binding.rs +++ b/heliopause/src/export/binding.rs @@ -443,6 +443,240 @@ pub(crate) fn execution( ); } } + if let Some(channels) = object.get("async_transfers").cloned() { + if channels.is_null() { + object.remove("async_transfers"); + } else { + let channels = channels + .as_array() + .ok_or_else(|| super::invalid("async_transfers must be an array"))?; + let buffers = object + .get("buffers") + .and_then(|v| v.as_array()) + .ok_or_else(|| super::invalid("execution buffers must be an array"))?; + let resolve_ref = |expected_memory: &str, + label: &str, + ref_obj: &serde_json::Map, + nbytes: u64, + alignment: u64| + -> super::Result { + let target_name = ref_obj + .get("allocation") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .ok_or_else(|| { + super::invalid(format!("async transfer {label} requires an allocation name")) + })?; + let offset = match ref_obj.get("offset") { + None => 0, + Some(v) => v.as_u64().ok_or_else(|| { + super::invalid(format!( + "async transfer {label} offset must be a nonnegative integer" + )) + })?, + }; + let (resolved_alloc, resolved_off) = if let Some(buf) = buffers + .iter() + .find(|b| b.get("name").and_then(|n| n.as_str()) == Some(target_name)) + { + let buf_nbytes = buf.get("nbytes").and_then(|v| v.as_u64()).ok_or_else(|| { + super::invalid(format!("async transfer {label} buffer lacks nbytes")) + })?; + let end = offset.checked_add(nbytes).ok_or_else(|| { + super::invalid(format!("async transfer {label} offset overflow")) + })?; + if end > buf_nbytes { + return Err(super::invalid(format!( + "async transfer {label} range exceeds registered buffer" + ))); + } + let reference = buf + .get("reference") + .and_then(|v| v.as_object()) + .ok_or_else(|| { + super::invalid(format!( + "async transfer {label} buffer lacks allocation reference" + )) + })?; + let alloc_name = reference + .get("allocation") + .and_then(|v| v.as_str()) + .ok_or_else(|| { + super::invalid(format!( + "async transfer {label} reference lacks allocation name" + )) + })?; + let alloc_offset = reference + .get("offset") + .and_then(|v| v.as_u64()) + .ok_or_else(|| { + super::invalid(format!( + "async transfer {label} reference lacks offset" + )) + })?; + let alloc = allocations + .iter() + .find(|a| a.name == alloc_name) + .ok_or_else(|| { + super::invalid(format!("async transfer {label} allocation not found")) + })?; + if alloc.memory != expected_memory || alloc.sizing.is_some() { + return Err(super::invalid(format!( + "async transfer {label} must reside in a fixed {expected_memory} allocation" + ))); + } + let final_offset = alloc_offset.checked_add(offset).ok_or_else(|| { + super::invalid(format!("async transfer {label} offset overflow")) + })?; + let final_end = final_offset.checked_add(nbytes).ok_or_else(|| { + super::invalid(format!("async transfer {label} offset overflow")) + })?; + if final_end > alloc.nbytes { + return Err(super::invalid(format!( + "async transfer {label} range exceeds allocation" + ))); + } + (alloc_name.to_owned(), final_offset) + } else if let Some(alloc) = allocations.iter().find(|a| a.name == target_name) { + if alloc.memory != expected_memory || alloc.sizing.is_some() { + return Err(super::invalid(format!( + "async transfer {label} must reside in a fixed {expected_memory} allocation" + ))); + } + let end = offset.checked_add(nbytes).ok_or_else(|| { + super::invalid(format!("async transfer {label} offset overflow")) + })?; + if end > alloc.nbytes { + return Err(super::invalid(format!( + "async transfer {label} range exceeds allocation" + ))); + } + (target_name.to_owned(), offset) + } else { + return Err(super::invalid(format!( + "async transfer references unknown {label} buffer or allocation" + ))); + }; + if resolved_off % alignment != 0 { + return Err(super::invalid(format!( + "async transfer {label} offset must be {alignment}-byte aligned" + ))); + } + Ok(serde_json::json!({ + "allocation": resolved_alloc, + "offset": resolved_off, + })) + }; + let mut seen_names = std::collections::BTreeSet::new(); + let mut resolved = Vec::with_capacity(channels.len()); + for channel in channels { + let mut ch_obj = channel + .as_object() + .ok_or_else(|| super::invalid("async transfer entry must be an object"))? + .clone(); + let name = ch_obj + .get("name") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .ok_or_else(|| super::invalid("async transfer channel requires a nonempty name"))? + .to_owned(); + if !seen_names.insert(name) { + return Err(super::invalid("duplicate async transfer channel name")); + } + let pool_name = ch_obj + .get("device_pool") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .ok_or_else(|| super::invalid("async transfer channel requires device_pool"))?; + let pool_alloc = allocations + .iter() + .find(|a| a.name == pool_name) + .ok_or_else(|| { + super::invalid("async transfer device_pool allocation not found") + })?; + let is_device_pool = pool_alloc.memory == "device" + && pool_alloc.sizing.as_ref().is_some_and(|s| { + s.get("capacity").is_some_and(|c| { + c.as_str() == Some("DEVICE_POOL") || c.as_u64() == Some(2) + }) + }); + if !is_device_pool { + return Err(super::invalid( + "async transfer device_pool must reference a Capacity::DEVICE_POOL allocation", + )); + } + let ring_capacity = ch_obj + .get("ring_capacity") + .and_then(|v| v.as_u64()) + .ok_or_else(|| super::invalid("async transfer ring_capacity is required"))?; + if ring_capacity < u64::from(helios_core::async_transfer::MIN_RING_CAPACITY) + || ring_capacity > u64::from(helios_core::async_transfer::MAX_RING_CAPACITY) + || !ring_capacity.is_power_of_two() + { + return Err(super::invalid( + "async transfer ring_capacity must be a power of two in [16, 4096]", + )); + } + let completion_slots = ch_obj + .get("completion_slots") + .and_then(|v| v.as_u64()) + .ok_or_else(|| super::invalid("async transfer completion_slots is required"))?; + if completion_slots == 0 || completion_slots > u32::MAX as u64 { + return Err(super::invalid( + "async transfer completion_slots must be a positive uint32", + )); + } + let alignment = ch_obj + .get("alignment") + .and_then(|v| v.as_u64()) + .ok_or_else(|| super::invalid("async transfer alignment is required"))?; + if alignment < 4096 || alignment > u32::MAX as u64 || !alignment.is_power_of_two() { + return Err(super::invalid( + "async transfer alignment must be a power of two >= 4096", + )); + } + let min_control = helios_core::async_transfer::required_control_bytes( + ring_capacity as u32, + completion_slots as u32, + ) + .ok_or_else(|| super::invalid("async transfer control size overflow"))?; + let control_bytes = ch_obj + .get("control_bytes") + .and_then(|v| v.as_u64()) + .ok_or_else(|| super::invalid("async transfer control_bytes is required"))?; + if control_bytes < min_control { + return Err(super::invalid( + "async transfer control_bytes is smaller than header, ring, and completion slots", + )); + } + let control_obj = ch_obj + .get("control") + .and_then(|v| v.as_object()) + .ok_or_else(|| super::invalid("async transfer requires a control reference"))?; + let resolved_ctrl = + resolve_ref("mapped_host", "control", control_obj, control_bytes, 64)?; + ch_obj.insert("control".into(), resolved_ctrl); + if let Some(comp_val) = ch_obj.get("device_completions").filter(|v| !v.is_null()).cloned() { + let comp_obj = comp_val.as_object().ok_or_else(|| { + super::invalid("async transfer device_completions must be an object") + })?; + let comp_bytes = completion_slots.checked_mul(8).ok_or_else(|| { + super::invalid("async transfer device_completions size overflow") + })?; + let resolved_comp = + resolve_ref("device", "device_completions", comp_obj, comp_bytes, 8)?; + ch_obj.insert("device_completions".into(), resolved_comp); + } else { + ch_obj.remove("device_completions"); + } + resolved.push(serde_json::Value::Object(ch_obj)); + } + object.insert( + "async_transfers".into(), + serde_json::Value::Array(resolved), + ); + } + } message("Execution", &value) } @@ -1283,6 +1517,103 @@ mod tests { assert!(execution(&bad_tune_collision, &allocs).is_err()); } + #[test] + fn async_transfers_export_resolves_references_and_rejects_invalid() { + let allocs = vec![ + super::super::Allocation { + name: "host-0".into(), + address: 0x10000, + nbytes: 16384, + alignment: 4096, + initialize: "zero".into(), + relocations: vec![], + preserve_address: true, + memory: "mapped_host".into(), + snapshot_spans: None, + sizing: None, + }, + super::super::Allocation { + name: "dev-pool".into(), + address: 0x200000, + nbytes: 0, + alignment: 2 << 20, + initialize: "zero".into(), + relocations: vec![], + preserve_address: true, + memory: "device".into(), + snapshot_spans: None, + sizing: Some(serde_json::json!({ + "capacity": "DEVICE_POOL", + "unit_bytes": 2 << 20, + "maximum": 64 + })), + }, + super::super::Allocation { + name: "dev-fixed".into(), + address: 0x40000, + nbytes: 4096, + alignment: 256, + initialize: "zero".into(), + relocations: vec![], + preserve_address: false, + memory: "device".into(), + snapshot_spans: None, + sizing: None, + }, + ]; + let min_ctrl = helios_core::async_transfer::required_control_bytes(64, 32).unwrap(); + let valid = serde_json::json!({ + "abi_version": 6, + "max_active": 1, + "input_frame_bytes": 16, + "buffers": [ + {"name": "xfer_ctrl", "address": 0x10040, "nbytes": 8192, "dtype": "uint8", "shape": [8192], "strides": [1]}, + {"name": "xfer_comp", "address": 0x40010, "nbytes": 512, "dtype": "uint64", "shape": [64], "strides": [1]} + ], + "graphs": [{"name": "decode", "kind": "decode", "batch_capacity": 1, "token_capacity": 1, "input_bindings": []}], + "async_transfers": [{ + "name": "weights", + "device_pool": "dev-pool", + "control": {"allocation": "xfer_ctrl", "offset": 64}, + "control_bytes": min_ctrl, + "device_completions": {"allocation": "xfer_comp", "offset": 16}, + "completion_slots": 32, + "ring_capacity": 64, + "max_host_pool_bytes": 1 << 30, + "alignment": 4096 + }] + }); + let encoded = execution(&valid, &allocs).unwrap(); + assert_eq!(encoded.async_transfers.len(), 1); + let ch = &encoded.async_transfers[0]; + assert_eq!(ch.name, "weights"); + assert_eq!(ch.device_pool, "dev-pool"); + assert_eq!(ch.control.as_ref().unwrap().allocation, "host-0"); + assert_eq!(ch.control.as_ref().unwrap().offset, 0x40 + 64); + assert_eq!(ch.device_completions.as_ref().unwrap().allocation, "dev-fixed"); + assert_eq!(ch.device_completions.as_ref().unwrap().offset, 0x10 + 16); + + // Non-DEVICE_POOL pool must be rejected. + let mut bad_pool = valid.clone(); + bad_pool["async_transfers"][0]["device_pool"] = serde_json::json!("dev-fixed"); + assert!(execution(&bad_pool, &allocs).is_err()); + + // Control on device memory must be rejected. + let mut bad_ctrl = valid.clone(); + bad_ctrl["async_transfers"][0]["control"]["allocation"] = serde_json::json!("xfer_comp"); + assert!(execution(&bad_ctrl, &allocs).is_err()); + + // Control bytes below header + ring + completion slots must be rejected. + let mut bad_size = valid.clone(); + bad_size["async_transfers"][0]["control_bytes"] = serde_json::json!(min_ctrl - 8); + assert!(execution(&bad_size, &allocs).is_err()); + + // Unaligned device_completions offset must be rejected. + let mut bad_comp_align = valid.clone(); + bad_comp_align["async_transfers"][0]["device_completions"]["offset"] = serde_json::json!(4); + assert!(execution(&bad_comp_align, &allocs).is_err()); + } + fn rebuild_catalog() -> (super::super::wire::RebuildWeights, Vec) { use super::super::wire; (wire::RebuildWeights { @@ -1357,7 +1688,7 @@ mod tests { }, allocations: vec![serde_json::from_value(serde_json::json!({"name":"weights","address":4096,"nbytes":64})).unwrap()], payload: vec![], module_globals: vec![], external: vec![], staging: None, - weight_payload: None, + weight_payload: None, external_extents: vec![], }; let mut valid = output.clone(); finish_rank(&request, &mut valid).unwrap(); diff --git a/heliopause/src/export/capture.rs b/heliopause/src/export/capture.rs index a783e39fb..e446bc1f6 100644 --- a/heliopause/src/export/capture.rs +++ b/heliopause/src/export/capture.rs @@ -3248,6 +3248,7 @@ pub(crate) fn capture_rank( staging: Some(stage.path.clone()), weight_payload: None, hardware: None, + external_extents: vec![], payload_leases: Default::default(), }; let mut roots = request.roots.clone(); @@ -3269,7 +3270,69 @@ pub(crate) fn capture_rank( if let Some(execution) = &request.execution { let execution = super::binding::execution(execution, &allocations)?; reach.execution(&execution)?; + if !request.external_extents.is_empty() { + let mut seen_channels = BTreeSet::new(); + for ext in &request.external_extents { + if !seen_channels.insert(ext.channel.clone()) { + return Err(invalid(format!( + "duplicate external_extents table for channel {:?}", + ext.channel + ))); + } + let channel = execution + .async_transfers + .iter() + .find(|ch| ch.name == ext.channel) + .ok_or_else(|| { + invalid(format!( + "external_extents references unknown async transfer channel {:?}", + ext.channel + )) + })?; + if ext.segments.is_empty() { + return Err(invalid(format!( + "external_extents channel {:?} requires at least one segment", + ext.channel + ))); + } + let dir_bytes = fs::read(&ext.directory).map_err(|e| { + invalid(format!( + "read external extent directory {}: {e}", + ext.directory.display() + )) + })?; + let mut resolved_segments = Vec::with_capacity(ext.segments.len()); + let align = u64::from(channel.alignment); + for (seg_idx, seg_path) in ext.segments.iter().enumerate() { + let meta = fs::metadata(seg_path).map_err(|e| { + invalid(format!( + "stat external extent segment {}: {e}", + seg_path.display() + )) + })?; + let len = meta.len(); + if len == 0 || len % align != 0 { + return Err(invalid(format!( + "external extent segment {} length {len} must be a positive multiple of {align}", + seg_path.display() + ))); + } + resolved_segments.push((seg_idx as u32, 0u64, len)); + } + helios_core::async_transfer::decode_extent_directory( + &dir_bytes, + &resolved_segments, + channel.alignment, + ) + .map_err(invalid)?; + } + output.external_extents = request.external_extents.clone(); + } output.index.ranks[0].execution = Some(execution); + } else if !request.external_extents.is_empty() { + return Err(invalid( + "external_extents requires an execution manifest with matching async_transfers", + )); } let mut other_resources = Vec::new(); let graph_phase = progress.phase("Serialize CUDA graphs", Some(request.graphs.len() as u64)); @@ -3783,6 +3846,7 @@ mod tests { external: vec![], staging: Some(directory.join("stage")), weight_payload: None, + external_extents: vec![], }; fs::create_dir_all(directory.join("stage"))?; Ok((request, output)) diff --git a/heliopause/src/export/core.rs b/heliopause/src/export/core.rs index 40b8d9e9d..bc2aa7f61 100644 --- a/heliopause/src/export/core.rs +++ b/heliopause/src/export/core.rs @@ -222,6 +222,9 @@ struct Sources { /// Platform identity detected on the preparing device. #[serde(default)] hardware: Option, + /// External 4 KiB-aligned extent tables published per rank for `Execution.async_transfers`. + #[serde(default)] + external_extents: Vec, } pub(crate) fn write_sources(path: &Path, rank: &RankOutput) -> Result<()> { let length = validate_payload(&rank.payload)?; @@ -236,6 +239,7 @@ pub(crate) fn write_sources(path: &Path, rank: &RankOutput) -> Result<()> { payload: rank.payload.clone(), weight_payload: rank.weight_payload.clone(), hardware: rank.hardware.clone(), + external_extents: rank.external_extents.clone(), }, )?; output.flush()?; @@ -285,6 +289,7 @@ pub(crate) fn read_sources(path: &Path) -> Result { external: vec![], staging: None, weight_payload: record.weight_payload, + external_extents: record.external_extents, }) } pub(crate) fn validate_payload(parts: &[FilePart]) -> Result { @@ -558,6 +563,7 @@ fn export_write_sources( external: vec![], staging: None, weight_payload, + external_extents: vec![], }, ) }) @@ -2149,6 +2155,76 @@ fn rank_plan( attributes: function.attributes.clone(), }) .collect(); + let mut external_extents = Vec::with_capacity(rank.external_extents.len()); + for ext in &rank.external_extents { + let safe_ch = safe_group(&ext.channel)?; + let dir_nbytes = fs::metadata(&ext.directory)?.len(); + let dir_id = stream_pieces( + &[FileSource { + path: ext.directory.clone(), + offset: 0, + nbytes: dir_nbytes, + }], + None, + )?; + let dir_relative = format!( + "deployments/{deployment_id}/rank-{rank_index}/extents-{safe_ch}-dir.safetensors" + ); + payloads.push(payload_export::PublishPayload { + role: pwire::PayloadRole::Weights, + relative: dir_relative, + source: payload_export::pin_file(&ext.directory, dir_nbytes)?, + id: dir_id, + tensor: None, + }); + let mut segment_uses = Vec::with_capacity(ext.segments.len()); + for (seg_idx, seg_path) in ext.segments.iter().enumerate() { + let seg_nbytes = fs::metadata(seg_path)?.len(); + let seg_id = stream_pieces( + &[FileSource { + path: seg_path.clone(), + offset: 0, + nbytes: seg_nbytes, + }], + None, + )?; + let seg_relative = if canonical { + format!("weights/extents-{safe_ch}-seg-{seg_idx}.safetensors") + } else { + format!( + "weights/tp{tensor_parallel}/rank-{rank_index}/extents-{safe_ch}-seg-{seg_idx}.safetensors" + ) + }; + payloads.push(payload_export::PublishPayload { + role: pwire::PayloadRole::Weights, + relative: seg_relative, + source: payload_export::pin_file(seg_path, seg_nbytes)?, + id: seg_id, + tensor: None, + }); + segment_uses.push(pwire::PayloadUse { + slice: Some(pwire::PayloadSlice { + payload_id: seg_id.as_bytes().to_vec(), + offset: 0, + nbytes: seg_nbytes, + }), + role: pwire::PayloadRole::Weights as i32, + }); + } + external_extents.push(pwire::ExternalExtentTable { + channel: ext.channel.clone(), + directory: Some(pwire::PayloadUse { + slice: Some(pwire::PayloadSlice { + payload_id: dir_id.as_bytes().to_vec(), + offset: 0, + nbytes: dir_nbytes, + }), + role: pwire::PayloadRole::Weights as i32, + }), + segments: segment_uses, + }); + } + payload_export::coalesce_initializers(&mut initializers)?; let mut body = pwire::RankBody { rank: rank_index, @@ -2168,6 +2244,7 @@ fn rank_plan( roce: bundle.roce.clone(), prepared_weights: prepared, compressed_prepared_weights: None, + external_extents, }; helios_core::core::prepared_weights::compact(&mut body)?; Ok(payload_export::PublishRank { @@ -2777,6 +2854,7 @@ mod payload_export_tests { external: vec![], staging: None, weight_payload: None, + external_extents: vec![], } } @@ -4945,6 +5023,7 @@ mod payload_export_tests { external: Vec::new(), staging: None, weight_payload: None, + external_extents: Vec::new(), }; let mut engram_rank = bare_rank.clone(); engram_rank.index.engram = Some(engram); @@ -5538,6 +5617,7 @@ mod payload_export_tests { external: vec![], staging: None, weight_payload: None, + external_extents: vec![], } } diff --git a/heliopause/src/export/mod.rs b/heliopause/src/export/mod.rs index d1e76e18c..1bdebae7a 100644 --- a/heliopause/src/export/mod.rs +++ b/heliopause/src/export/mod.rs @@ -156,6 +156,13 @@ pub(crate) enum DeviceIdentity { None, } +#[derive(Clone, Debug, Deserialize, Serialize)] +pub(crate) struct ExternalExtentInput { + pub channel: String, + pub directory: PathBuf, + pub segments: Vec, +} + #[derive(Clone, Debug, Deserialize, Serialize)] pub(crate) struct CaptureRequest { pub path: PathBuf, @@ -204,6 +211,8 @@ pub(crate) struct CaptureRequest { #[serde(default)] pub device_identity: DeviceIdentity, pub execution: Option, + #[serde(default)] + pub external_extents: Vec, pub server: Option, #[serde(default)] pub transports: Vec, @@ -373,6 +382,9 @@ pub(crate) struct RankOutput { /// Platform identifier detected from the capture device. #[serde(default)] pub hardware: Option, + /// External 4 KiB-aligned extent tables published per rank for `Execution.async_transfers`. + #[serde(default)] + pub external_extents: Vec, /// Live object leases; serialized rank sources carry none. #[serde(skip)] pub payload_leases: PayloadLeases, diff --git a/heliopause/src/export/reachability.rs b/heliopause/src/export/reachability.rs index 94d3cfaa3..2409f9836 100644 --- a/heliopause/src/export/reachability.rs +++ b/heliopause/src/export/reachability.rs @@ -102,6 +102,15 @@ impl Reachability { self.reference(&metrics.allocation)?; } } + for channel in &execution.async_transfers { + self.reference(&channel.device_pool)?; + if let Some(control) = &channel.control { + self.reference(&control.allocation)?; + } + if let Some(completions) = &channel.device_completions { + self.reference(&completions.allocation)?; + } + } Ok(()) } diff --git a/heliopause/src/export/transfer.rs b/heliopause/src/export/transfer.rs index d6418c54e..72286157f 100644 --- a/heliopause/src/export/transfer.rs +++ b/heliopause/src/export/transfer.rs @@ -1352,6 +1352,7 @@ mod tests { external: vec![], staging: None, weight_payload: None, + external_extents: vec![], } } fn roundtrip( @@ -2229,6 +2230,7 @@ mod tests { }], engram: None, }), + external_extents: vec![], payload_leases: Default::default(), }; diff --git a/heliopause/src/export/weight_reuse.rs b/heliopause/src/export/weight_reuse.rs index c92400f08..551b361f4 100644 --- a/heliopause/src/export/weight_reuse.rs +++ b/heliopause/src/export/weight_reuse.rs @@ -976,6 +976,7 @@ mod tests { staging: None, weight_payload: None, hardware: None, + external_extents: vec![], payload_leases: Default::default(), }; output.index.ranks.push(wire::BundleIndex { @@ -1148,6 +1149,7 @@ mod tests { staging: None, weight_payload: None, hardware: None, + external_extents: vec![], payload_leases: Default::default(), }; output.index.ranks.push(wire::BundleIndex { diff --git a/heliopause/src/python.rs b/heliopause/src/python.rs index 4c50a33de..333e2f045 100644 --- a/heliopause/src/python.rs +++ b/heliopause/src/python.rs @@ -311,6 +311,18 @@ pub(crate) fn execution_manifest(value: &Bound<'_, PyAny>) -> PyResult(value.py()) => {} Err(error) => return Err(error), } + match value.get_item("async_transfers") { + Ok(channels) if !channels.is_none() => { + if channels.try_iter()?.next().is_some() { + return Err(PyValueError::new_err( + "async transfer channels require native core serving (export a core and serve with flare run)", + )); + } + } + Ok(_) => {} + Err(error) if error.is_instance_of::(value.py()) => {} + Err(error) => return Err(error), + } Ok(ExecutionManifest { collectives: None, engram: crate::embedding_tables::binding(value)?, diff --git a/helios/build.rs b/helios/build.rs index 3a2b941a8..34c047d39 100644 --- a/helios/build.rs +++ b/helios/build.rs @@ -43,6 +43,18 @@ fn main() { ".flare.runtime.Execution.persistent_workers", "#[serde(default)]", ) + .field_attribute( + ".flare.runtime.Execution.async_transfers", + "#[serde(default)]", + ) + .field_attribute( + ".flare.runtime.AsyncTransfer.device_completions", + "#[serde(default)]", + ) + .field_attribute( + ".flare.runtime.AsyncTransfer.extents", + "#[serde(default)]", + ) .field_attribute( ".flare.runtime.PersistentWorker.metrics", "#[serde(default)]", diff --git a/helios/manifest.md b/helios/manifest.md index 9ed32fc39..06f40381e 100644 --- a/helios/manifest.md +++ b/helios/manifest.md @@ -150,6 +150,60 @@ pruning. In-process Python execution (`GraphExecutor`, explicitly; persistent workers run only through exported cores served by `flare run`. +## Asynchronous extent transfers + +An execution catalog may optionally declare `Execution.async_transfers` +(repeated Protobuf message `AsyncTransfer`, field 9) alongside one or more +runtime-sized `Capacity::DEVICE_POOL` allocations and authenticated +`RankBody.external_extents` tables (repeated `ExternalExtentTable`, field 18 of +`RankBody`). Each `AsyncTransfer` channel connects a model's captured CUDA +graphs to a stateless, domain-agnostic host transfer worker that copies +4 KiB-aligned read-only extents from core storage (`O_DIRECT` + `io_uring` on +Linux, `pread` elsewhere) through an optional runtime-sized pinned host byte +pool (`HOST_POOL`) and a dedicated non-blocking CUDA Copy Engine stream into a +`Capacity::DEVICE_POOL` device byte pool (`DEVICE_POOL`). + +Each `AsyncTransfer` entry declares: + +- `name`: unique nonempty channel name on the rank. +- `device_pool`: name of a fixed-VA `Capacity::DEVICE_POOL` allocation on the + rank, sized at startup from free VRAM and `--pool-vram-memory`. +- `control` and `control_bytes`: 64-byte-aligned `Reference` inside a fixed + `Memory::MappedHost` allocation holding a 256-byte `ControlHeader` (four + cache lines: startup geometry, producer doorbells `cmd_tail`/`active_epoch`, + consumer progress `cmd_head`/`worker_state`/`last_error`, and lock-free + telemetry counters), a power-of-two ring of 64-byte `TransferCommand` slots + (`ring_capacity` in `[16, 4096]`), and `completion_slots` 64-bit host + completion words. +- `device_completions` (optional): 8-byte-aligned `Reference` inside a fixed + `Memory::Device` allocation holding `completion_slots` 64-bit completion + words written in stream order by `cuStreamWriteValue64_v2` (when device + attribute `CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS = 122` is + supported) after Copy Engine DMA completes. +- `max_host_pool_bytes`: optional ceiling on the channel's pinned host pool + (`0` allows up to the runtime `--pool-ram-memory` budget). +- `alignment`: power-of-two direct-I/O and offset alignment (`>= 4096`). + +Supported command opcodes are `DISK_TO_HOST` (`1`), `HOST_TO_DEV` (`2`), +`DISK_TO_DEV` (`3`, supporting either a caller host offset or sentinel +`u64::MAX` for internal pinned bounce staging when `host_pool_bytes == 0`), and +`CANCEL_EPOCH` (`4`). Priorities `DEMAND` (`0`), `PREFETCH` (`1`), and `WARM` +(`2`) feed a preemptible host queue with bounded background I/O and DMA depth; +`CANCEL_EPOCH` and `ControlHeader.active_epoch` drop queued non-demand commands +from older epochs while preserving `DEMAND`. Helios starts prepared channels +before launching `Execution.tuning_graphs` so startup tuning kernels can read +`device_pool_bytes` and `host_pool_bytes` from `ControlHeader` and partition or +pre-warm pools. Teardown drains serving streams, cancels queued background +transfers, drains in-flight storage I/O and the Copy Engine stream within a +bounded timeout, and retains pinned host memory and CUDA handles until process +exit if drain is not confirmed. + +Helios implements no model-specific routing, eviction, prefetch policy, or +cache directory layout inside `AsyncTransfer`; captured graphs own all slot +mapping and policy state. In-process Python execution rejects manifests with +`async_transfers`; async transfer channels run only through exported cores +served by `flare run`. + Execution ABI numbers are descriptive metadata and do not gate loading or rank agreement. Every engine version loads the core layouts that earlier versions supported. The diff --git a/helios/proto/core.proto b/helios/proto/core.proto index 18bf63ada..e7e09c38f 100644 --- a/helios/proto/core.proto +++ b/helios/proto/core.proto @@ -173,6 +173,16 @@ message RankBody { flare.runtime.RoceTransport roce = 15; PreparedWeightCatalog prepared_weights = 16; CompressedPreparedWeightCatalog compressed_prepared_weights = 17; + // Authenticated read-only byte extents addressed by index through `Execution.async_transfers`. + repeated ExternalExtentTable external_extents = 18; +} + +// Authenticated backing segments and packed extent directory for one `AsyncTransfer` channel. +// Each directory entry is 24 little-endian bytes: `[u32 segment_index, u32 reserved, u64 offset, u64 nbytes]`. +message ExternalExtentTable { + string channel = 1; + repeated PayloadUse segments = 2; + PayloadUse directory = 3; } message Allocation { diff --git a/helios/proto/runtime_core.proto b/helios/proto/runtime_core.proto index 54ad04c70..3b0ed0d62 100644 --- a/helios/proto/runtime_core.proto +++ b/helios/proto/runtime_core.proto @@ -778,7 +778,7 @@ message Allocation { Memory memory = 8; Sizing sizing = 9; } -enum Capacity { STATE_ROWS = 0; KV_PAGES = 1; } +enum Capacity { STATE_ROWS = 0; KV_PAGES = 1; DEVICE_POOL = 2; } message Sizing { Capacity capacity = 1; uint64 unit_bytes = 2; uint64 maximum = 3; } message Module { string name = 1; string file = 2; repeated Global globals = 3; } message Global { string symbol = 1; string file = 2; uint64 nbytes = 3; repeated Relocation relocations = 4; } @@ -834,6 +834,31 @@ message Execution { uint32 completion_token_capacity = 7; // Optional dedicated worker graphs launched once on partitioned CUDA green contexts. repeated PersistentWorker persistent_workers = 8; + // Optional stateless host-driven byte-copy channels between authenticated external + // extents, a runtime-sized host pool, and a device pool allocation. + repeated AsyncTransfer async_transfers = 9; +} +message AsyncTransfer { + // Channel name, nonempty and unique within the rank. + string name = 1; + // Target device allocation name (fixed or runtime-sized with Capacity::DEVICE_POOL). + string device_pool = 2; + // Mapped-host control header, command ring, telemetry counters, and host completion slots. + Reference control = 3; + uint64 control_bytes = 4; + // Optional device allocation range holding `completion_slots` 64-bit completion words + // written on the copy stream via `cuStreamWriteValue64` when supported. + Reference device_completions = 5; + uint32 completion_slots = 6; + // Command ring slot count (power of two, 16..=4096). + uint32 ring_capacity = 7; + // Upper bound on the runtime-sized host pool in bytes (zero disables the host pool). + uint64 max_host_pool_bytes = 8; + // Required byte alignment for extent reads and pool offsets (power of two, at least 4096). + uint32 alignment = 9; + // Legacy-core backing extents addressed by zero-based index; payload-format cores + // supply authenticated extents through `RankBody.external_extents`. + repeated Span extents = 10; } message PersistentWorker { uint32 worker_sm_count = 1; diff --git a/helios/src/async_transfer/io_backend.rs b/helios/src/async_transfer/io_backend.rs new file mode 100644 index 000000000..41619d05d --- /dev/null +++ b/helios/src/async_transfer/io_backend.rs @@ -0,0 +1,292 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +//! Direct-I/O storage backend for `AsyncTransfer`: Linux `io_uring` with registered files, +//! and a cross-platform `pread` fallback for non-Linux hosts and unit tests. + +use std::{ + fs::File, + io, + time::{Duration, Instant}, +}; + +use super::scheduler::OpId; + +/// Result of one completed asynchronous read operation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct IoCompletion { + pub op_id: OpId, + pub ok: bool, +} + +/// Non-blocking direct-I/O reader driving storage transfers into pinned host memory. +pub trait IoBackend: Send { + /// Enqueue one aligned read of `nbytes` bytes from `file_index` at `file_offset` into `dst`. + /// + /// # Safety + /// `dst` must point to at least `nbytes` writable, aligned bytes that remain live and + /// unaliased until a matching [`IoCompletion`] is harvested or [`Self::cancel_and_drain`] + /// returns `true`. + unsafe fn submit_read( + &mut self, + op_id: OpId, + file_index: u32, + file_offset: u64, + dst: *mut u8, + nbytes: u64, + ) -> io::Result<()>; + + /// Flush any locally staged submission entries to the kernel without blocking. + fn flush(&mut self) -> io::Result<()>; + + /// Harvest all currently completed I/O operations without blocking. + fn poll_completions(&mut self, out: &mut Vec) -> io::Result<()>; + + /// Number of submitted reads whose completion has not yet been harvested. + fn in_flight(&self) -> usize; + + /// Cancel and drain all in-flight reads within `timeout`, appending every harvested + /// completion to `out`. Returns `true` iff `in_flight() == 0`. + fn cancel_and_drain(&mut self, timeout: Duration, out: &mut Vec) -> bool; +} + +#[cfg(target_os = "linux")] +pub mod linux_uring { + use super::*; + use io_uring::{IoUring, opcode, types}; + use std::{collections::HashMap, os::fd::AsRawFd}; + + const RING_ENTRIES: u32 = 128; + + /// Linux `io_uring` direct-I/O reader with registered fixed file descriptors. + pub struct IoUringBackend { + ring: IoUring, + _files: Vec, + registered_files: bool, + raw_fds: Vec, + expected: HashMap, + queued_sqes: usize, + } + + // SAFETY: One worker thread exclusively owns `IoUringBackend`, its file handles, and its ring. + unsafe impl Send for IoUringBackend {} + + impl IoUringBackend { + /// Construct a new `io_uring` backend from direct-I/O opened files. + pub fn new(files: Vec) -> io::Result { + let ring = IoUring::new(RING_ENTRIES)?; + let raw_fds: Vec = files.iter().map(AsRawFd::as_raw_fd).collect(); + let registered_files = if raw_fds.is_empty() { + false + } else { + ring.submitter().register_files(&raw_fds).is_ok() + }; + Ok(Self { + ring, + _files: files, + registered_files, + raw_fds, + expected: HashMap::new(), + queued_sqes: 0, + }) + } + + fn push_read_sqe( + &mut self, + op_id: OpId, + file_index: u32, + file_offset: u64, + dst: *mut u8, + nbytes: u32, + ) -> io::Result<()> { + let entry = if self.registered_files { + opcode::Read::new(types::Fixed(file_index), dst, nbytes) + .offset(file_offset) + .build() + .user_data(op_id) + } else { + let fd = *self + .raw_fds + .get(file_index as usize) + .ok_or(io::ErrorKind::InvalidInput)?; + opcode::Read::new(types::Fd(fd), dst, nbytes) + .offset(file_offset) + .build() + .user_data(op_id) + }; + // Flush once if the submission queue is momentarily full. + if self.ring.submission().is_full() { + self.flush()?; + } + // SAFETY: Caller guarantees `dst..dst+nbytes` stays live until completion or drain. + unsafe { + self.ring + .submission() + .push(&entry) + .map_err(|_| io::Error::new(io::ErrorKind::WouldBlock, "io_uring SQ full"))?; + } + self.queued_sqes += 1; + Ok(()) + } + } + + impl IoBackend for IoUringBackend { + unsafe fn submit_read( + &mut self, + op_id: OpId, + file_index: u32, + file_offset: u64, + dst: *mut u8, + nbytes: u64, + ) -> io::Result<()> { + if (file_index as usize) >= self.raw_fds.len() { + return Err(io::ErrorKind::InvalidInput.into()); + } + let len_u32 = u32::try_from(nbytes).map_err(|_| io::ErrorKind::InvalidInput)?; + self.push_read_sqe(op_id, file_index, file_offset, dst, len_u32)?; + self.expected.insert(op_id, nbytes); + Ok(()) + } + + fn flush(&mut self) -> io::Result<()> { + if self.queued_sqes == 0 { + return Ok(()); + } + let submitted = self.ring.submit()?; + self.queued_sqes = self.queued_sqes.saturating_sub(submitted); + Ok(()) + } + + fn poll_completions(&mut self, out: &mut Vec) -> io::Result<()> { + let mut cq = self.ring.completion(); + for cqe in &mut cq { + let op_id = cqe.user_data(); + if op_id == 0 { + // Internal cancel SQE completion. + continue; + } + let expected = self.expected.remove(&op_id); + let result = cqe.result(); + let ok = expected.is_some_and(|want| result >= 0 && (result as u64) == want); + out.push(IoCompletion { op_id, ok }); + } + Ok(()) + } + + fn in_flight(&self) -> usize { + self.expected.len() + } + + fn cancel_and_drain(&mut self, timeout: Duration, out: &mut Vec) -> bool { + let _ = self.flush(); + if !self.expected.is_empty() { + // Request asynchronous cancellation for every pending op. + let pending_ids: Vec = self.expected.keys().copied().collect(); + for op_id in pending_ids { + let cancel = opcode::AsyncCancel::new(op_id).build().user_data(0); + if self.ring.submission().is_full() { + let _ = self.ring.submit(); + } + // SAFETY: AsyncCancel references no caller buffer. + let _ = unsafe { self.ring.submission().push(&cancel) }; + } + let _ = self.ring.submit(); + } + let deadline = Instant::now() + timeout; + while !self.expected.is_empty() { + let _ = self.poll_completions(out); + if self.expected.is_empty() { + break; + } + if Instant::now() >= deadline { + return false; + } + let _ = self.ring.submit_and_wait(1); + } + true + } + } +} + +/// Synchronous `pread`-backed fallback for non-Linux targets and non-`O_DIRECT` unit tests. +pub struct PreadBackend { + files: Vec, + completed: Vec, +} + +impl PreadBackend { + pub fn new(files: Vec) -> Self { + Self { + files, + completed: Vec::new(), + } + } +} + +impl IoBackend for PreadBackend { + unsafe fn submit_read( + &mut self, + op_id: OpId, + file_index: u32, + file_offset: u64, + dst: *mut u8, + nbytes: u64, + ) -> io::Result<()> { + let file = self + .files + .get(file_index as usize) + .ok_or(io::ErrorKind::InvalidInput)?; + let len = usize::try_from(nbytes).map_err(|_| io::ErrorKind::InvalidInput)?; + let mut done = 0usize; + let mut ok = true; + while done < len { + // SAFETY: Caller guarantees `dst..dst+len` is writable for the read duration. + match unsafe { crate::os::read_at_raw(file, dst.add(done), len - done, file_offset + done as u64) } { + Ok(0) => { + ok = false; + break; + } + Ok(n) => done += n, + Err(_) => { + ok = false; + break; + } + } + } + self.completed.push(IoCompletion { op_id, ok }); + Ok(()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + + fn poll_completions(&mut self, out: &mut Vec) -> io::Result<()> { + out.append(&mut self.completed); + Ok(()) + } + + fn in_flight(&self) -> usize { + self.completed.len() + } + + fn cancel_and_drain(&mut self, _timeout: Duration, out: &mut Vec) -> bool { + out.append(&mut self.completed); + true + } +} + +/// Construct the platform [`IoBackend`] from already-opened direct-I/O file handles. +pub fn from_direct_files(files: Vec) -> io::Result> { + #[cfg(target_os = "linux")] + { + Ok(Box::new(linux_uring::IoUringBackend::new(files)?)) + } + #[cfg(not(target_os = "linux"))] + { + Ok(Box::new(PreadBackend::new(files))) + } +} diff --git a/helios/src/async_transfer/kani_proofs.rs b/helios/src/async_transfer/kani_proofs.rs new file mode 100644 index 000000000..d128a7106 --- /dev/null +++ b/helios/src/async_transfer/kani_proofs.rs @@ -0,0 +1,238 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +//! Sequential Kani verification harnesses for `AsyncTransfer` layout, extent, pool-sizing, +//! and command bounds/alignment validators. + +use super::ring::{ + BOUNCE_HOST_OFFSET, COMMAND_BYTES, ErrorCode, ExtentEntry, HEADER_BYTES, MAX_RING_CAPACITY, + MIN_ALIGNMENT, MIN_RING_CAPACITY, NO_COMPLETION_SLOT, Opcode, Priority, TransferCommand, + ValidatedCommand, resolve_pool_bytes, validate_command, validate_control_layout, + validate_extent_entry, +}; + +#[kani::proof] +fn control_layout_matches_u128_oracle() { + let control_bytes: u64 = kani::any(); + let ring_capacity: u32 = kani::any(); + let completion_slots: u32 = kani::any(); + let alignment: u32 = kani::any(); + + let got = validate_control_layout(control_bytes, ring_capacity, completion_slots, alignment); + + let ring_ok = ring_capacity >= MIN_RING_CAPACITY + && ring_capacity <= MAX_RING_CAPACITY + && ring_capacity.is_power_of_two(); + let slots_ok = completion_slots > 0 && completion_slots != NO_COMPLETION_SLOT; + let align_ok = alignment >= MIN_ALIGNMENT && alignment.is_power_of_two(); + let needed: u128 = (HEADER_BYTES as u128) + + (ring_capacity as u128) * (COMMAND_BYTES as u128) + + (completion_slots as u128) * 8u128; + let expected = ring_ok && slots_ok && align_ok && (control_bytes as u128) >= needed; + + assert_eq!(got, expected); +} + +#[kani::proof] +fn extent_entry_matches_u128_oracle() { + let seg_idx: u32 = kani::any(); + let seg_count: u32 = kani::any(); + let offset: u64 = kani::any(); + let nbytes: u64 = kani::any(); + let seg_nbytes: u64 = kani::any(); + let alignment: u32 = kani::any(); + + let got = validate_extent_entry(seg_idx, seg_count, offset, nbytes, seg_nbytes, alignment); + + let align_ok = alignment >= MIN_ALIGNMENT && alignment.is_power_of_two(); + let expected = align_ok + && seg_idx < seg_count + && nbytes > 0 + && (offset % (alignment as u64)) == 0 + && (nbytes % (alignment as u64)) == 0 + && (offset as u128) + (nbytes as u128) <= (seg_nbytes as u128); + + assert_eq!(got, expected); +} + +#[kani::proof] +fn resolve_pool_bytes_is_aligned_and_bounded() { + let available: u64 = kani::any(); + let has_cap: bool = kani::any(); + let cap: u64 = kani::any(); + let max_pool: u64 = kani::any(); + let alignment: u64 = kani::any(); + let requested = if has_cap { Some(cap) } else { None }; + + let got = resolve_pool_bytes(available, requested, max_pool, alignment); + + if alignment == 0 || !alignment.is_power_of_two() || max_pool == 0 { + assert_eq!(got, 0); + } else { + assert_eq!(got % alignment, 0); + assert!(got <= available); + assert!(got <= max_pool); + if let Some(c) = requested { + assert!(got <= c); + } + // Maximality: adding one alignment granule must exceed at least one bound (or overflow). + let next = (got as u128) + (alignment as u128); + let limit = match requested { + Some(c) => (available.min(max_pool).min(c)) as u128, + None => (available.min(max_pool)) as u128, + }; + assert!(next > limit); + } +} + +#[kani::proof] +fn validate_command_guarantees_bounds_and_alignment_for_all_inputs() { + let ext0 = ExtentEntry { + file_index: kani::any(), + offset: kani::any(), + nbytes: kani::any(), + }; + let ext1 = ExtentEntry { + file_index: kani::any(), + offset: kani::any(), + nbytes: kani::any(), + }; + let use_two: bool = kani::any(); + let extents_arr = [ext0, ext1]; + let extents: &[ExtentEntry] = if use_two { + &extents_arr + } else { + &extents_arr[..1] + }; + + let cmd = TransferCommand { + opcode: kani::any(), + priority: kani::any(), + extent_id: kani::any(), + completion_slot: kani::any(), + host_offset: kani::any(), + device_offset: kani::any(), + nbytes: kani::any(), + epoch: kani::any(), + signal_value: kani::any(), + _reserved: kani::any(), + }; + let host_pool_bytes: u64 = kani::any(); + let device_pool_bytes: u64 = kani::any(); + let completion_slots: u32 = kani::any(); + let alignment: u32 = kani::any(); + let bounce_slot_bytes: u64 = kani::any(); + + match validate_command( + &cmd, + extents, + host_pool_bytes, + device_pool_bytes, + completion_slots, + alignment, + bounce_slot_bytes, + ) { + Ok(ValidatedCommand::CancelEpoch { + completion_slot, .. + }) => { + assert_eq!(cmd.opcode, Opcode::CancelEpoch as u32); + if let Some(slot) = completion_slot { + assert!(slot < completion_slots); + } else { + assert_eq!(cmd.completion_slot, NO_COMPLETION_SLOT); + } + } + Ok(ValidatedCommand::DiskToHost { + priority, + extent, + host_offset, + completion_slot, + .. + }) => { + assert_eq!(cmd.opcode, Opcode::DiskToHost as u32); + assert!(Priority::from_u32(cmd.priority) == Some(priority)); + assert!(alignment >= MIN_ALIGNMENT && alignment.is_power_of_two()); + assert!((cmd.extent_id as usize) < extents.len()); + assert!(extent.nbytes > 0); + assert_eq!(host_offset % (alignment as u64), 0); + assert_eq!(extent.nbytes % (alignment as u64), 0); + assert!((host_offset as u128) + (extent.nbytes as u128) <= (host_pool_bytes as u128)); + if let Some(slot) = completion_slot { + assert!(slot < completion_slots); + } + } + Ok(ValidatedCommand::HostToDev { + priority, + host_offset, + device_offset, + nbytes, + completion_slot, + .. + }) => { + assert_eq!(cmd.opcode, Opcode::HostToDev as u32); + assert!(Priority::from_u32(cmd.priority) == Some(priority)); + assert!(nbytes > 0); + assert!((host_offset as u128) + (nbytes as u128) <= (host_pool_bytes as u128)); + assert!((device_offset as u128) + (nbytes as u128) <= (device_pool_bytes as u128)); + if let Some(slot) = completion_slot { + assert!(slot < completion_slots); + } + } + Ok(ValidatedCommand::DiskToDev { + priority, + extent, + host_offset, + device_offset, + completion_slot, + .. + }) => { + assert_eq!(cmd.opcode, Opcode::DiskToDev as u32); + assert!(Priority::from_u32(cmd.priority) == Some(priority)); + assert!(alignment >= MIN_ALIGNMENT && alignment.is_power_of_two()); + assert!((cmd.extent_id as usize) < extents.len()); + assert!(extent.nbytes > 0); + assert_eq!(extent.nbytes % (alignment as u64), 0); + match host_offset { + None => { + assert_eq!(cmd.host_offset, BOUNCE_HOST_OFFSET); + assert!(extent.nbytes <= bounce_slot_bytes); + } + Some(off) => { + assert_eq!(off % (alignment as u64), 0); + assert!((off as u128) + (extent.nbytes as u128) <= (host_pool_bytes as u128)); + } + } + assert!((device_offset as u128) + (extent.nbytes as u128) <= (device_pool_bytes as u128)); + if let Some(slot) = completion_slot { + assert!(slot < completion_slots); + } + } + Err(code) => { + assert_ne!(code, ErrorCode::Ok); + } + } +} + +#[kani::proof] +fn bounce_pool_geometry_never_exceeds_reserved_bound() { + let max_extent: u64 = kani::any(); + let alignment: u32 = kani::any(); + + let (slots, slot_bytes) = super::worker::bounce_pool_geometry(max_extent, alignment); + let max_pool = super::worker::max_bounce_pool_bytes(alignment); + let total = (slots as u128) * (slot_bytes as u128); + + assert!(total <= max_pool as u128); + if slots > 0 { + let align = u64::from(alignment); + assert!(align > 0 && align.is_power_of_two()); + assert!(slot_bytes >= max_extent); + assert!(slot_bytes % align == 0); + assert!(slot_bytes <= super::worker::MAX_BOUNCE_SLOT_BYTES); + } else { + assert_eq!(slot_bytes, 0); + } +} diff --git a/helios/src/async_transfer/lifecycle_tests.rs b/helios/src/async_transfer/lifecycle_tests.rs new file mode 100644 index 000000000..28ca8065f --- /dev/null +++ b/helios/src/async_transfer/lifecycle_tests.rs @@ -0,0 +1,342 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +//! Bounded trace conformance against `verification/helios-lifecycle/AsyncTransfer.tla`. + +use std::{collections::BTreeSet, fs, path::Path}; + +use super::{ + ring::{ChannelState, ExtentEntry, Priority, ValidatedCommand}, + scheduler::TransferScheduler, +}; + +/// Compact 13-integer projection shared with `AsyncTransfer.tla`. +/// +/// `[phase, active_epoch, q_io, q_dma, in_dem_io, in_bg_io, in_dem_dma, in_bg_dma, +/// b_in_io, b_q_dma, b_in_dma, free_bounce, can_release]` +type Projection = [i64; 13]; + +fn project(sched: &TransferScheduler) -> Projection { + let in_bg_io = sched.bg_io_inflight(); + let in_dem_io = sched.inflight_io_count() - in_bg_io; + let in_bg_dma = sched.bg_dma_inflight(); + let in_dem_dma = sched.inflight_dma_count() - in_bg_dma; + [ + sched.state() as i64, + sched.active_epoch() as i64, + sched.queued_io_count() as i64, + sched.queued_dma_count() as i64, + in_dem_io as i64, + in_bg_io as i64, + in_dem_dma as i64, + in_bg_dma as i64, + sched.bounce_in_io() as i64, + sched.bounce_in_qdma() as i64, + sched.bounce_in_dma() as i64, + sched.free_bounce_count() as i64, + i64::from(sched.can_release_memory()), + ] +} + +fn format_json_vec(v: &Projection) -> String { + format!( + "[{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]", + v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12] + ) +} + +fn dummy_extent() -> ExtentEntry { + ExtentEntry { + file_index: 0, + offset: 4096, + nbytes: 4096, + } +} + +/// Explore bounded operation sequences on the production [`TransferScheduler`] and assert every +/// lifecycle, priority-preemption, epoch-cancellation, bounce-slot, and drain safety invariant. +/// +/// Emits `ASYNC_TRANSFER_EDGE [before, [action_kind, 0, 0], after]` lines on stdout for +/// `verification/helios-lifecycle/check.py` observed-edge conformance against `AsyncTransfer.tla`. +#[test] +fn async_transfer_scheduler_matches_lifecycle_model() { + let max_total_io = 2usize; + let max_bg_io = 1usize; + let max_total_dma = 2usize; + let max_bg_dma = 1usize; + let bounce_slots = 1usize; + + let initial = TransferScheduler::new( + max_total_io, + max_bg_io, + max_total_dma, + max_bg_dma, + bounce_slots, + ); + + let mut edges: BTreeSet<(Projection, i64, Projection)> = BTreeSet::new(); + let mut visited: BTreeSet<(Projection, usize, usize)> = BTreeSet::new(); + let mut frontier: Vec<(TransferScheduler, Vec, Vec, usize)> = + vec![(initial, Vec::new(), Vec::new(), 0)]; + + while let Some((sched, io_ids, dma_ids, depth)) = frontier.pop() { + let before = project(&sched); + // Core safety assertions on every reachable Rust state. + assert!( + sched.bg_io_inflight() <= max_bg_io, + "background IO depth exceeded cap" + ); + assert!( + sched.bg_dma_inflight() <= max_bg_dma, + "background DMA depth exceeded cap" + ); + assert!(sched.inflight_io_count() <= max_total_io); + assert!(sched.inflight_dma_count() <= max_total_dma); + assert_eq!( + sched.free_bounce_count() + + sched.bounce_in_io() + + sched.bounce_in_qdma() + + sched.bounce_in_dma(), + bounce_slots, + "bounce slot conservation violated" + ); + if sched.inflight_io_count() > 0 || sched.inflight_dma_count() > 0 { + assert!( + !sched.can_release_memory(), + "in-flight work must block memory release" + ); + } + if sched.state() == ChannelState::FailedDrain { + assert!( + !sched.can_release_memory(), + "failed drain must retain pinned memory" + ); + } + if sched.state() == ChannelState::Stopped { + assert_eq!(sched.inflight_io_count(), 0); + assert_eq!(sched.inflight_dma_count(), 0); + assert_eq!( + sched.free_bounce_count(), + bounce_slots, + "stopped channel leaked bounce slot" + ); + assert!(sched.can_release_memory()); + } + + if depth >= 7 { + continue; + } + let key = (before, io_ids.len(), dma_ids.len()); + if !visited.insert(key) { + continue; + } + + let mut push_next = + |action: i64, next: TransferScheduler, next_io: Vec, next_dma: Vec| { + let after = project(&next); + edges.insert((before, action, after)); + frontier.push((next, next_io, next_dma, depth + 1)); + }; + + // 1. Start + if sched.state() == ChannelState::Idle { + let mut n = sched.clone(); + n.start().unwrap(); + push_next(1, n, io_ids.clone(), dma_ids.clone()); + } + + // 2. Enqueue commands while Running (bounded queue size for finite exploration). + if sched.state() == ChannelState::Running + && sched.queued_io_count() + sched.queued_dma_count() < 2 + { + for (prio, epoch) in [ + (Priority::Demand, 0u64), + (Priority::Prefetch, 0u64), + (Priority::Warm, 1u64), + ] { + // DiskToHost + let mut n = sched.clone(); + n.enqueue(ValidatedCommand::DiskToHost { + priority: prio, + extent: dummy_extent(), + host_offset: 0, + epoch, + completion_slot: Some(0), + signal_value: 1, + }); + push_next(2, n, io_ids.clone(), dma_ids.clone()); + + // HostToDev + let mut n = sched.clone(); + n.enqueue(ValidatedCommand::HostToDev { + priority: prio, + host_offset: 0, + device_offset: 0, + nbytes: 4096, + epoch, + completion_slot: Some(0), + signal_value: 2, + }); + push_next(2, n, io_ids.clone(), dma_ids.clone()); + + // Fused DiskToDev (bounce slot) + let mut n = sched.clone(); + n.enqueue(ValidatedCommand::DiskToDev { + priority: prio, + extent: dummy_extent(), + host_offset: None, + device_offset: 0, + epoch, + completion_slot: Some(0), + signal_value: 3, + }); + push_next(2, n, io_ids.clone(), dma_ids.clone()); + } + + // 3. CancelEpoch (0 -> 1 -> 2) + if sched.active_epoch() < 2 { + let mut n = sched.clone(); + n.enqueue(ValidatedCommand::CancelEpoch { + min_epoch: sched.active_epoch() + 1, + completion_slot: None, + signal_value: 0, + }); + push_next(3, n, io_ids.clone(), dma_ids.clone()); + } + } + + // 4. Dispatch IO + { + let mut n = sched.clone(); + if let Some(op) = n.pop_next_io() { + if op.priority.is_background() { + assert!(op.epoch >= sched.active_epoch()); + } + let mut n_io = io_ids.clone(); + n_io.push(op.op_id); + push_next(4, n, n_io, dma_ids.clone()); + } + } + + // 5. Dispatch DMA + { + let mut n = sched.clone(); + if let Some(op) = n.pop_next_dma() { + if op.priority.is_background() { + assert!(op.epoch >= sched.active_epoch()); + } + let mut n_dma = dma_ids.clone(); + n_dma.push(op.op_id); + push_next(5, n, io_ids.clone(), n_dma); + } + } + + // 6. Complete any in-flight IO (both ok=true and ok=false) + for (idx, &op_id) in io_ids.iter().enumerate() { + for ok in [true, false] { + let mut n = sched.clone(); + let _ = n.complete_io(op_id, ok); + let mut n_io = io_ids.clone(); + n_io.remove(idx); + push_next(6, n, n_io, dma_ids.clone()); + } + } + + // 7. Complete any in-flight DMA + for (idx, &op_id) in dma_ids.iter().enumerate() { + for ok in [true, false] { + let mut n = sched.clone(); + let _ = n.complete_dma(op_id, ok); + let mut n_dma = dma_ids.clone(); + n_dma.remove(idx); + push_next(7, n, io_ids.clone(), n_dma); + } + } + + // 8. BeginDrain + if matches!(sched.state(), ChannelState::Idle | ChannelState::Running) { + let mut n = sched.clone(); + n.begin_drain().unwrap(); + push_next(8, n, io_ids.clone(), dma_ids.clone()); + } + + // 9 / 10. FinishDrain (confirmed and unconfirmed) + if sched.state() == ChannelState::Draining { + for stream_drained in [true, false] { + let mut n = sched.clone(); + let res = n.finish_drain(stream_drained); + if stream_drained && io_ids.is_empty() && dma_ids.is_empty() { + assert!(res.is_ok()); + assert_eq!(n.state(), ChannelState::Stopped); + push_next(9, n, io_ids.clone(), dma_ids.clone()); + } else { + assert!( + res.is_err(), + "unconfirmed drain must not complete into Stopped" + ); + assert_eq!(n.state(), ChannelState::FailedDrain); + push_next(10, n, io_ids.clone(), dma_ids.clone()); + } + } + } + } + + // Explicit guard check: CancelEpoch must drop stale Prefetch/Warm but preserve Demand. + { + let mut s = TransferScheduler::new(2, 1, 2, 1, 1); + s.start().unwrap(); + s.enqueue(ValidatedCommand::HostToDev { + priority: Priority::Demand, + host_offset: 0, + device_offset: 0, + nbytes: 4096, + epoch: 0, + completion_slot: Some(0), + signal_value: 7, + }); + s.enqueue(ValidatedCommand::HostToDev { + priority: Priority::Prefetch, + host_offset: 4096, + device_offset: 4096, + nbytes: 4096, + epoch: 0, + completion_slot: Some(0), + signal_value: 8, + }); + s.advance_epoch(1); + assert_eq!( + s.queued_dma_count(), + 1, + "cancel_epoch must preserve Demand and drop stale Prefetch" + ); + } + + assert!( + edges.len() >= 200, + "expected rich explored transition graph, observed only {} edges", + edges.len() + ); + + for (before, action, after) in &edges { + println!( + "ASYNC_TRANSFER_EDGE [{}, [{action}, 0, 0], {}]", + format_json_vec(before), + format_json_vec(after) + ); + } + + if let Ok(path) = std::env::var("FLARE_ASYNC_TRANSFER_TRACE") { + let mut out = String::new(); + for (before, action, after) in &edges { + out.push_str(&format!( + "[{}, [{action}, 0, 0], {}]\n", + format_json_vec(before), + format_json_vec(after) + )); + } + fs::write(Path::new(&path), out).expect("write AsyncTransfer trace edges"); + } +} diff --git a/helios/src/async_transfer/mod.rs b/helios/src/async_transfer/mod.rs new file mode 100644 index 000000000..ad63bf613 --- /dev/null +++ b/helios/src/async_transfer/mod.rs @@ -0,0 +1,30 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +//! Stateless, domain-agnostic asynchronous byte-copy engine between authenticated core extents, +//! a runtime-sized pinned host byte pool, and a device byte pool. + +pub mod io_backend; +#[cfg(kani)] +mod kani_proofs; +#[cfg(test)] +mod lifecycle_tests; +pub mod ring; +pub mod scheduler; +#[cfg(feature = "runtime-core")] +pub mod worker; + +pub use ring::{ + ABI_VERSION, BOUNCE_HOST_OFFSET, COMMAND_BYTES, ChannelState, ControlHeader, EXTENT_ENTRY_BYTES, + ErrorCode, ExtentEntry, FLAG_DEVICE_COMPLETIONS, FLAG_STREAM_WRITE_VALUE64, HEADER_BYTES, + MAX_RING_CAPACITY, MIN_ALIGNMENT, MIN_RING_CAPACITY, NO_COMPLETION_SLOT, Opcode, Priority, + TransferCommand, ValidatedCommand, decode_extent_directory, host_completions_offset, + required_control_bytes, resolve_pool_bytes, validate_command, validate_control_layout, + validate_extent_entry, +}; +pub use scheduler::{CompletionNotice, InflightDma, InflightIo, OpId, QueuedOp, TransferScheduler}; +#[cfg(feature = "runtime-core")] +pub use worker::{AsyncTransferRuntime, AsyncTransferSnapshot, ChannelConfig}; diff --git a/helios/src/async_transfer/ring.rs b/helios/src/async_transfer/ring.rs new file mode 100644 index 000000000..b64e7e610 --- /dev/null +++ b/helios/src/async_transfer/ring.rs @@ -0,0 +1,626 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +//! Mapped-host ABI v1 layout and overflow-free command/extent validation for `AsyncTransfer`. + +use std::sync::atomic::{AtomicU32, AtomicU64}; + +/// Current binary layout version written into [`ControlHeader::abi_version`]. +pub const ABI_VERSION: u32 = 1; +/// Size in bytes of [`ControlHeader`], reserving four 64-byte cache lines. +pub const HEADER_BYTES: usize = 256; +/// Size in bytes of one [`TransferCommand`] ring slot (one 64-byte cache line). +pub const COMMAND_BYTES: usize = 64; +/// Size in bytes of one packed external-extent directory entry on disk. +pub const EXTENT_ENTRY_BYTES: usize = 24; + +/// Minimum supported power-of-two command ring capacity. +pub const MIN_RING_CAPACITY: u32 = 16; +/// Maximum supported power-of-two command ring capacity. +pub const MAX_RING_CAPACITY: u32 = 4096; +/// Minimum byte alignment for direct-I/O extents and pool offsets. +pub const MIN_ALIGNMENT: u32 = 4096; +/// Sentinel [`TransferCommand::completion_slot`] requesting no completion write. +pub const NO_COMPLETION_SLOT: u32 = u32::MAX; +/// Sentinel [`TransferCommand::host_offset`] selecting an internal pinned bounce slot +/// for fused [`Opcode::DiskToDev`] transfers when no caller-managed host slot is supplied. +pub const BOUNCE_HOST_OFFSET: u64 = u64::MAX; + +/// Control header feature bit indicating VRAM completion slots are configured. +pub const FLAG_DEVICE_COMPLETIONS: u32 = 1 << 0; +/// Control header feature bit indicating `cuStreamWriteValue64` v2 is active on the copy stream. +pub const FLAG_STREAM_WRITE_VALUE64: u32 = 1 << 1; + +/// Transfer operation code stored in [`TransferCommand::opcode`]. +#[repr(u32)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Opcode { + /// Read one authenticated external extent into the runtime-sized host pool. + DiskToHost = 1, + /// Copy a byte range from the runtime-sized host pool to the device pool via Copy Engine DMA. + HostToDev = 2, + /// Read one authenticated external extent into host staging and immediately DMA it to the device pool. + DiskToDev = 3, + /// Raise the active cancellation epoch, dropping queued non-demand commands from older epochs. + CancelEpoch = 4, +} + +impl Opcode { + #[inline] + pub const fn from_u32(raw: u32) -> Option { + match raw { + 1 => Some(Self::DiskToHost), + 2 => Some(Self::HostToDev), + 3 => Some(Self::DiskToDev), + 4 => Some(Self::CancelEpoch), + _ => None, + } + } +} + +/// Dispatch priority class stored in [`TransferCommand::priority`]. +#[repr(u32)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Priority { + /// Latency-critical transfer that preempts background queues and is never dropped by `CANCEL_EPOCH`. + Demand = 0, + /// Short-horizon speculative copy bounded to preserve copy-engine headroom for `Demand`. + Prefetch = 1, + /// Long-horizon background warming bounded to preserve storage queue headroom for `Demand`. + Warm = 2, +} + +impl Priority { + #[inline] + pub const fn from_u32(raw: u32) -> Option { + match raw { + 0 => Some(Self::Demand), + 1 => Some(Self::Prefetch), + 2 => Some(Self::Warm), + _ => None, + } + } + + #[inline] + pub const fn index(self) -> usize { + self as usize + } + + #[inline] + pub const fn is_background(self) -> bool { + !matches!(self, Self::Demand) + } +} + +/// Lifecycle state published in [`ControlHeader::worker_state`]. +#[repr(u32)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ChannelState { + #[default] + Idle = 0, + Running = 1, + Draining = 2, + Stopped = 3, + FailedDrain = 4, +} + +impl ChannelState { + #[inline] + pub const fn from_u32(raw: u32) -> Self { + match raw { + 0 => Self::Idle, + 1 => Self::Running, + 2 => Self::Draining, + 3 => Self::Stopped, + _ => Self::FailedDrain, + } + } +} + +/// Nonzero status codes recorded in [`ControlHeader::last_error`]. +#[repr(u32)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ErrorCode { + Ok = 0, + InvalidOpcode = 1, + InvalidPriority = 2, + ExtentOutOfRange = 3, + CompletionSlotOutOfRange = 4, + UnalignedOffsetOrLength = 5, + HostRangeOutOfBounds = 6, + DeviceRangeOutOfBounds = 7, + LengthMismatch = 8, + IoFailure = 9, + CudaFailure = 10, + RingOverrun = 11, +} + +/// One validated, read-only byte extent backed by an opened core file. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ExtentEntry { + pub file_index: u32, + pub offset: u64, + pub nbytes: u64, +} + +/// Fixed-layout mapped-host header at byte offset 0 of an `AsyncTransfer` control region. +/// +/// The layout occupies four 64-byte cache lines so GPU producer writes (`cmd_tail`, `active_epoch`), +/// host consumer writes (`cmd_head`, `worker_state`), and telemetry counters never false-share. +#[repr(C, align(64))] +pub struct ControlHeader { + // Cache line 0 (bytes 0..64): immutable startup geometry written before tuning graphs launch. + pub abi_version: u32, + pub flags: u32, + pub ring_capacity: u32, + pub completion_slots: u32, + pub extent_count: u32, + pub alignment: u32, + pub device_pool_base: u64, + pub device_pool_bytes: u64, + pub host_pool_bytes: u64, + pub device_completions_base: u64, + pub _pad0: u64, + + // Cache line 1 (bytes 64..128): producer-written doorbells (GPU -> host). + pub cmd_tail: AtomicU64, + pub active_epoch: AtomicU64, + pub _pad1: [u64; 6], + + // Cache line 2 (bytes 128..192): consumer-written progress and lifecycle state (host -> GPU). + pub cmd_head: AtomicU64, + pub worker_state: AtomicU32, + pub last_error: AtomicU32, + pub _pad2: [u64; 6], + + // Cache line 3 (bytes 192..256): lock-free host telemetry counters. + pub submitted_cmds: AtomicU64, + pub completed_cmds: AtomicU64, + pub canceled_cmds: AtomicU64, + pub rejected_cmds: AtomicU64, + pub bytes_disk_to_host: AtomicU64, + pub bytes_host_to_dev: AtomicU64, + pub bytes_disk_to_dev: AtomicU64, + pub active_inflight: AtomicU64, +} + +/// One 64-byte command ring slot written by GPU kernels and read by the Helios transfer worker. +#[repr(C, align(64))] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct TransferCommand { + pub opcode: u32, + pub priority: u32, + pub extent_id: u32, + pub completion_slot: u32, + pub host_offset: u64, + pub device_offset: u64, + pub nbytes: u64, + pub epoch: u64, + pub signal_value: u64, + pub _reserved: u64, +} + +/// Validated, bounds-checked command ready for the transfer scheduler. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ValidatedCommand { + DiskToHost { + priority: Priority, + extent: ExtentEntry, + host_offset: u64, + epoch: u64, + completion_slot: Option, + signal_value: u64, + }, + HostToDev { + priority: Priority, + host_offset: u64, + device_offset: u64, + nbytes: u64, + epoch: u64, + completion_slot: Option, + signal_value: u64, + }, + DiskToDev { + priority: Priority, + extent: ExtentEntry, + /// `None` requests an internal Helios pinned bounce slot (`BOUNCE_HOST_OFFSET`). + host_offset: Option, + device_offset: u64, + epoch: u64, + completion_slot: Option, + signal_value: u64, + }, + CancelEpoch { + min_epoch: u64, + completion_slot: Option, + signal_value: u64, + }, +} + +/// Byte offset of the host completion-slot array inside the mapped-host control allocation. +#[inline] +pub const fn host_completions_offset(ring_capacity: u32) -> Option { + let Some(ring_bytes) = (ring_capacity as u64).checked_mul(COMMAND_BYTES as u64) else { + return None; + }; + (HEADER_BYTES as u64).checked_add(ring_bytes) +} + +/// Minimum control allocation byte length required for `ring_capacity` and `completion_slots`. +#[inline] +pub const fn required_control_bytes(ring_capacity: u32, completion_slots: u32) -> Option { + let Some(comp_offset) = host_completions_offset(ring_capacity) else { + return None; + }; + let Some(comp_bytes) = (completion_slots as u64).checked_mul(8) else { + return None; + }; + comp_offset.checked_add(comp_bytes) +} + +/// Validate control allocation sizing, ring geometry, and direct-I/O alignment. +#[inline] +pub const fn validate_control_layout( + control_bytes: u64, + ring_capacity: u32, + completion_slots: u32, + alignment: u32, +) -> bool { + if ring_capacity < MIN_RING_CAPACITY + || ring_capacity > MAX_RING_CAPACITY + || !ring_capacity.is_power_of_two() + { + return false; + } + if completion_slots == 0 || completion_slots == NO_COMPLETION_SLOT { + return false; + } + if alignment < MIN_ALIGNMENT || !alignment.is_power_of_two() { + return false; + } + let Some(required) = required_control_bytes(ring_capacity, completion_slots) else { + return false; + }; + control_bytes >= required +} + +/// Validate one extent directory record against its backing segment length and required alignment. +#[inline] +pub const fn validate_extent_entry( + segment_index: u32, + segment_count: u32, + offset: u64, + nbytes: u64, + segment_nbytes: u64, + alignment: u32, +) -> bool { + if alignment < MIN_ALIGNMENT || !alignment.is_power_of_two() { + return false; + } + if segment_index >= segment_count || nbytes == 0 { + return false; + } + let mask = (alignment as u64) - 1; + if (offset & mask) != 0 || (nbytes & mask) != 0 { + return false; + } + match offset.checked_add(nbytes) { + Some(end) => end <= segment_nbytes, + None => false, + } +} + +/// Choose a runtime pool byte size aligned down to `alignment` within both `available_bytes` +/// and `max_pool_bytes`, honoring an optional caller ceiling. +#[inline] +pub const fn resolve_pool_bytes( + available_bytes: u64, + requested_cap: Option, + max_pool_bytes: u64, + alignment: u64, +) -> u64 { + if alignment == 0 || !alignment.is_power_of_two() || max_pool_bytes == 0 { + return 0; + } + let mut target = if available_bytes < max_pool_bytes { + available_bytes + } else { + max_pool_bytes + }; + if let Some(cap) = requested_cap { + if cap < target { + target = cap; + } + } + target & !(alignment - 1) +} + +#[inline] +const fn fits_range(offset: u64, nbytes: u64, bound: u64) -> bool { + match offset.checked_add(nbytes) { + Some(end) => end <= bound, + None => false, + } +} + +#[inline] +fn validate_transfer_header(raw_priority: u32, alignment: u32) -> Result<(Priority, u64), ErrorCode> { + let priority = Priority::from_u32(raw_priority).ok_or(ErrorCode::InvalidPriority)?; + if alignment < MIN_ALIGNMENT || !alignment.is_power_of_two() { + return Err(ErrorCode::UnalignedOffsetOrLength); + } + Ok((priority, (alignment as u64) - 1)) +} + +/// Validate one raw command against channel bounds, extent table, and alignment rules. +/// +/// No disk I/O or CUDA DMA may be issued unless this function returns `Ok(_)`. +pub fn validate_command( + cmd: &TransferCommand, + extents: &[ExtentEntry], + host_pool_bytes: u64, + device_pool_bytes: u64, + completion_slots: u32, + alignment: u32, + bounce_slot_bytes: u64, +) -> Result { + let opcode = Opcode::from_u32(cmd.opcode).ok_or(ErrorCode::InvalidOpcode)?; + let completion_slot = if cmd.completion_slot == NO_COMPLETION_SLOT { + None + } else if cmd.completion_slot < completion_slots { + Some(cmd.completion_slot) + } else { + return Err(ErrorCode::CompletionSlotOutOfRange); + }; + + match opcode { + Opcode::CancelEpoch => Ok(ValidatedCommand::CancelEpoch { + min_epoch: cmd.epoch, + completion_slot, + signal_value: cmd.signal_value, + }), + Opcode::DiskToHost => { + let (priority, align_mask) = validate_transfer_header(cmd.priority, alignment)?; + let extent = *extents + .get(cmd.extent_id as usize) + .ok_or(ErrorCode::ExtentOutOfRange)?; + if extent.nbytes == 0 || (cmd.nbytes != 0 && cmd.nbytes != extent.nbytes) { + return Err(ErrorCode::LengthMismatch); + } + if (cmd.host_offset & align_mask) != 0 || (extent.nbytes & align_mask) != 0 { + return Err(ErrorCode::UnalignedOffsetOrLength); + } + if !fits_range(cmd.host_offset, extent.nbytes, host_pool_bytes) { + return Err(ErrorCode::HostRangeOutOfBounds); + } + Ok(ValidatedCommand::DiskToHost { + priority, + extent, + host_offset: cmd.host_offset, + epoch: cmd.epoch, + completion_slot, + signal_value: cmd.signal_value, + }) + } + Opcode::HostToDev => { + let (priority, _) = validate_transfer_header(cmd.priority, alignment)?; + if cmd.nbytes == 0 { + return Err(ErrorCode::LengthMismatch); + } + if !fits_range(cmd.host_offset, cmd.nbytes, host_pool_bytes) { + return Err(ErrorCode::HostRangeOutOfBounds); + } + if !fits_range(cmd.device_offset, cmd.nbytes, device_pool_bytes) { + return Err(ErrorCode::DeviceRangeOutOfBounds); + } + Ok(ValidatedCommand::HostToDev { + priority, + host_offset: cmd.host_offset, + device_offset: cmd.device_offset, + nbytes: cmd.nbytes, + epoch: cmd.epoch, + completion_slot, + signal_value: cmd.signal_value, + }) + } + Opcode::DiskToDev => { + let (priority, align_mask) = validate_transfer_header(cmd.priority, alignment)?; + let extent = *extents + .get(cmd.extent_id as usize) + .ok_or(ErrorCode::ExtentOutOfRange)?; + if extent.nbytes == 0 || (cmd.nbytes != 0 && cmd.nbytes != extent.nbytes) { + return Err(ErrorCode::LengthMismatch); + } + if (extent.nbytes & align_mask) != 0 { + return Err(ErrorCode::UnalignedOffsetOrLength); + } + let host_offset = if cmd.host_offset == BOUNCE_HOST_OFFSET { + if extent.nbytes > bounce_slot_bytes { + return Err(ErrorCode::HostRangeOutOfBounds); + } + None + } else { + if (cmd.host_offset & align_mask) != 0 { + return Err(ErrorCode::UnalignedOffsetOrLength); + } + if !fits_range(cmd.host_offset, extent.nbytes, host_pool_bytes) { + return Err(ErrorCode::HostRangeOutOfBounds); + } + Some(cmd.host_offset) + }; + if !fits_range(cmd.device_offset, extent.nbytes, device_pool_bytes) { + return Err(ErrorCode::DeviceRangeOutOfBounds); + } + Ok(ValidatedCommand::DiskToDev { + priority, + extent, + host_offset, + device_offset: cmd.device_offset, + epoch: cmd.epoch, + completion_slot, + signal_value: cmd.signal_value, + }) + } + } +} + +/// Decode a packed little-endian extent directory (`[u32 seg, u32 reserved, u64 offset, u64 nbytes]`) +/// and validate every entry against resolved `(file_index, segment_base_offset, segment_nbytes)`. +pub fn decode_extent_directory( + directory_bytes: &[u8], + segments: &[(u32, u64, u64)], + alignment: u32, +) -> std::result::Result, String> { + if alignment < MIN_ALIGNMENT || !alignment.is_power_of_two() { + return Err(format!("invalid async transfer alignment {alignment}")); + } + if directory_bytes.len() % EXTENT_ENTRY_BYTES != 0 { + return Err(format!( + "extent directory length {} is not a multiple of {EXTENT_ENTRY_BYTES}", + directory_bytes.len() + )); + } + let count = directory_bytes.len() / EXTENT_ENTRY_BYTES; + let mut entries = Vec::with_capacity(count); + let seg_count = u32::try_from(segments.len()) + .map_err(|_| "extent segment count exceeds u32".to_string())?; + let align_mask = (alignment as u64) - 1; + for index in 0..count { + let base = index * EXTENT_ENTRY_BYTES; + let seg_idx = u32::from_le_bytes(directory_bytes[base..base + 4].try_into().unwrap()); + let reserved = u32::from_le_bytes(directory_bytes[base + 4..base + 8].try_into().unwrap()); + let rel_offset = + u64::from_le_bytes(directory_bytes[base + 8..base + 16].try_into().unwrap()); + let nbytes = u64::from_le_bytes(directory_bytes[base + 16..base + 24].try_into().unwrap()); + if reserved != 0 { + return Err(format!( + "extent {index} has nonzero reserved field {reserved}" + )); + } + let &(file_index, seg_base_offset, seg_nbytes) = segments + .get(seg_idx as usize) + .ok_or_else(|| format!("extent {index} references missing segment {seg_idx}"))?; + if !validate_extent_entry(seg_idx, seg_count, rel_offset, nbytes, seg_nbytes, alignment) { + return Err(format!( + "extent {index} (seg={seg_idx}, offset={rel_offset}, nbytes={nbytes}) violates segment bounds or {alignment}-byte alignment" + )); + } + let abs_offset = seg_base_offset + .checked_add(rel_offset) + .ok_or_else(|| format!("extent {index} absolute file offset overflow"))?; + if (abs_offset & align_mask) != 0 { + return Err(format!( + "extent {index} absolute file offset {abs_offset} is not {alignment}-byte aligned" + )); + } + entries.push(ExtentEntry { + file_index, + offset: abs_offset, + nbytes, + }); + } + Ok(entries) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn control_header_and_command_layouts_match_abi_v1() { + assert_eq!(std::mem::size_of::(), HEADER_BYTES); + assert_eq!(std::mem::align_of::(), 64); + assert_eq!(std::mem::offset_of!(ControlHeader, cmd_tail), 64); + assert_eq!(std::mem::offset_of!(ControlHeader, cmd_head), 128); + assert_eq!(std::mem::offset_of!(ControlHeader, submitted_cmds), 192); + assert_eq!(std::mem::size_of::(), COMMAND_BYTES); + assert_eq!(std::mem::align_of::(), 64); + } + + #[test] + fn validate_command_enforces_bounds_alignment_and_bounce_slots() { + let extents = [ExtentEntry { + file_index: 0, + offset: 4096, + nbytes: 8192, + }]; + let mut cmd = TransferCommand { + opcode: Opcode::DiskToHost as u32, + priority: Priority::Warm as u32, + extent_id: 0, + completion_slot: 3, + host_offset: 4096, + device_offset: 0, + nbytes: 0, + epoch: 7, + signal_value: 99, + _reserved: 0, + }; + assert!(matches!( + validate_command(&cmd, &extents, 16384, 16384, 8, 4096, 8192), + Ok(ValidatedCommand::DiskToHost { .. }) + )); + // Unaligned host offset rejected for direct I/O. + cmd.host_offset = 512; + assert_eq!( + validate_command(&cmd, &extents, 16384, 16384, 8, 4096, 8192), + Err(ErrorCode::UnalignedOffsetOrLength) + ); + // Overflowing host range rejected. + cmd.host_offset = u64::MAX - 4095; + assert_eq!( + validate_command(&cmd, &extents, 16384, 16384, 8, 4096, 8192), + Err(ErrorCode::HostRangeOutOfBounds) + ); + // Fused DiskToDev with bounce sentinel allowed even with zero host pool. + let fused = TransferCommand { + opcode: Opcode::DiskToDev as u32, + priority: Priority::Demand as u32, + extent_id: 0, + completion_slot: 0, + host_offset: BOUNCE_HOST_OFFSET, + device_offset: 4096, + nbytes: 8192, + epoch: 1, + signal_value: 42, + _reserved: 0, + }; + assert!(matches!( + validate_command(&fused, &extents, 0, 16384, 8, 4096, 8192), + Ok(ValidatedCommand::DiskToDev { + host_offset: None, + .. + }) + )); + // Rejected when extent exceeds bounce slot capacity. + assert_eq!( + validate_command(&fused, &extents, 0, 16384, 8, 4096, 4096), + Err(ErrorCode::HostRangeOutOfBounds) + ); + } + + #[test] + fn decode_extent_directory_checks_alignment_and_bounds() { + let mut dir = Vec::new(); + dir.extend_from_slice(&0u32.to_le_bytes()); + dir.extend_from_slice(&0u32.to_le_bytes()); + dir.extend_from_slice(&4096u64.to_le_bytes()); + dir.extend_from_slice(&8192u64.to_le_bytes()); + let ok = decode_extent_directory(&dir, &[(2, 4096, 16384)], 4096).unwrap(); + assert_eq!( + ok, + vec![ExtentEntry { + file_index: 2, + offset: 8192, + nbytes: 8192, + }] + ); + // Unaligned segment base fails even if relative offset is aligned. + assert!(decode_extent_directory(&dir, &[(2, 512, 16384)], 4096).is_err()); + // Out-of-bounds length fails. + assert!(decode_extent_directory(&dir, &[(2, 4096, 8192)], 4096).is_err()); + } +} diff --git a/helios/src/async_transfer/scheduler.rs b/helios/src/async_transfer/scheduler.rs new file mode 100644 index 000000000..5625220b2 --- /dev/null +++ b/helios/src/async_transfer/scheduler.rs @@ -0,0 +1,857 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +//! Deterministic preemptible priority scheduler and lifecycle state machine for `AsyncTransfer`. +//! +//! This module contains no OS or CUDA calls so both unit tests and TLA+ trace conformance +//! exercise the exact production queueing, epoch-cancellation, hardware-depth bounding, +//! bounce-slot ownership, and shutdown-drain state transitions. + +use std::collections::VecDeque; + +use super::ring::{ChannelState, ErrorCode, ExtentEntry, Priority, ValidatedCommand}; + +/// Unique monotonic operation ID assigned to every accepted transfer. +pub type OpId = u64; + +/// A validated operation waiting in the preemptible host priority queues. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum QueuedOp { + DiskToHost { + op_id: OpId, + priority: Priority, + extent: ExtentEntry, + host_offset: u64, + epoch: u64, + completion_slot: Option, + signal_value: u64, + }, + HostToDev { + op_id: OpId, + priority: Priority, + host_offset: u64, + device_offset: u64, + nbytes: u64, + epoch: u64, + completion_slot: Option, + signal_value: u64, + /// Internal bounce slot owned by a fused `DiskToDev` op after its IO stage finishes. + bounce_slot: Option, + /// True when this DMA is stage 2 of a fused `DiskToDev` transfer. + from_disk: bool, + }, + DiskToDevIo { + op_id: OpId, + priority: Priority, + extent: ExtentEntry, + host_offset: Option, + device_offset: u64, + epoch: u64, + completion_slot: Option, + signal_value: u64, + }, +} + +impl QueuedOp { + #[inline] + pub const fn priority(&self) -> Priority { + match *self { + Self::DiskToHost { priority, .. } + | Self::HostToDev { priority, .. } + | Self::DiskToDevIo { priority, .. } => priority, + } + } + + #[inline] + pub const fn epoch(&self) -> u64 { + match *self { + Self::DiskToHost { epoch, .. } + | Self::HostToDev { epoch, .. } + | Self::DiskToDevIo { epoch, .. } => epoch, + } + } + + #[inline] + pub const fn bounce_slot(&self) -> Option { + match *self { + Self::HostToDev { bounce_slot, .. } => bounce_slot, + Self::DiskToHost { .. } | Self::DiskToDevIo { .. } => None, + } + } +} + +/// An active disk-read operation submitted to the storage backend. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct InflightIo { + pub op_id: OpId, + pub priority: Priority, + pub extent: ExtentEntry, + pub host_offset: Option, + pub bounce_slot: Option, + pub device_offset: Option, + pub epoch: u64, + pub completion_slot: Option, + pub signal_value: u64, +} + +/// An active H2D DMA operation submitted to the Copy Engine stream. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct InflightDma { + pub op_id: OpId, + pub priority: Priority, + pub host_offset: Option, + pub bounce_slot: Option, + pub device_offset: u64, + pub nbytes: u64, + pub epoch: u64, + pub completion_slot: Option, + pub signal_value: u64, + pub from_disk: bool, +} + +/// Completion notification emitted by the scheduler when an operation finishes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CompletionNotice { + pub op_id: OpId, + pub completion_slot: Option, + pub signal_value: u64, + pub error: ErrorCode, + pub bytes_disk_to_host: u64, + pub bytes_host_to_dev: u64, + pub bytes_disk_to_dev: u64, +} + +/// Deterministic scheduler and lifecycle state machine for one `AsyncTransfer` channel. +#[derive(Clone, Debug)] +pub struct TransferScheduler { + state: ChannelState, + active_epoch: u64, + next_op_id: OpId, + max_total_io: usize, + max_bg_io: usize, + max_total_dma: usize, + max_bg_dma: usize, + io_queues: [VecDeque; 3], + dma_queues: [VecDeque; 3], + inflight_io: Vec, + inflight_dma: Vec, + free_bounce_slots: Vec, + total_bounce_slots: usize, + pub submitted_cmds: u64, + pub completed_cmds: u64, + pub canceled_cmds: u64, + pub rejected_cmds: u64, +} + +impl TransferScheduler { + /// Construct a new `Idle` scheduler with explicit total and background concurrency caps. + pub fn new( + max_total_io: usize, + max_bg_io: usize, + max_total_dma: usize, + max_bg_dma: usize, + bounce_slots: usize, + ) -> Self { + let max_total_io = max_total_io.max(1); + let max_total_dma = max_total_dma.max(1); + Self { + state: ChannelState::Idle, + active_epoch: 0, + next_op_id: 1, + max_total_io, + max_bg_io: max_bg_io.min(max_total_io), + max_total_dma, + max_bg_dma: max_bg_dma.min(max_total_dma), + io_queues: [VecDeque::new(), VecDeque::new(), VecDeque::new()], + dma_queues: [VecDeque::new(), VecDeque::new(), VecDeque::new()], + inflight_io: Vec::new(), + inflight_dma: Vec::new(), + free_bounce_slots: (0..bounce_slots).rev().collect(), + total_bounce_slots: bounce_slots, + submitted_cmds: 0, + completed_cmds: 0, + canceled_cmds: 0, + rejected_cmds: 0, + } + } + + #[inline] + pub const fn state(&self) -> ChannelState { + self.state + } + + #[inline] + pub const fn active_epoch(&self) -> u64 { + self.active_epoch + } + + #[inline] + pub fn inflight_io_count(&self) -> usize { + self.inflight_io.len() + } + + #[inline] + pub fn inflight_dma_count(&self) -> usize { + self.inflight_dma.len() + } + + #[inline] + pub fn bg_io_inflight(&self) -> usize { + self.inflight_io + .iter() + .filter(|op| op.priority.is_background()) + .count() + } + + #[inline] + pub fn bg_dma_inflight(&self) -> usize { + self.inflight_dma + .iter() + .filter(|op| op.priority.is_background()) + .count() + } + + #[inline] + pub fn queued_io_count(&self) -> usize { + self.io_queues.iter().map(VecDeque::len).sum() + } + + #[inline] + pub fn queued_dma_count(&self) -> usize { + self.dma_queues.iter().map(VecDeque::len).sum() + } + + #[inline] + pub fn free_bounce_count(&self) -> usize { + self.free_bounce_slots.len() + } + + #[inline] + pub const fn total_bounce_slots(&self) -> usize { + self.total_bounce_slots + } + + #[inline] + pub fn bounce_in_io(&self) -> usize { + self.inflight_io + .iter() + .filter(|op| op.bounce_slot.is_some()) + .count() + } + + #[inline] + pub fn bounce_in_qdma(&self) -> usize { + self.dma_queues + .iter() + .flat_map(|q| q.iter()) + .filter(|op| op.bounce_slot().is_some()) + .count() + } + + #[inline] + pub fn bounce_in_dma(&self) -> usize { + self.inflight_dma + .iter() + .filter(|op| op.bounce_slot.is_some()) + .count() + } + + /// True only when no storage I/O or Copy Engine DMA is in flight and the channel is idle or stopped. + #[inline] + pub fn can_release_memory(&self) -> bool { + matches!(self.state, ChannelState::Idle | ChannelState::Stopped) + && self.inflight_io.is_empty() + && self.inflight_dma.is_empty() + } + + /// Transition `Idle -> Running` (idempotent when already `Running`). + pub fn start(&mut self) -> Result<(), &'static str> { + match self.state { + ChannelState::Idle => { + self.state = ChannelState::Running; + Ok(()) + } + ChannelState::Running => Ok(()), + ChannelState::Draining => Err("async transfer channel is draining"), + ChannelState::Stopped => Err("async transfer channel has already been stopped"), + ChannelState::FailedDrain => Err("async transfer channel failed to drain"), + } + } + + /// Record a rejected malformed command without mutating any hardware queue. + pub fn record_rejected(&mut self) { + self.rejected_cmds = self.rejected_cmds.saturating_add(1); + } + + /// Advance the active epoch monotonically and drop every queued background op with + /// `op.epoch < active_epoch`. `Demand` operations are never dropped by cancellation. + pub fn advance_epoch(&mut self, min_epoch: u64) -> u64 { + if min_epoch <= self.active_epoch { + return 0; + } + self.active_epoch = min_epoch; + let mut dropped = 0u64; + for prio in [Priority::Prefetch.index(), Priority::Warm.index()] { + let before_io = self.io_queues[prio].len(); + self.io_queues[prio].retain(|op| op.epoch() >= min_epoch); + dropped += (before_io - self.io_queues[prio].len()) as u64; + + let mut kept = VecDeque::with_capacity(self.dma_queues[prio].len()); + while let Some(op) = self.dma_queues[prio].pop_front() { + if op.epoch() < min_epoch { + if let Some(slot) = op.bounce_slot() { + self.free_bounce_slots.push(slot); + } + dropped += 1; + } else { + kept.push_back(op); + } + } + self.dma_queues[prio] = kept; + } + self.canceled_cmds = self.canceled_cmds.saturating_add(dropped); + dropped + } + + /// Admit one already-validated command into the preemptible host priority queues. + /// + /// Returns an immediate [`CompletionNotice`] for `CancelEpoch` or for background commands + /// whose epoch is already strictly older than `active_epoch`. + pub fn enqueue(&mut self, cmd: ValidatedCommand) -> Option { + if self.state != ChannelState::Running { + self.rejected_cmds = self.rejected_cmds.saturating_add(1); + return None; + } + self.submitted_cmds = self.submitted_cmds.saturating_add(1); + match cmd { + ValidatedCommand::CancelEpoch { + min_epoch, + completion_slot, + signal_value, + } => { + self.advance_epoch(min_epoch); + self.completed_cmds = self.completed_cmds.saturating_add(1); + Some(CompletionNotice { + op_id: 0, + completion_slot, + signal_value, + error: ErrorCode::Ok, + bytes_disk_to_host: 0, + bytes_host_to_dev: 0, + bytes_disk_to_dev: 0, + }) + } + ValidatedCommand::DiskToHost { + priority, + extent, + host_offset, + epoch, + completion_slot, + signal_value, + } => { + if priority.is_background() && epoch < self.active_epoch { + self.canceled_cmds = self.canceled_cmds.saturating_add(1); + return None; + } + let op_id = self.next_op_id; + self.next_op_id = self.next_op_id.wrapping_add(1).max(1); + self.io_queues[priority.index()].push_back(QueuedOp::DiskToHost { + op_id, + priority, + extent, + host_offset, + epoch, + completion_slot, + signal_value, + }); + None + } + ValidatedCommand::HostToDev { + priority, + host_offset, + device_offset, + nbytes, + epoch, + completion_slot, + signal_value, + } => { + if priority.is_background() && epoch < self.active_epoch { + self.canceled_cmds = self.canceled_cmds.saturating_add(1); + return None; + } + let op_id = self.next_op_id; + self.next_op_id = self.next_op_id.wrapping_add(1).max(1); + self.dma_queues[priority.index()].push_back(QueuedOp::HostToDev { + op_id, + priority, + host_offset, + device_offset, + nbytes, + epoch, + completion_slot, + signal_value, + bounce_slot: None, + from_disk: false, + }); + None + } + ValidatedCommand::DiskToDev { + priority, + extent, + host_offset, + device_offset, + epoch, + completion_slot, + signal_value, + } => { + if priority.is_background() && epoch < self.active_epoch { + self.canceled_cmds = self.canceled_cmds.saturating_add(1); + return None; + } + let op_id = self.next_op_id; + self.next_op_id = self.next_op_id.wrapping_add(1).max(1); + self.io_queues[priority.index()].push_back(QueuedOp::DiskToDevIo { + op_id, + priority, + extent, + host_offset, + device_offset, + epoch, + completion_slot, + signal_value, + }); + None + } + } + } + + /// Pop the highest-priority eligible storage read allowed by total and background IO caps. + pub fn pop_next_io(&mut self) -> Option { + if self.state != ChannelState::Running || self.inflight_io.len() >= self.max_total_io { + return None; + } + let bg_used = self.bg_io_inflight(); + for prio in [Priority::Demand, Priority::Prefetch, Priority::Warm] { + if prio.is_background() && bg_used >= self.max_bg_io { + continue; + } + let queue = &mut self.io_queues[prio.index()]; + while let Some(front) = queue.front().copied() { + if prio.is_background() && front.epoch() < self.active_epoch { + queue.pop_front(); + self.canceled_cmds = self.canceled_cmds.saturating_add(1); + continue; + } + let needs_bounce = matches!( + front, + QueuedOp::DiskToDevIo { + host_offset: None, + .. + } + ); + if needs_bounce && self.free_bounce_slots.is_empty() { + break; + } + let op = queue.pop_front().unwrap(); + let bounce_slot = if needs_bounce { + self.free_bounce_slots.pop() + } else { + None + }; + let inflight = match op { + QueuedOp::DiskToHost { + op_id, + priority, + extent, + host_offset, + epoch, + completion_slot, + signal_value, + } => InflightIo { + op_id, + priority, + extent, + host_offset: Some(host_offset), + bounce_slot: None, + device_offset: None, + epoch, + completion_slot, + signal_value, + }, + QueuedOp::DiskToDevIo { + op_id, + priority, + extent, + host_offset, + device_offset, + epoch, + completion_slot, + signal_value, + } => InflightIo { + op_id, + priority, + extent, + host_offset, + bounce_slot, + device_offset: Some(device_offset), + epoch, + completion_slot, + signal_value, + }, + QueuedOp::HostToDev { .. } => unreachable!(), + }; + self.inflight_io.push(inflight); + return Some(inflight); + } + } + None + } + + /// Record completion of an in-flight storage read. + /// + /// A successful fused `DiskToDev` read transitions into `dma_queues` while still `Running` + /// (unless canceled by `active_epoch` as a background op); during `Draining`, fused stage 2 + /// is skipped and any bounce slot is returned so drain always terminates. + pub fn complete_io(&mut self, op_id: OpId, ok: bool) -> Option { + let pos = self.inflight_io.iter().position(|op| op.op_id == op_id)?; + let op = self.inflight_io.swap_remove(pos); + + if let Some(device_offset) = op.device_offset { + let stale_bg = op.priority.is_background() && op.epoch < self.active_epoch; + if ok && self.state == ChannelState::Running && !stale_bg { + self.dma_queues[op.priority.index()].push_back(QueuedOp::HostToDev { + op_id: op.op_id, + priority: op.priority, + host_offset: op.host_offset.unwrap_or(0), + device_offset, + nbytes: op.extent.nbytes, + epoch: op.epoch, + completion_slot: op.completion_slot, + signal_value: op.signal_value, + bounce_slot: op.bounce_slot, + from_disk: true, + }); + return None; + } + if let Some(slot) = op.bounce_slot { + self.free_bounce_slots.push(slot); + } + if !ok { + self.completed_cmds = self.completed_cmds.saturating_add(1); + return Some(CompletionNotice { + op_id: op.op_id, + completion_slot: op.completion_slot, + signal_value: op.signal_value, + error: ErrorCode::IoFailure, + bytes_disk_to_host: 0, + bytes_host_to_dev: 0, + bytes_disk_to_dev: 0, + }); + } + self.canceled_cmds = self.canceled_cmds.saturating_add(1); + return None; + } + + self.completed_cmds = self.completed_cmds.saturating_add(1); + Some(CompletionNotice { + op_id: op.op_id, + completion_slot: op.completion_slot, + signal_value: op.signal_value, + error: if ok { + ErrorCode::Ok + } else { + ErrorCode::IoFailure + }, + bytes_disk_to_host: if ok { op.extent.nbytes } else { 0 }, + bytes_host_to_dev: 0, + bytes_disk_to_dev: 0, + }) + } + + /// Pop the highest-priority eligible H2D DMA allowed by total and background DMA caps. + pub fn pop_next_dma(&mut self) -> Option { + if self.state != ChannelState::Running || self.inflight_dma.len() >= self.max_total_dma { + return None; + } + let bg_used = self.bg_dma_inflight(); + for prio in [Priority::Demand, Priority::Prefetch, Priority::Warm] { + if prio.is_background() && bg_used >= self.max_bg_dma { + continue; + } + let queue = &mut self.dma_queues[prio.index()]; + while let Some(op) = queue.pop_front() { + if prio.is_background() && op.epoch() < self.active_epoch { + if let Some(slot) = op.bounce_slot() { + self.free_bounce_slots.push(slot); + } + self.canceled_cmds = self.canceled_cmds.saturating_add(1); + continue; + } + let QueuedOp::HostToDev { + op_id, + priority, + host_offset, + device_offset, + nbytes, + epoch, + completion_slot, + signal_value, + bounce_slot, + from_disk, + } = op + else { + unreachable!(); + }; + let inflight = InflightDma { + op_id, + priority, + host_offset: if bounce_slot.is_some() { + None + } else { + Some(host_offset) + }, + bounce_slot, + device_offset, + nbytes, + epoch, + completion_slot, + signal_value, + from_disk, + }; + self.inflight_dma.push(inflight); + return Some(inflight); + } + } + None + } + + /// Record completion of an in-flight Copy Engine DMA transfer. + pub fn complete_dma(&mut self, op_id: OpId, ok: bool) -> Option { + let pos = self.inflight_dma.iter().position(|op| op.op_id == op_id)?; + let op = self.inflight_dma.swap_remove(pos); + if let Some(slot) = op.bounce_slot { + self.free_bounce_slots.push(slot); + } + self.completed_cmds = self.completed_cmds.saturating_add(1); + Some(CompletionNotice { + op_id: op.op_id, + completion_slot: op.completion_slot, + signal_value: op.signal_value, + error: if ok { + ErrorCode::Ok + } else { + ErrorCode::CudaFailure + }, + bytes_disk_to_host: 0, + bytes_host_to_dev: if ok && !op.from_disk { op.nbytes } else { 0 }, + bytes_disk_to_dev: if ok && op.from_disk { op.nbytes } else { 0 }, + }) + } + + /// Begin shutdown drain: transition `Running -> Draining` and drop all unstarted queued ops. + /// + /// Transitions `Idle -> Stopped` immediately. Returns `Err` if already `FailedDrain`. + pub fn begin_drain(&mut self) -> Result { + match self.state { + ChannelState::Idle => { + self.state = ChannelState::Stopped; + Ok(self.state) + } + ChannelState::Running => { + self.state = ChannelState::Draining; + let mut dropped = 0u64; + for q in &mut self.io_queues { + dropped += q.len() as u64; + q.clear(); + } + for q in &mut self.dma_queues { + while let Some(op) = q.pop_front() { + if let Some(slot) = op.bounce_slot() { + self.free_bounce_slots.push(slot); + } + dropped += 1; + } + } + self.canceled_cmds = self.canceled_cmds.saturating_add(dropped); + Ok(self.state) + } + ChannelState::Draining => Ok(self.state), + ChannelState::Stopped => Ok(self.state), + ChannelState::FailedDrain => Err("async transfer channel failed to drain"), + } + } + + /// Finalize drain after storage and CUDA stream drain attempts complete. + /// + /// Enters `Stopped` only if every in-flight IO and DMA finished and `stream_drained` is true; + /// otherwise transitions to `FailedDrain` so callers retain backing memory until process exit. + pub fn finish_drain(&mut self, stream_drained: bool) -> Result<(), &'static str> { + match self.state { + ChannelState::Stopped => Ok(()), + ChannelState::Draining => { + if stream_drained && self.inflight_io.is_empty() && self.inflight_dma.is_empty() { + self.state = ChannelState::Stopped; + Ok(()) + } else { + self.state = ChannelState::FailedDrain; + Err("async transfer channel failed to confirm hardware drain") + } + } + ChannelState::Idle => { + self.state = ChannelState::Stopped; + Ok(()) + } + ChannelState::Running => Err("cannot finish drain before begin_drain"), + ChannelState::FailedDrain => Err("async transfer channel failed to drain"), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ext(nbytes: u64) -> ExtentEntry { + ExtentEntry { + file_index: 0, + offset: 4096, + nbytes, + } + } + + #[test] + fn demand_preempts_background_and_survives_cancel_epoch() { + let mut sched = TransferScheduler::new(4, 1, 4, 1, 2); + sched.start().unwrap(); + // Queue two warm/prefetch DMAs and one demand DMA in epoch 1. + sched.enqueue(ValidatedCommand::HostToDev { + priority: Priority::Warm, + host_offset: 0, + device_offset: 0, + nbytes: 4096, + epoch: 1, + completion_slot: Some(0), + signal_value: 1, + }); + sched.enqueue(ValidatedCommand::HostToDev { + priority: Priority::Prefetch, + host_offset: 4096, + device_offset: 4096, + nbytes: 4096, + epoch: 1, + completion_slot: Some(1), + signal_value: 2, + }); + sched.enqueue(ValidatedCommand::HostToDev { + priority: Priority::Demand, + host_offset: 8192, + device_offset: 8192, + nbytes: 4096, + epoch: 1, + completion_slot: Some(2), + signal_value: 3, + }); + // Cancel epoch 2 drops Warm and Prefetch, leaving Demand intact. + let notice = sched + .enqueue(ValidatedCommand::CancelEpoch { + min_epoch: 2, + completion_slot: Some(3), + signal_value: 99, + }) + .unwrap(); + assert_eq!(notice.signal_value, 99); + assert_eq!(sched.canceled_cmds, 2); + assert_eq!(sched.queued_dma_count(), 1); + let op = sched.pop_next_dma().unwrap(); + assert_eq!(op.priority, Priority::Demand); + assert_eq!(op.signal_value, 3); + assert!(sched.pop_next_dma().is_none()); + } + + #[test] + fn background_depth_is_capped_while_demand_dispatches_immediately() { + let mut sched = TransferScheduler::new(4, 1, 4, 1, 2); + sched.start().unwrap(); + for i in 0..3u64 { + sched.enqueue(ValidatedCommand::HostToDev { + priority: Priority::Prefetch, + host_offset: i * 4096, + device_offset: i * 4096, + nbytes: 4096, + epoch: 5, + completion_slot: Some(i as u32), + signal_value: i + 1, + }); + } + // Only one background DMA may enter hardware (max_bg_dma = 1). + let bg = sched.pop_next_dma().unwrap(); + assert_eq!(bg.priority, Priority::Prefetch); + assert!(sched.pop_next_dma().is_none()); + // A newly arriving Demand op jumps ahead immediately despite bg_used == max_bg_dma. + sched.enqueue(ValidatedCommand::HostToDev { + priority: Priority::Demand, + host_offset: 0, + device_offset: 0, + nbytes: 4096, + epoch: 5, + completion_slot: Some(7), + signal_value: 77, + }); + let dem = sched.pop_next_dma().unwrap(); + assert_eq!(dem.priority, Priority::Demand); + assert_eq!(dem.signal_value, 77); + } + + #[test] + fn fused_disk_to_dev_preserves_bounce_slot_across_drain_and_completion() { + let mut sched = TransferScheduler::new(2, 1, 2, 1, 1); + sched.start().unwrap(); + sched.enqueue(ValidatedCommand::DiskToDev { + priority: Priority::Demand, + extent: ext(8192), + host_offset: None, + device_offset: 0, + epoch: 1, + completion_slot: Some(0), + signal_value: 55, + }); + let io = sched.pop_next_io().unwrap(); + assert_eq!(io.bounce_slot, Some(0)); + assert_eq!(sched.free_bounce_count(), 0); + // Completing IO queues stage-2 DMA keeping bounce_slot=0. + assert!(sched.complete_io(io.op_id, true).is_none()); + let dma = sched.pop_next_dma().unwrap(); + assert_eq!(dma.bounce_slot, Some(0)); + assert!(dma.from_disk); + // Cannot release memory while DMA is in flight. + assert!(!sched.can_release_memory()); + let notice = sched.complete_dma(dma.op_id, true).unwrap(); + assert_eq!(notice.bytes_disk_to_dev, 8192); + assert_eq!(sched.free_bounce_count(), 1); + sched.begin_drain().unwrap(); + sched.finish_drain(true).unwrap(); + assert!(sched.can_release_memory()); + } + + #[test] + fn failed_drain_never_permits_memory_release() { + let mut sched = TransferScheduler::new(2, 1, 2, 1, 1); + sched.start().unwrap(); + sched.enqueue(ValidatedCommand::DiskToHost { + priority: Priority::Demand, + extent: ext(4096), + host_offset: 0, + epoch: 1, + completion_slot: None, + signal_value: 0, + }); + let _io = sched.pop_next_io().unwrap(); + sched.begin_drain().unwrap(); + assert!(sched.finish_drain(true).is_err()); + assert_eq!(sched.state(), ChannelState::FailedDrain); + assert!(!sched.can_release_memory()); + } +} diff --git a/helios/src/async_transfer/worker.rs b/helios/src/async_transfer/worker.rs new file mode 100644 index 000000000..ca1dffa11 --- /dev/null +++ b/helios/src/async_transfer/worker.rs @@ -0,0 +1,1502 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +//! Runtime worker thread, pinned host byte pool, Copy Engine stream, and bounded shutdown drain +//! for `AsyncTransfer`. + +use std::{ + collections::VecDeque, + ptr::null_mut, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}, + }, + thread::{self, JoinHandle}, + time::{Duration, Instant}, +}; + +use crate::{ + Error, ExecutionError, Result, + runtime_core::driver::{ + CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS, CU_MEMHOSTREGISTER_PORTABLE, + CU_STREAM_NON_BLOCKING, CU_STREAM_WRITE_VALUE_DEFAULT, CUDA_ERROR_NOT_READY, Driver, + Handle, + }, +}; + +use super::{ + io_backend::{IoBackend, IoCompletion}, + ring::{ + ABI_VERSION, ChannelState, ControlHeader, ErrorCode, ExtentEntry, + FLAG_DEVICE_COMPLETIONS, FLAG_STREAM_WRITE_VALUE64, HEADER_BYTES, TransferCommand, + host_completions_offset, validate_command, + }, + scheduler::{CompletionNotice, OpId, TransferScheduler}, +}; + +const DRAIN_TIMEOUT: Duration = Duration::from_secs(5); +const BUSY_SPIN_LIMIT: u32 = 512; +const IDLE_SPIN_LIMIT: u32 = 4096; +const BUSY_PARK_INTERVAL: Duration = Duration::from_micros(50); +const IDLE_PARK_INTERVAL: Duration = Duration::from_micros(200); +const DEFAULT_MAX_TOTAL_IO: usize = 32; +const DEFAULT_MAX_BG_IO: usize = 8; +const DEFAULT_MAX_TOTAL_DMA: usize = 16; +const DEFAULT_MAX_BG_DMA: usize = 4; +const DEFAULT_BOUNCE_SLOTS: usize = 16; +pub(crate) const MAX_BOUNCE_SLOT_BYTES: u64 = 32 << 20; +/// Maximum pinned host bounce buffer registered by one channel (`DEFAULT_BOUNCE_SLOTS * MAX_BOUNCE_SLOT_BYTES`). +pub(crate) const MAX_BOUNCE_POOL_BYTES: u64 = (DEFAULT_BOUNCE_SLOTS as u64) * MAX_BOUNCE_SLOT_BYTES; + +/// Upper bound on pinned bounce bytes registered by one channel with the given direct-I/O +/// alignment. Returns `0` when `alignment` itself exceeds [`MAX_BOUNCE_SLOT_BYTES`] (or is not a +/// positive power of two), because bounce staging is disabled in that configuration. +pub(crate) fn max_bounce_pool_bytes(alignment: u32) -> u64 { + let align = u64::from(alignment); + if align == 0 || !align.is_power_of_two() || align > MAX_BOUNCE_SLOT_BYTES { + return 0; + } + MAX_BOUNCE_POOL_BYTES +} + +/// Compute `(bounce_slots, bounce_slot_bytes)` for a channel's maximum extent size and +/// direct-I/O alignment. +/// +/// Rounds `max_extent_bytes` up to `alignment` before applying [`MAX_BOUNCE_SLOT_BYTES`]; if the +/// aligned slot exceeds [`MAX_BOUNCE_SLOT_BYTES`], bounce staging is disabled (`(0, 0)`) so +/// registered bounce memory never exceeds [`max_bounce_pool_bytes`]. +pub(crate) fn bounce_pool_geometry(max_extent_bytes: u64, alignment: u32) -> (usize, u64) { + let align = u64::from(alignment); + if max_extent_bytes == 0 + || align == 0 + || !align.is_power_of_two() + || align > MAX_BOUNCE_SLOT_BYTES + { + return (0, 0); + } + let Some(slot_bytes) = max_extent_bytes.checked_next_multiple_of(align) else { + return (0, 0); + }; + if slot_bytes > MAX_BOUNCE_SLOT_BYTES { + return (0, 0); + } + (DEFAULT_BOUNCE_SLOTS, slot_bytes) +} + +/// Immutable configuration passed to [`AsyncTransferRuntime::new`]. +#[derive(Clone, Debug)] +pub struct ChannelConfig { + pub name: String, + pub device_pool_base: u64, + pub device_pool_bytes: u64, + pub host_pool_bytes: u64, + pub control_address: usize, + pub control_bytes: usize, + pub device_completions_base: u64, + pub completion_slots: u32, + pub ring_capacity: u32, + pub alignment: u32, + pub extents: Vec, +} + +/// Lock-free telemetry snapshot from one `AsyncTransfer` channel. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AsyncTransferSnapshot { + pub name: String, + pub state: ChannelState, + pub device_pool_bytes: u64, + pub host_pool_bytes: u64, + pub extent_count: u32, + pub submitted_cmds: u64, + pub completed_cmds: u64, + pub canceled_cmds: u64, + pub rejected_cmds: u64, + pub bytes_disk_to_host: u64, + pub bytes_host_to_dev: u64, + pub bytes_disk_to_dev: u64, + pub last_error: u32, +} + +/// Page-aligned, CUDA-pinned host memory region owned by [`AsyncTransferRuntime`]. +struct PinnedHostRegion { + ptr: *mut u8, + nbytes: usize, + cuda_registered: bool, +} + +// SAFETY: Ownership transfers only to the channel owner / worker and is released after drain. +unsafe impl Send for PinnedHostRegion {} +unsafe impl Sync for PinnedHostRegion {} + +impl PinnedHostRegion { + unsafe fn allocate(driver: &Driver, context: Handle, nbytes: usize) -> Result { + if nbytes == 0 { + return Ok(Self { + ptr: null_mut(), + nbytes: 0, + cuda_registered: false, + }); + } + let address = crate::os::map_host(nbytes).map_err(|err| { + format!("map {nbytes} bytes for async transfer host pool failed: {err}") + })?; + let ptr = address as *mut u8; + let mut region = Self { + ptr, + nbytes, + cuda_registered: false, + }; + // Register with CUDA for full-speed Copy Engine DMA over PCIe. + unsafe { + let mut prev = null_mut(); + let had_prev = (driver.context_get)(&mut prev) == 0; + if let Err(err) = driver.check("cuCtxSetCurrent", (driver.context_set)(context)) { + region.release_unregistered(); + return Err(err); + } + let status = (driver.host_register)(ptr.cast(), nbytes, CU_MEMHOSTREGISTER_PORTABLE); + if had_prev && prev != context { + let _ = (driver.context_set)(prev); + } + if let Err(err) = driver.check("cuMemHostRegister_v2(host_pool)", status) { + region.release_unregistered(); + return Err(err); + } + } + region.cuda_registered = true; + Ok(region) + } + + unsafe fn release_unregistered(&mut self) { + if self.ptr.is_null() || self.nbytes == 0 { + return; + } + unsafe { + crate::os::unmap_host(self.ptr as usize, self.nbytes); + } + self.ptr = null_mut(); + self.nbytes = 0; + } + + unsafe fn release(&mut self, driver: &Driver, context: Handle) { + if self.ptr.is_null() || self.nbytes == 0 { + return; + } + if self.cuda_registered { + unsafe { + let mut prev = null_mut(); + let had_prev = (driver.context_get)(&mut prev) == 0; + if (driver.context_set)(context) == 0 { + let _ = (driver.host_unregister)(self.ptr.cast()); + } + if had_prev && prev != context { + let _ = (driver.context_set)(prev); + } + } + self.cuda_registered = false; + } + unsafe { self.release_unregistered() }; + } +} + +enum EventCompletionAction { + None, + HostOnly(u32, u64), + HostAndDevice(u32, u64), +} + +struct PendingEventDma { + op_id: OpId, + event: Handle, + completion_action: EventCompletionAction, +} + +struct WorkerStateInner { + state: ChannelState, + stop_requested: Arc, + join_handle: Option>, + io_backend: Option>, + copy_stream: Handle, + signal_stream: Handle, + host_pool: PinnedHostRegion, + bounce_pool: PinnedHostRegion, + bounce_slot_bytes: u64, + bounce_slots: usize, + use_write_value64: bool, + released: bool, +} + +// SAFETY: Access to CUDA handles and worker thread handle is serialized by `AsyncTransferRuntime`'s mutex. +unsafe impl Send for WorkerStateInner {} + +/// Thread-safe runtime owner for one stateless `AsyncTransfer` channel. +pub struct AsyncTransferRuntime { + config: ChannelConfig, + driver: Arc, + context: Handle, + atomic_state: Arc, + inner: Mutex, +} + +// SAFETY: State transitions are serialized by `self.inner`; telemetry reads use atomics. +unsafe impl Send for AsyncTransferRuntime {} +unsafe impl Sync for AsyncTransferRuntime {} + +impl AsyncTransferRuntime { + /// Allocate pinned host and bounce pools, create the non-blocking Copy Engine stream, + /// populate the mapped-host startup geometry header, and prepare the channel in `Idle`. + /// + /// # Safety + /// `config.control_address..control_address + control_bytes` must be live mapped-host + /// storage and `config.device_pool_base..+device_pool_bytes` must be mapped in `context`. + pub unsafe fn new( + config: ChannelConfig, + driver: Arc, + context: Handle, + device: i32, + io_backend: Box, + ) -> Result> { + // Query v2 64-bit stream memory op capability (attribute 122, NOT deprecated _V1). + let use_write_value64 = unsafe { + let mut cap = 0i32; + let ok = (driver.device_attribute)( + &mut cap, + CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS, + device, + ) == 0; + ok && cap != 0 && driver.stream_write_value64.is_some() + }; + + let host_pool_usize = usize::try_from(config.host_pool_bytes) + .map_err(|_| Error::execution(ExecutionError::Manifest, "host pool exceeds usize"))?; + let host_pool = unsafe { PinnedHostRegion::allocate(&driver, context, host_pool_usize)? }; + + let max_extent = config.extents.iter().map(|e| e.nbytes).max().unwrap_or(0); + let (bounce_slots, bounce_slot_bytes) = bounce_pool_geometry(max_extent, config.alignment); + let bounce_total = usize::try_from(bounce_slot_bytes.saturating_mul(bounce_slots as u64)) + .map_err(|_| Error::execution(ExecutionError::Manifest, "bounce pool exceeds usize"))?; + let bounce_pool = match unsafe { PinnedHostRegion::allocate(&driver, context, bounce_total) } + { + Ok(pool) => pool, + Err(err) => { + let mut hp = host_pool; + unsafe { hp.release(&driver, context) }; + return Err(err); + } + }; + + let mut copy_stream = null_mut(); + let mut signal_stream = null_mut(); + let stream_result = unsafe { + let mut prev = null_mut(); + let had_prev = (driver.context_get)(&mut prev) == 0; + let res = driver + .check("cuCtxSetCurrent", (driver.context_set)(context)) + .and_then(|()| { + driver.check( + "cuStreamCreate(async_transfer)", + (driver.stream_create)(&mut copy_stream, CU_STREAM_NON_BLOCKING), + ) + }) + .and_then(|()| { + driver.check( + "cuStreamCreate(async_transfer_signal)", + (driver.stream_create)(&mut signal_stream, CU_STREAM_NON_BLOCKING), + ) + }); + if res.is_err() { + if !signal_stream.is_null() { + let _ = (driver.stream_destroy)(signal_stream); + signal_stream = null_mut(); + } + if !copy_stream.is_null() { + let _ = (driver.stream_destroy)(copy_stream); + copy_stream = null_mut(); + } + } + if had_prev && prev != context { + let _ = (driver.context_set)(prev); + } + res + }; + if let Err(err) = stream_result { + let mut hp = host_pool; + let mut bp = bounce_pool; + unsafe { + bp.release(&driver, context); + hp.release(&driver, context); + } + return Err(err); + } + + // Zero control region and publish immutable startup geometry BEFORE tuning graphs launch. + unsafe { + std::ptr::write_bytes(config.control_address as *mut u8, 0, config.control_bytes); + let header = &mut *(config.control_address as *mut ControlHeader); + let mut flags = 0u32; + if config.device_completions_base != 0 { + flags |= FLAG_DEVICE_COMPLETIONS; + } + if use_write_value64 { + flags |= FLAG_STREAM_WRITE_VALUE64; + } + header.abi_version = ABI_VERSION; + header.flags = flags; + header.ring_capacity = config.ring_capacity; + header.completion_slots = config.completion_slots; + header.extent_count = config.extents.len() as u32; + header.alignment = config.alignment; + header.device_pool_base = config.device_pool_base; + header.device_pool_bytes = config.device_pool_bytes; + header.host_pool_bytes = config.host_pool_bytes; + header.device_completions_base = config.device_completions_base; + header + .worker_state + .store(ChannelState::Idle as u32, Ordering::Release); + } + + Ok(Arc::new(Self { + config, + driver, + context, + atomic_state: Arc::new(AtomicU32::new(ChannelState::Idle as u32)), + inner: Mutex::new(WorkerStateInner { + state: ChannelState::Idle, + stop_requested: Arc::new(AtomicBool::new(false)), + join_handle: None, + io_backend: Some(io_backend), + copy_stream, + signal_stream, + host_pool, + bounce_pool, + bounce_slot_bytes, + bounce_slots, + use_write_value64, + released: false, + }), + })) + } + + pub fn name(&self) -> &str { + &self.config.name + } + + pub fn state(&self) -> ChannelState { + ChannelState::from_u32(self.atomic_state.load(Ordering::Acquire)) + } + + pub fn host_pool_bytes(&self) -> u64 { + self.config.host_pool_bytes + } + + pub fn device_pool_bytes(&self) -> u64 { + self.config.device_pool_bytes + } + + /// Start the background host polling & transfer thread (`Idle -> Running`). + /// Idempotent when already `Running`. + pub fn start(&self) -> Result<()> { + let mut inner = self + .inner + .lock() + .unwrap_or_else(|poison| poison.into_inner()); + match inner.state { + ChannelState::Running => return Ok(()), + ChannelState::Idle => {} + ChannelState::Draining => { + return Err(Error::execution( + ExecutionError::Manifest, + "async transfer channel is draining", + )); + } + ChannelState::Stopped => { + return Err(Error::execution( + ExecutionError::Manifest, + "async transfer channel has already been stopped", + )); + } + ChannelState::FailedDrain => { + return Err(Error::execution( + ExecutionError::Drain, + "async transfer channel failed to drain", + )); + } + } + + let io_backend = inner.io_backend.take().ok_or_else(|| { + Error::execution( + ExecutionError::Manifest, + "async transfer I/O backend missing", + ) + })?; + inner.stop_requested.store(false, Ordering::Release); + + let args = WorkerThreadArgs { + config: self.config.clone(), + driver: self.driver.clone(), + context: self.context as usize, + copy_stream: inner.copy_stream as usize, + signal_stream: inner.signal_stream as usize, + host_pool_ptr: inner.host_pool.ptr as usize, + bounce_pool_ptr: inner.bounce_pool.ptr as usize, + bounce_slot_bytes: inner.bounce_slot_bytes, + bounce_slots: inner.bounce_slots, + use_write_value64: inner.use_write_value64, + stop_requested: inner.stop_requested.clone(), + atomic_state: self.atomic_state.clone(), + io_backend, + }; + + let thread_name = format!("flare-xfer-{}", self.config.name); + let handle = thread::Builder::new() + .name(thread_name) + .spawn(move || worker_main(args)) + .map_err(|e| { + Error::execution( + ExecutionError::Manifest, + format!("spawn async transfer worker: {e}"), + ) + })?; + + inner.state = ChannelState::Running; + self.atomic_state + .store(ChannelState::Running as u32, Ordering::Release); + inner.join_handle = Some(handle); + Ok(()) + } + + /// Signal the worker to stop, drain all in-flight storage I/O and Copy Engine work within a + /// bounded deadline, join the thread, and destroy the copy stream and pinned host pools. + /// + /// If drain fails or times out, transitions to `FailedDrain` and retains pinned host memory + /// and CUDA handles until process exit so in-flight DMA/IO cannot hit unmapped pages. + pub fn stop(&self) -> Result<()> { + let mut inner = self + .inner + .lock() + .unwrap_or_else(|poison| poison.into_inner()); + match inner.state { + ChannelState::Idle => { + inner.state = ChannelState::Stopped; + self.atomic_state + .store(ChannelState::Stopped as u32, Ordering::Release); + unsafe { + let header = &*(self.config.control_address as *const ControlHeader); + header + .worker_state + .store(ChannelState::Stopped as u32, Ordering::Release); + } + self.release_owned_resources_locked(&mut inner); + return Ok(()); + } + ChannelState::Stopped => { + self.release_owned_resources_locked(&mut inner); + return Ok(()); + } + ChannelState::FailedDrain => { + return Err(Error::execution( + ExecutionError::Drain, + "async transfer channel failed to drain", + )); + } + ChannelState::Running | ChannelState::Draining => {} + } + + inner.state = ChannelState::Draining; + self.atomic_state + .store(ChannelState::Draining as u32, Ordering::Release); + inner.stop_requested.store(true, Ordering::Release); + + let drained = match inner.join_handle.take() { + Some(handle) => match handle.join() { + Ok(ok) => ok, + Err(_) => false, + }, + None => true, + }; + + if drained { + inner.state = ChannelState::Stopped; + self.atomic_state + .store(ChannelState::Stopped as u32, Ordering::Release); + unsafe { + let header = &*(self.config.control_address as *const ControlHeader); + header + .worker_state + .store(ChannelState::Stopped as u32, Ordering::Release); + } + self.release_owned_resources_locked(&mut inner); + Ok(()) + } else { + inner.state = ChannelState::FailedDrain; + self.atomic_state + .store(ChannelState::FailedDrain as u32, Ordering::Release); + unsafe { + let header = &*(self.config.control_address as *const ControlHeader); + header + .worker_state + .store(ChannelState::FailedDrain as u32, Ordering::Release); + } + // Retain driver and pinned memory until process termination so in-flight hardware + // operations never access unmapped addresses. + std::mem::forget(self.driver.clone()); + Err(Error::execution( + ExecutionError::Drain, + format!( + "async transfer channel {:?} did not confirm hardware drain within {} ms", + self.config.name, + DRAIN_TIMEOUT.as_millis() + ), + )) + } + } + + fn release_owned_resources_locked(&self, inner: &mut WorkerStateInner) { + if inner.released { + return; + } + inner.released = true; + inner.io_backend = None; + unsafe { + let mut prev = null_mut(); + let had_prev = (self.driver.context_get)(&mut prev) == 0; + if (self.driver.context_set)(self.context) == 0 { + if !inner.copy_stream.is_null() { + let _ = (self.driver.stream_destroy)(inner.copy_stream); + inner.copy_stream = null_mut(); + } + if !inner.signal_stream.is_null() { + let _ = (self.driver.stream_destroy)(inner.signal_stream); + inner.signal_stream = null_mut(); + } + } + if had_prev && prev != self.context { + let _ = (self.driver.context_set)(prev); + } + inner.bounce_pool.release(&self.driver, self.context); + inner.host_pool.release(&self.driver, self.context); + } + } + + /// Lock-free telemetry read from the mapped-host control header. + pub fn snapshot(&self) -> AsyncTransferSnapshot { + // SAFETY: Validated mapped-host control header stays alive until `NativeResources` teardown. + let header = unsafe { &*(self.config.control_address as *const ControlHeader) }; + AsyncTransferSnapshot { + name: self.config.name.clone(), + state: self.state(), + device_pool_bytes: self.config.device_pool_bytes, + host_pool_bytes: self.config.host_pool_bytes, + extent_count: self.config.extents.len() as u32, + submitted_cmds: header.submitted_cmds.load(Ordering::Relaxed), + completed_cmds: header.completed_cmds.load(Ordering::Relaxed), + canceled_cmds: header.canceled_cmds.load(Ordering::Relaxed), + rejected_cmds: header.rejected_cmds.load(Ordering::Relaxed), + bytes_disk_to_host: header.bytes_disk_to_host.load(Ordering::Relaxed), + bytes_host_to_dev: header.bytes_host_to_dev.load(Ordering::Relaxed), + bytes_disk_to_dev: header.bytes_disk_to_dev.load(Ordering::Relaxed), + last_error: header.last_error.load(Ordering::Relaxed), + } + } +} + +impl Drop for AsyncTransferRuntime { + fn drop(&mut self) { + let _ = self.stop(); + } +} + +struct WorkerThreadArgs { + config: ChannelConfig, + driver: Arc, + context: usize, + copy_stream: usize, + signal_stream: usize, + host_pool_ptr: usize, + bounce_pool_ptr: usize, + bounce_slot_bytes: u64, + bounce_slots: usize, + use_write_value64: bool, + stop_requested: Arc, + atomic_state: Arc, + io_backend: Box, +} + +fn worker_main(mut args: WorkerThreadArgs) -> bool { + let context = args.context as Handle; + let copy_stream = args.copy_stream as Handle; + let signal_stream = args.signal_stream as Handle; + let driver = &args.driver; + // SAFETY: The worker binds the channel's CUDA context once for its entire lifetime. + if unsafe { (driver.context_set)(context) } != 0 { + return false; + } + + let header = unsafe { &*(args.config.control_address as *const ControlHeader) }; + let ring_base = (args.config.control_address + HEADER_BYTES) as *const TransferCommand; + let ring_mask = (args.config.ring_capacity as u64) - 1; + let host_comp_offset = host_completions_offset(args.config.ring_capacity).unwrap() as usize; + let host_comp_base = (args.config.control_address + host_comp_offset) as *const AtomicU64; + + let mut scheduler = TransferScheduler::new( + DEFAULT_MAX_TOTAL_IO, + DEFAULT_MAX_BG_IO, + DEFAULT_MAX_TOTAL_DMA, + DEFAULT_MAX_BG_DMA, + args.bounce_slots, + ); + let _ = scheduler.start(); + header + .worker_state + .store(ChannelState::Running as u32, Ordering::Release); + + // Pre-create a bounded pool of CUDA events (CU_EVENT_DISABLE_TIMING = 0x2) to track + // Copy Engine completion for bounce-slot reclamation and non-WriteValue64 fallback. + let mut free_events: Vec = Vec::with_capacity(DEFAULT_MAX_TOTAL_DMA); + for _ in 0..DEFAULT_MAX_TOTAL_DMA { + let mut ev = null_mut(); + if unsafe { (driver.event_create)(&mut ev, 0x2) } == 0 { + free_events.push(ev); + } + } + let mut pending_dma_events: VecDeque = + VecDeque::with_capacity(DEFAULT_MAX_TOTAL_DMA); + let mut io_completions: Vec = Vec::with_capacity(32); + + let mut head = header.cmd_head.load(Ordering::Relaxed); + let mut idle_spins: u32 = 0; + + let signal_completion_slot = |slot: u32, value: u64| { + // SAFETY: `slot < completion_slots` was validated before enqueue; `host_comp_base` is + // pinned mapped-host memory owned for the entire `NativeResources` lifetime. + unsafe { + (&*host_comp_base.add(slot as usize)).store(value, Ordering::Release); + if args.config.device_completions_base != 0 { + let dev_addr = args.config.device_completions_base + u64::from(slot) * 8; + if args.use_write_value64 { + let write_fn = driver.stream_write_value64.unwrap(); + let _ = write_fn( + signal_stream, + dev_addr, + value, + CU_STREAM_WRITE_VALUE_DEFAULT, + ); + } else { + let host_ptr = host_comp_base.add(slot as usize) as *const std::ffi::c_void; + let _ = (driver.upload_async)(dev_addr, host_ptr, 8, signal_stream); + } + } + } + }; + + let publish_notice = |notice: CompletionNotice, write_slot: bool| { + if notice.error != ErrorCode::Ok { + header + .last_error + .store(notice.error as u32, Ordering::Release); + } + if notice.bytes_disk_to_host != 0 { + header + .bytes_disk_to_host + .fetch_add(notice.bytes_disk_to_host, Ordering::Relaxed); + } + if notice.bytes_host_to_dev != 0 { + header + .bytes_host_to_dev + .fetch_add(notice.bytes_host_to_dev, Ordering::Relaxed); + } + if notice.bytes_disk_to_dev != 0 { + header + .bytes_disk_to_dev + .fetch_add(notice.bytes_disk_to_dev, Ordering::Relaxed); + } + if write_slot { + if let Some(slot) = notice.completion_slot { + signal_completion_slot(slot, notice.signal_value); + } + } + }; + + let sync_telemetry = |sched: &TransferScheduler| { + header + .submitted_cmds + .store(sched.submitted_cmds, Ordering::Relaxed); + header + .completed_cmds + .store(sched.completed_cmds, Ordering::Relaxed); + header + .canceled_cmds + .store(sched.canceled_cmds, Ordering::Relaxed); + header + .rejected_cmds + .store(sched.rejected_cmds, Ordering::Relaxed); + header.active_inflight.store( + (sched.inflight_io_count() + + sched.inflight_dma_count() + + sched.queued_io_count() + + sched.queued_dma_count()) as u64, + Ordering::Relaxed, + ); + }; + + while !args.stop_requested.load(Ordering::Acquire) { + let mut did_work = false; + + // 1. Observe out-of-band GPU epoch advancement before dispatching queued work. + let gpu_epoch = header.active_epoch.load(Ordering::Acquire); + if gpu_epoch > scheduler.active_epoch() { + scheduler.advance_epoch(gpu_epoch); + did_work = true; + } + + // 2. Drain all newly published ring commands into the preemptible priority queues. + let tail = header.cmd_tail.load(Ordering::Acquire); + let pending = tail.wrapping_sub(head); + if pending > u64::from(args.config.ring_capacity) { + // Producer overran the command ring before the worker consumed older slots; + // skip the overwritten span explicitly instead of executing corrupted entries. + for _ in 0..pending.min(u64::from(args.config.ring_capacity)) { + scheduler.record_rejected(); + } + header + .last_error + .store(ErrorCode::RingOverrun as u32, Ordering::Release); + head = tail; + did_work = true; + } else { + while head < tail { + let slot_idx = (head & ring_mask) as usize; + // SAFETY: Producer wrote command before Release-storing `cmd_tail > head`. + let cmd = unsafe { std::ptr::read_volatile(ring_base.add(slot_idx)) }; + head = head.wrapping_add(1); + did_work = true; + match validate_command( + &cmd, + &args.config.extents, + args.config.host_pool_bytes, + args.config.device_pool_bytes, + args.config.completion_slots, + args.config.alignment, + args.bounce_slot_bytes, + ) { + Ok(validated) => { + if let Some(immediate) = scheduler.enqueue(validated) { + publish_notice(immediate, true); + } + } + Err(code) => { + scheduler.record_rejected(); + header.last_error.store(code as u32, Ordering::Release); + } + } + } + } + if did_work { + header.cmd_head.store(head, Ordering::Release); + } + + // 3. Harvest completed storage reads and advance fused DiskToDev ops to DMA queue. + io_completions.clear(); + if args.io_backend.poll_completions(&mut io_completions).is_ok() && !io_completions.is_empty() + { + did_work = true; + for c in io_completions.drain(..) { + if let Some(notice) = scheduler.complete_io(c.op_id, c.ok) { + publish_notice(notice, true); + } + } + } + + // 4. Harvest completed Copy Engine DMA events (in FIFO stream order). + while let Some(front) = pending_dma_events.front() { + let status = unsafe { (driver.event_query)(front.event) }; + if status == CUDA_ERROR_NOT_READY { + break; + } + let done = pending_dma_events.pop_front().unwrap(); + free_events.push(done.event); + did_work = true; + let ok = status == 0; + match done.completion_action { + EventCompletionAction::None => {} + EventCompletionAction::HostOnly(slot, val) => { + // Device word was already written in-order via cuStreamWriteValue64_v2; + // mirror the host completion word idempotently so host consumers observe it too. + unsafe { + (&*host_comp_base.add(slot as usize)).store(val, Ordering::Release); + } + } + EventCompletionAction::HostAndDevice(slot, val) => { + signal_completion_slot(slot, val); + } + } + if let Some(notice) = scheduler.complete_dma(done.op_id, ok) { + publish_notice(notice, false); + } + } + + // 5. Submit highest-priority eligible Copy Engine DMAs (DEMAND jumps ahead of background). + while !free_events.is_empty() { + let Some(dma) = scheduler.pop_next_dma() else { + break; + }; + did_work = true; + let ev = free_events.pop().unwrap(); + let src_ptr = match (dma.host_offset, dma.bounce_slot) { + (Some(off), _) => (args.host_pool_ptr + off as usize) as *const std::ffi::c_void, + (None, Some(slot)) => { + (args.bounce_pool_ptr + slot * args.bounce_slot_bytes as usize) + as *const std::ffi::c_void + } + (None, None) => { + free_events.push(ev); + if let Some(notice) = scheduler.complete_dma(dma.op_id, false) { + publish_notice(notice, true); + } + continue; + } + }; + let dst_addr = args.config.device_pool_base + dma.device_offset; + let copy_status = unsafe { + (driver.upload_async)(dst_addr, src_ptr, dma.nbytes as usize, copy_stream) + }; + let mut completion_action = EventCompletionAction::None; + let mut signal_status = 0; + if copy_status == 0 { + if let Some(slot) = dma.completion_slot { + if args.use_write_value64 { + let writes_device_word = args.config.device_completions_base != 0; + let target_addr = if writes_device_word { + args.config.device_completions_base + u64::from(slot) * 8 + } else { + // Mapped host completion word address equals host pointer under UVA. + let mut gpu_ptr = 0u64; + let host_ptr = unsafe { host_comp_base.add(slot as usize) } as Handle; + if unsafe { (driver.host_device)(&mut gpu_ptr, host_ptr, 0) } == 0 { + gpu_ptr + } else { + 0 + } + }; + if target_addr != 0 { + let write_fn = driver.stream_write_value64.unwrap(); + signal_status = unsafe { + write_fn( + copy_stream, + target_addr, + dma.signal_value, + CU_STREAM_WRITE_VALUE_DEFAULT, + ) + }; + if signal_status == 0 && writes_device_word { + completion_action = + EventCompletionAction::HostOnly(slot, dma.signal_value); + } + } else { + completion_action = + EventCompletionAction::HostAndDevice(slot, dma.signal_value); + } + } else { + completion_action = + EventCompletionAction::HostAndDevice(slot, dma.signal_value); + } + } + } + let rec_status = if copy_status == 0 && signal_status == 0 { + unsafe { (driver.event_record)(ev, copy_stream) } + } else { + -1 + }; + if copy_status == 0 && signal_status == 0 && rec_status == 0 { + pending_dma_events.push_back(PendingEventDma { + op_id: dma.op_id, + event: ev, + completion_action, + }); + } else { + free_events.push(ev); + if let Some(notice) = scheduler.complete_dma(dma.op_id, false) { + publish_notice(notice, true); + } + } + } + + // 6. Submit highest-priority eligible storage reads (DEMAND jumps ahead of background). + let mut submitted_io = false; + while let Some(io_op) = scheduler.pop_next_io() { + did_work = true; + let dst_ptr = match (io_op.host_offset, io_op.bounce_slot) { + (Some(off), _) => (args.host_pool_ptr + off as usize) as *mut u8, + (None, Some(slot)) => { + (args.bounce_pool_ptr + slot * args.bounce_slot_bytes as usize) as *mut u8 + } + (None, None) => { + if let Some(notice) = scheduler.complete_io(io_op.op_id, false) { + publish_notice(notice, true); + } + continue; + } + }; + let res = unsafe { + args.io_backend.submit_read( + io_op.op_id, + io_op.extent.file_index, + io_op.extent.offset, + dst_ptr, + io_op.extent.nbytes, + ) + }; + if res.is_ok() { + submitted_io = true; + } else if let Some(notice) = scheduler.complete_io(io_op.op_id, false) { + publish_notice(notice, true); + } + } + if submitted_io { + if args.io_backend.flush().is_err() { + header + .last_error + .store(ErrorCode::IoFailure as u32, Ordering::Release); + } + } + + if did_work { + sync_telemetry(&scheduler); + idle_spins = 0; + } else { + idle_spins = idle_spins.saturating_add(1); + let has_inflight = + scheduler.inflight_io_count() > 0 || scheduler.inflight_dma_count() > 0; + if has_inflight { + if idle_spins < BUSY_SPIN_LIMIT { + std::hint::spin_loop(); + } else if idle_spins < IDLE_SPIN_LIMIT { + thread::yield_now(); + } else { + thread::sleep(BUSY_PARK_INTERVAL); + } + } else if idle_spins < IDLE_SPIN_LIMIT { + std::hint::spin_loop(); + } else { + thread::sleep(IDLE_PARK_INTERVAL); + } + } + } + + // Shutdown drain sequence: drop queued work, cancel/drain storage I/O, drain Copy Engine stream. + let _ = scheduler.begin_drain(); + header + .worker_state + .store(ChannelState::Draining as u32, Ordering::Release); + args.atomic_state + .store(ChannelState::Draining as u32, Ordering::Release); + + io_completions.clear(); + let io_drained = args + .io_backend + .cancel_and_drain(DRAIN_TIMEOUT, &mut io_completions); + let _ = args.io_backend.poll_completions(&mut io_completions); + for c in io_completions.drain(..) { + let _ = scheduler.complete_io(c.op_id, c.ok); + } + + let deadline = Instant::now() + DRAIN_TIMEOUT; + let mut stream_drained = false; + loop { + let copy_status = unsafe { (driver.stream_query)(copy_stream) }; + let sig_status = unsafe { (driver.stream_query)(signal_stream) }; + if copy_status == 0 && sig_status == 0 { + stream_drained = true; + break; + } + let copy_ok = copy_status == 0 || copy_status == CUDA_ERROR_NOT_READY; + let sig_ok = sig_status == 0 || sig_status == CUDA_ERROR_NOT_READY; + if !copy_ok || !sig_ok || Instant::now() >= deadline { + break; + } + thread::sleep(Duration::from_millis(1)); + } + if stream_drained { + while let Some(done) = pending_dma_events.pop_front() { + let _ = scheduler.complete_dma(done.op_id, true); + free_events.push(done.event); + } + for ev in free_events.drain(..) { + unsafe { + let _ = (driver.event_destroy)(ev); + } + } + } + + let ok = scheduler.finish_drain(io_drained && stream_drained).is_ok(); + sync_telemetry(&scheduler); + ok +} + +#[cfg(test)] +mod cuda_tests { + use super::*; + use crate::{ + async_transfer::ring::{ + BOUNCE_HOST_OFFSET, NO_COMPLETION_SLOT, Opcode, Priority, required_control_bytes, + }, + runtime_core::driver::CU_MEMHOSTREGISTER_DEVICEMAP, + }; + use std::io::Write; + + #[test] + fn live_cuda_async_transfer_end_to_end() { + if std::env::var_os("FLARE_RUN_CUDA_TESTS").as_deref() != Some(std::ffi::OsStr::new("1")) { + return; + } + let driver = Arc::new(Driver::load().expect("load CUDA driver")); + unsafe { + driver.check("cuInit", (driver.init)(0)).unwrap(); + } + let mut device = 0; + let mut context = null_mut(); + unsafe { + driver.check("cuDeviceGet", (driver.device)(&mut device, 0)).unwrap(); + driver + .check("cuCtxCreate_v2", (driver.context_create)(&mut context, 0, device)) + .unwrap(); + } + + // Create a real O_DIRECT-compatible file with 4 distinct 64 KiB extents. + let dir = std::env::temp_dir().join(format!( + "flare-async-xfer-cuda-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let file_path = dir.join("extents.bin"); + let extent_bytes: usize = 64 * 1024; + let mut patterns: Vec> = Vec::new(); + { + let mut f = std::fs::File::create(&file_path).unwrap(); + for ext in 0..4u8 { + let buf: Vec = (0..extent_bytes) + .map(|i| ext.wrapping_mul(53).wrapping_add((i & 0xff) as u8)) + .collect(); + f.write_all(&buf).unwrap(); + patterns.push(buf); + } + f.sync_all().unwrap(); + } + + let open_direct_file = || -> std::fs::File { + #[cfg(target_os = "linux")] + { + use std::os::unix::fs::OpenOptionsExt; + std::fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_DIRECT) + .open(&file_path) + .unwrap() + } + #[cfg(not(target_os = "linux"))] + { + std::fs::File::open(&file_path).unwrap() + } + }; + + let make_backend = |f: std::fs::File| -> Box { + #[cfg(target_os = "linux")] + { + Box::new( + crate::async_transfer::io_backend::linux_uring::IoUringBackend::new(vec![f]) + .unwrap(), + ) + } + #[cfg(not(target_os = "linux"))] + { + Box::new(crate::async_transfer::io_backend::PreadBackend::new(vec![f])) + } + }; + + let extents: Vec = (0..4u64) + .map(|i| ExtentEntry { + file_index: 0, + offset: i * extent_bytes as u64, + nbytes: extent_bytes as u64, + }) + .collect(); + + // Allocate device pool, device completion array, and mapped-host control region. + let dev_pool_bytes = 2usize << 20; + let completion_slots = 32u32; + let ring_capacity = 64u32; + let ctrl_bytes = required_control_bytes(ring_capacity, completion_slots).unwrap() as usize; + let ctrl_alloc_bytes = ctrl_bytes.div_ceil(4096) * 4096; + + let mut dev_pool = 0u64; + let mut dev_comp = 0u64; + let ctrl_ptr = unsafe { + driver + .check("cuMemAlloc_v2(pool)", (driver.allocate)(&mut dev_pool, dev_pool_bytes)) + .unwrap(); + driver + .check( + "cuMemAlloc_v2(comp)", + (driver.allocate)(&mut dev_comp, completion_slots as usize * 8), + ) + .unwrap(); + driver + .check("cuMemsetD8_v2(pool)", (driver.zero)(dev_pool, 0, dev_pool_bytes)) + .unwrap(); + driver + .check( + "cuMemsetD8_v2(comp)", + (driver.zero)(dev_comp, 0, completion_slots as usize * 8), + ) + .unwrap(); + let p = libc::mmap( + null_mut(), + ctrl_alloc_bytes, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, + -1, + 0, + ); + assert_ne!(p, libc::MAP_FAILED); + driver + .check( + "cuMemHostRegister_v2(ctrl)", + (driver.host_register)( + p, + ctrl_alloc_bytes, + CU_MEMHOSTREGISTER_PORTABLE | CU_MEMHOSTREGISTER_DEVICEMAP, + ), + ) + .unwrap(); + p + }; + + let push_cmd = |ctrl_addr: usize, cmd: TransferCommand| { + let header = unsafe { &*(ctrl_addr as *const ControlHeader) }; + let ring_base = (ctrl_addr + HEADER_BYTES) as *mut TransferCommand; + let tail = header.cmd_tail.load(Ordering::Relaxed); + let idx = (tail & (ring_capacity as u64 - 1)) as usize; + unsafe { + std::ptr::write_volatile(ring_base.add(idx), cmd); + } + header.cmd_tail.store(tail + 1, Ordering::Release); + }; + + let wait_host_comp = |ctrl_addr: usize, slot: u32, expected: u64| { + let off = host_completions_offset(ring_capacity).unwrap() as usize; + let ptr = (ctrl_addr + off) as *const AtomicU64; + let start = Instant::now(); + while start.elapsed() < Duration::from_secs(5) { + if unsafe { (&*ptr.add(slot as usize)).load(Ordering::Acquire) } == expected { + return; + } + thread::sleep(Duration::from_micros(50)); + } + panic!("timed out waiting for host completion slot {slot} == {expected}"); + }; + + let wait_dev_comp = |slot: u32, expected: u64| { + let start = Instant::now(); + let mut val = 0u64; + while start.elapsed() < Duration::from_secs(5) { + unsafe { + driver + .check( + "cuMemcpyDtoH_v2(comp)", + (driver.download)( + (&mut val as *mut u64).cast(), + dev_comp + u64::from(slot) * 8, + 8, + ), + ) + .unwrap(); + } + if val == expected { + return; + } + thread::sleep(Duration::from_micros(50)); + } + panic!("timed out waiting for device completion slot {slot} == {expected} (got {val})"); + }; + + // 1. Test 3-tier path: DISK_TO_HOST -> HOST_TO_DEV -> cuStreamWriteValue64_v2 + invalid cmd rejection. + { + let cfg = ChannelConfig { + name: "cuda-3tier".into(), + device_pool_base: dev_pool, + device_pool_bytes: dev_pool_bytes as u64, + host_pool_bytes: 2 << 20, + control_address: ctrl_ptr as usize, + control_bytes: ctrl_alloc_bytes, + device_completions_base: dev_comp, + completion_slots, + ring_capacity, + alignment: 4096, + extents: extents.clone(), + }; + let rt = unsafe { + AsyncTransferRuntime::new( + cfg, + driver.clone(), + context, + device, + make_backend(open_direct_file()), + ) + .unwrap() + }; + let header = unsafe { &*(ctrl_ptr as *const ControlHeader) }; + assert_eq!(header.abi_version, ABI_VERSION); + assert_eq!(header.device_pool_bytes, dev_pool_bytes as u64); + assert_eq!(header.host_pool_bytes, 2 << 20); + assert_eq!(header.extent_count, 4); + assert_ne!(header.flags & FLAG_DEVICE_COMPLETIONS, 0); + assert_ne!(header.flags & FLAG_STREAM_WRITE_VALUE64, 0); + + rt.start().unwrap(); + + // DISK_TO_HOST extent 1 -> host_offset 0. + push_cmd( + ctrl_ptr as usize, + TransferCommand { + opcode: Opcode::DiskToHost as u32, + priority: Priority::Warm as u32, + extent_id: 1, + completion_slot: 0, + host_offset: 0, + device_offset: 0, + nbytes: extent_bytes as u64, + epoch: 1, + signal_value: 1001, + _reserved: 0, + }, + ); + wait_host_comp(ctrl_ptr as usize, 0, 1001); + wait_dev_comp(0, 1001); + + // HOST_TO_DEV host_offset 0 -> device_offset 64 KiB, signaled via cuStreamWriteValue64_v2. + push_cmd( + ctrl_ptr as usize, + TransferCommand { + opcode: Opcode::HostToDev as u32, + priority: Priority::Demand as u32, + extent_id: 0, + completion_slot: 1, + host_offset: 0, + device_offset: extent_bytes as u64, + nbytes: extent_bytes as u64, + epoch: 1, + signal_value: 2002, + _reserved: 0, + }, + ); + wait_dev_comp(1, 2002); + wait_host_comp(ctrl_ptr as usize, 1, 2002); + + let mut readback = vec![0u8; extent_bytes]; + unsafe { + driver + .check( + "cuMemcpyDtoH_v2(ext1)", + (driver.download)( + readback.as_mut_ptr().cast(), + dev_pool + extent_bytes as u64, + extent_bytes, + ), + ) + .unwrap(); + } + assert_eq!(readback, patterns[1]); + + // Fused DISK_TO_DEV with caller host_offset (extent 2 -> host 64 KiB -> dev 128 KiB). + push_cmd( + ctrl_ptr as usize, + TransferCommand { + opcode: Opcode::DiskToDev as u32, + priority: Priority::Demand as u32, + extent_id: 2, + completion_slot: 2, + host_offset: extent_bytes as u64, + device_offset: 2 * extent_bytes as u64, + nbytes: extent_bytes as u64, + epoch: 2, + signal_value: 3003, + _reserved: 0, + }, + ); + wait_dev_comp(2, 3003); + wait_host_comp(ctrl_ptr as usize, 2, 3003); + unsafe { + driver + .check( + "cuMemcpyDtoH_v2(ext2)", + (driver.download)( + readback.as_mut_ptr().cast(), + dev_pool + 2 * extent_bytes as u64, + extent_bytes, + ), + ) + .unwrap(); + } + assert_eq!(readback, patterns[2]); + + // Out-of-range extent is rejected cleanly without harming the channel. + push_cmd( + ctrl_ptr as usize, + TransferCommand { + opcode: Opcode::DiskToHost as u32, + priority: Priority::Warm as u32, + extent_id: 99, + completion_slot: NO_COMPLETION_SLOT, + host_offset: 0, + device_offset: 0, + nbytes: extent_bytes as u64, + epoch: 2, + signal_value: 0, + _reserved: 0, + }, + ); + // Follow with CancelEpoch so we have a deterministic barrier after the invalid command. + push_cmd( + ctrl_ptr as usize, + TransferCommand { + opcode: Opcode::CancelEpoch as u32, + priority: Priority::Demand as u32, + extent_id: 0, + completion_slot: 3, + host_offset: 0, + device_offset: 0, + nbytes: 0, + epoch: 5, + signal_value: 5005, + _reserved: 0, + }, + ); + wait_host_comp(ctrl_ptr as usize, 3, 5005); + wait_dev_comp(3, 5005); + + let snap = rt.snapshot(); + assert_eq!(snap.rejected_cmds, 1); + assert_eq!(snap.last_error, ErrorCode::ExtentOutOfRange as u32); + assert_eq!(snap.bytes_disk_to_host, extent_bytes as u64); + assert_eq!(snap.bytes_host_to_dev, extent_bytes as u64); + assert_eq!(snap.bytes_disk_to_dev, extent_bytes as u64); + + rt.stop().unwrap(); + assert_eq!(rt.state(), ChannelState::Stopped); + assert_eq!(header.active_inflight.load(Ordering::Acquire), 0); + } + + // 2. Test RAM=0 fused DISK_TO_DEV using internal pinned bounce pool (BOUNCE_HOST_OFFSET). + { + unsafe { + driver + .check("cuMemsetD8_v2(comp)", (driver.zero)(dev_comp, 0, completion_slots as usize * 8)) + .unwrap(); + } + let cfg = ChannelConfig { + name: "cuda-ram0-bounce".into(), + device_pool_base: dev_pool, + device_pool_bytes: dev_pool_bytes as u64, + host_pool_bytes: 0, + control_address: ctrl_ptr as usize, + control_bytes: ctrl_alloc_bytes, + device_completions_base: dev_comp, + completion_slots, + ring_capacity, + alignment: 4096, + extents: extents.clone(), + }; + let rt = unsafe { + AsyncTransferRuntime::new( + cfg, + driver.clone(), + context, + device, + make_backend(open_direct_file()), + ) + .unwrap() + }; + assert_eq!(rt.host_pool_bytes(), 0); + rt.start().unwrap(); + + push_cmd( + ctrl_ptr as usize, + TransferCommand { + opcode: Opcode::DiskToDev as u32, + priority: Priority::Demand as u32, + extent_id: 3, + completion_slot: 4, + host_offset: BOUNCE_HOST_OFFSET, + device_offset: 3 * extent_bytes as u64, + nbytes: extent_bytes as u64, + epoch: 1, + signal_value: 4004, + _reserved: 0, + }, + ); + wait_dev_comp(4, 4004); + wait_host_comp(ctrl_ptr as usize, 4, 4004); + + let mut readback = vec![0u8; extent_bytes]; + unsafe { + driver + .check( + "cuMemcpyDtoH_v2(ext3)", + (driver.download)( + readback.as_mut_ptr().cast(), + dev_pool + 3 * extent_bytes as u64, + extent_bytes, + ), + ) + .unwrap(); + } + assert_eq!(readback, patterns[3]); + rt.stop().unwrap(); + assert_eq!(rt.state(), ChannelState::Stopped); + let header = unsafe { &*(ctrl_ptr as *const ControlHeader) }; + assert_eq!(header.active_inflight.load(Ordering::Acquire), 0); + } + + unsafe { + let _ = (driver.host_unregister)(ctrl_ptr); + libc::munmap(ctrl_ptr, ctrl_alloc_bytes); + let _ = (driver.free)(dev_comp); + let _ = (driver.free)(dev_pool); + let _ = (driver.context_destroy)(context); + } + let _ = std::fs::remove_dir_all(&dir); + } +} + +#[cfg(test)] +mod unit_tests { + use super::*; + + #[test] + fn bounce_pool_geometry_rounds_before_capping_and_never_exceeds_reserve() { + // Normal 4 KiB alignment with 16 MiB extent stays bounded below 512 MiB. + assert_eq!( + bounce_pool_geometry(16 << 20, 4096), + (DEFAULT_BOUNCE_SLOTS, 16 << 20) + ); + assert_eq!(max_bounce_pool_bytes(4096), MAX_BOUNCE_POOL_BYTES); + + // Extent larger than MAX_BOUNCE_SLOT_BYTES disables bounce staging instead of truncating. + assert_eq!(bounce_pool_geometry((32 << 20) + 4096, 4096), (0, 0)); + + // Large alignment (> 32 MiB) disables bounce staging in both allocator and VRAM reserve. + assert_eq!(bounce_pool_geometry(4096, 64 << 20), (0, 0)); + assert_eq!(max_bounce_pool_bytes(64 << 20), 0); + assert_eq!(bounce_pool_geometry(4096, 1 << 30), (0, 0)); + assert_eq!(max_bounce_pool_bytes(1 << 30), 0); + + // Zero extent or invalid alignment disables bounce staging. + assert_eq!(bounce_pool_geometry(0, 4096), (0, 0)); + assert_eq!(bounce_pool_geometry(4096, 0), (0, 0)); + assert_eq!(bounce_pool_geometry(4096, 6000), (0, 0)); + } +} diff --git a/helios/src/core/export.rs b/helios/src/core/export.rs index 1f1b23b2e..afb6f165f 100644 --- a/helios/src/core/export.rs +++ b/helios/src/core/export.rs @@ -2869,6 +2869,7 @@ mod tests { roce: None, prepared_weights: None, compressed_prepared_weights: None, + external_extents: vec![], }; let request = PublishRequest { core, diff --git a/helios/src/core/protection.rs b/helios/src/core/protection.rs index e7059f30e..1dff95b8c 100644 --- a/helios/src/core/protection.rs +++ b/helios/src/core/protection.rs @@ -2020,6 +2020,7 @@ mod tests { roce: None, prepared_weights: None, compressed_prepared_weights: None, + external_extents: vec![], } } diff --git a/helios/src/core/reader.rs b/helios/src/core/reader.rs index 3cb09ad14..270e77fc6 100644 --- a/helios/src/core/reader.rs +++ b/helios/src/core/reader.rs @@ -222,6 +222,12 @@ pub fn required_payloads(core: &VerifiedCore) -> Result>> { add(global.contents.as_ref())?; } } + for table in &rank.external_extents { + add(table.directory.as_ref())?; + for segment in &table.segments { + add(Some(segment))?; + } + } } if let Some(engram) = core .deployment() diff --git a/helios/src/core/schema.rs b/helios/src/core/schema.rs index c66f43265..0679486e7 100644 --- a/helios/src/core/schema.rs +++ b/helios/src/core/schema.rs @@ -427,7 +427,7 @@ fn allocation_extent(allocation: &wire::Allocation) -> Result { || allocation.address.is_none() || !allocation.relocations.is_empty() || allocation.memory != runtime::Memory::Device as i32 - || !matches!(sizing.capacity, 0 | 1) + || !matches!(sizing.capacity, 0 | 1 | 2) || sizing.unit_bytes == 0 || sizing.maximum == 0 { @@ -640,6 +640,41 @@ pub fn validate_rank( if let Some(weights) = &body.prepared_weights { validate_rank_prepared_weights(body, weights)?; } + validate_external_extents(body, catalog)?; + Ok(()) +} + +fn validate_external_extents(body: &wire::RankBody, catalog: &Catalog) -> Result<()> { + let roles = [ + wire::PayloadRole::Weights, + wire::PayloadRole::TunedWeights, + wire::PayloadRole::InitialState, + ]; + let mut channels = BTreeSet::new(); + for table in &body.external_extents { + bounded_name(&table.channel, 128, "external extent channel")?; + if !channels.insert(table.channel.as_str()) { + return Err(invalid("duplicate external extent channel")); + } + let directory = table + .directory + .as_ref() + .ok_or_else(|| invalid("external extent table lacks a directory payload"))?; + let dir_bytes = catalog.check_use(directory, &roles)?; + if dir_bytes % (crate::async_transfer::EXTENT_ENTRY_BYTES as u64) != 0 { + return Err(invalid( + "external extent directory length is not a multiple of entry size", + )); + } + if table.segments.is_empty() && dir_bytes != 0 { + return Err(invalid( + "nonempty external extent directory requires backing segments", + )); + } + for segment in &table.segments { + catalog.check_use(segment, &roles)?; + } + } Ok(()) } diff --git a/helios/src/lib.rs b/helios/src/lib.rs index 9e2ee8dca..a023e4b58 100644 --- a/helios/src/lib.rs +++ b/helios/src/lib.rs @@ -3,6 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ +pub mod async_transfer; pub mod cache; #[cfg(all(test, feature = "frontend"))] #[path = "../tests/support/templates.rs"] diff --git a/helios/src/runtime_core/cache_memory.rs b/helios/src/runtime_core/cache_memory.rs index e71e2ab44..cace47362 100644 --- a/helios/src/runtime_core/cache_memory.rs +++ b/helios/src/runtime_core/cache_memory.rs @@ -1338,6 +1338,7 @@ mod tests { execution: None, context: Context::default(), allocations: vec![], + external_extents: vec![], }; let mut owner = NativeResources::initialize(&core, 0).unwrap(); let properties = AllocationProperties { diff --git a/helios/src/runtime_core/describe.rs b/helios/src/runtime_core/describe.rs index 56aaf6a83..8d11be769 100644 --- a/helios/src/runtime_core/describe.rs +++ b/helios/src/runtime_core/describe.rs @@ -1087,6 +1087,7 @@ mod tests { execution: Some(wire::Execution { tuning_graphs: vec![], persistent_workers: vec![], + async_transfers: vec![], abi_version: 9, completion_token_capacity: 0, max_active: 32, diff --git a/helios/src/runtime_core/driver.rs b/helios/src/runtime_core/driver.rs index a9cc85ecb..91538b383 100644 --- a/helios/src/runtime_core/driver.rs +++ b/helios/src/runtime_core/driver.rs @@ -91,6 +91,14 @@ pub const CU_DEV_SM_RESOURCE_GROUP_BACKFILL: c_uint = 1; pub const CU_GREEN_CTX_DEFAULT_STREAM: c_uint = 1; /// `CU_STREAM_NON_BLOCKING`: required flag for streams created on a green context. pub const CU_STREAM_NON_BLOCKING: c_uint = 1; +/// `CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS`: device supports v2 64-bit stream memory ops. +pub const CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS: c_int = 122; +/// `CU_STREAM_WRITE_VALUE_DEFAULT`: release-ordered 64-bit stream write after prior stream work. +pub const CU_STREAM_WRITE_VALUE_DEFAULT: c_uint = 0x0; +/// `CU_MEMHOSTREGISTER_PORTABLE`: register pinned host memory usable across all CUDA contexts. +pub const CU_MEMHOSTREGISTER_PORTABLE: c_uint = 0x1; +/// `CU_MEMHOSTREGISTER_DEVICEMAP`: map registered host memory into the device address space. +pub const CU_MEMHOSTREGISTER_DEVICEMAP: c_uint = 0x2; /// `CUDA_ERROR_NOT_READY`: asynchronous stream or event operation has not completed. pub const CUDA_ERROR_NOT_READY: c_int = 600; /// `CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE`: primary context flags were already fixed by an active user. @@ -205,6 +213,8 @@ macro_rules! driver { pub struct Driver { _library: Library, pub green_ctx: Option, + pub stream_write_value64: + Option c_int>, $(pub $field: unsafe extern "C" fn($($arg),*) -> c_int,)* } @@ -217,7 +227,16 @@ macro_rules! driver { $(let $field = *library.get(concat!($symbol, "\0").as_bytes()) .map_err(|e| e.to_string())?;)* let green_ctx = GreenCtxDriver::try_load(&library); - Ok(Self { _library: library, green_ctx, $($field,)* }) + let stream_write_value64 = library + .get(b"cuStreamWriteValue64_v2\0") + .ok() + .map(|symbol| *symbol); + Ok(Self { + _library: library, + green_ctx, + stream_write_value64, + $($field,)* + }) } } } @@ -271,6 +290,7 @@ driver! { stream_end_capture: "cuStreamEndCapture"(Handle, *mut Handle); event_create: "cuEventCreate"(*mut Handle, c_uint); event_record: "cuEventRecord"(Handle, Handle); + event_query: "cuEventQuery"(Handle); event_sync: "cuEventSynchronize"(Handle); event_destroy: "cuEventDestroy_v2"(Handle); download: "cuMemcpyDtoH_v2"(*mut c_void, u64, usize); diff --git a/helios/src/runtime_core/engram.rs b/helios/src/runtime_core/engram.rs index 08fe8e248..b054f8c84 100644 --- a/helios/src/runtime_core/engram.rs +++ b/helios/src/runtime_core/engram.rs @@ -624,8 +624,10 @@ mod tests { }], tuning_graphs: vec![], persistent_workers: vec![], + async_transfers: vec![], }), context: Default::default(), + external_extents: vec![], events: vec!["engram_1_ready".into()], }; (catalog, core) diff --git a/helios/src/runtime_core/format.rs b/helios/src/runtime_core/format.rs index bc42e5821..066a804d2 100644 --- a/helios/src/runtime_core/format.rs +++ b/helios/src/runtime_core/format.rs @@ -12,6 +12,14 @@ pub(super) fn invalid(message: impl Into) -> Error { Error::execution(ExecutionError::Manifest, message) } +/// Resolved external extent table for one `AsyncTransfer` channel in payload-format cores. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct ExternalExtentTable { + pub channel: String, + pub segments: Vec, + pub directory: String, +} + #[derive(Debug)] pub(super) struct Core { pub resources: HashMap, @@ -24,6 +32,7 @@ pub(super) struct Core { pub execution: Option, pub context: Context, pub events: Vec, + pub external_extents: Vec, } #[derive(Debug, Default)] @@ -304,7 +313,7 @@ impl Core { || a.file.is_some() || !a.data_spans.is_empty() || !a.relocations.is_empty() - || ![0, 1].contains(&s.capacity) + || ![0, 1, 2].contains(&s.capacity) || s.unit_bytes == 0 || s.maximum == 0 || s.maximum > i32::MAX as u64 @@ -507,6 +516,7 @@ impl Core { } if let Some(execution) = self.execution.as_ref() { super::protobuf::validate_persistent_workers(self, execution)?; + super::protobuf::validate_async_transfers(self, execution)?; } Ok(()) } @@ -653,6 +663,7 @@ mod tests { reservations: vec![], execution: None, context: Context::default(), + external_extents: vec![], graphs: vec![Graph { name: "copy".into(), flags: 0, diff --git a/helios/src/runtime_core/limits.rs b/helios/src/runtime_core/limits.rs index 9b86f7f86..bb60c3705 100644 --- a/helios/src/runtime_core/limits.rs +++ b/helios/src/runtime_core/limits.rs @@ -49,10 +49,26 @@ pub enum MemoryLimit { impl MemoryLimit { pub(super) fn validate(self) -> crate::Result<()> { + self.validate_with(false) + } + + fn validate_with(self, allow_zero: bool) -> crate::Result<()> { match self { - Self::Bytes(0) => Err("occupied memory limit must be positive".into()), - Self::Fraction(f) if !f.is_finite() || !(0.0 < f && f <= 1.0) => { - Err("memory fraction must be greater than zero and at most one".into()) + Self::Bytes(0) if !allow_zero => Err("occupied memory limit must be positive".into()), + Self::Fraction(f) + if !f.is_finite() + || if allow_zero { + !(0.0..=1.0).contains(&f) + } else { + !(0.0 < f && f <= 1.0) + } => + { + Err(if allow_zero { + "pool memory fraction must be between zero and one" + } else { + "memory fraction must be greater than zero and at most one" + } + .into()) } _ => Ok(()), } @@ -65,16 +81,20 @@ impl MemoryLimit { Self::Reserve(_) => None, } } -} -impl FromStr for MemoryLimit { - type Err = String; - - fn from_str(value: &str) -> Result { + fn parse_with(value: &str, allow_zero: bool) -> Result { let value = value.trim(); let invalid = || { - "memory limit must be a positive size (30G), a reserve (-30G), or a fraction greater than zero and at most one (0.8)".to_owned() + if allow_zero { + "pool memory limit must be a nonnegative size (0, 12G), a reserve (-8G), or a fraction in [0, 1] (0.25)" + } else { + "memory limit must be a positive size (30G), a reserve (-30G), or a fraction greater than zero and at most one (0.8)" + } + .to_owned() }; + if allow_zero && value == "0" { + return Ok(Self::Bytes(0)); + } let (reserve, number) = match value.strip_prefix('-') { Some(number) => (true, number), None => (false, value), @@ -82,7 +102,7 @@ impl FromStr for MemoryLimit { // Bare numbers are fractions. Byte sizes require a unit to avoid ambiguity at 1. if number.chars().any(|c| c.is_ascii_alphabetic()) { let bytes = crate::offload::parse_size(number).map_err(|_| invalid())?; - if bytes == 0 && !reserve { + if bytes == 0 && !reserve && !allow_zero { return Err(invalid()); } Ok(if reserve { @@ -92,10 +112,15 @@ impl FromStr for MemoryLimit { }) } else { let fraction = number.parse::().map_err(|_| invalid())?; + let in_range = if allow_zero { + (0.0..=1.0).contains(&fraction) + } else { + 0.0 < fraction && fraction <= 1.0 + }; if reserve || !number.chars().all(|c| c.is_ascii_digit() || c == '.') || !fraction.is_finite() - || !(0.0 < fraction && fraction <= 1.0) + || !in_range { return Err(invalid()); } @@ -104,6 +129,14 @@ impl FromStr for MemoryLimit { } } +impl FromStr for MemoryLimit { + type Err = String; + + fn from_str(value: &str) -> Result { + Self::parse_with(value, false) + } +} + impl fmt::Display for MemoryLimit { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { @@ -125,6 +158,46 @@ impl fmt::Display for MemoryLimit { } } +/// A byte pool budget for `Capacity::DEVICE_POOL` or `AsyncTransfer` host RAM pools. +/// +/// Wraps [`MemoryLimit`] while allowing an explicit zero (`0` or `0G`) to disable the +/// corresponding runtime byte pool. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PoolMemoryLimit(pub MemoryLimit); + +impl PoolMemoryLimit { + pub(super) fn validate(self) -> crate::Result<()> { + self.0.validate_with(true) + } + + /// Compute the upper byte cap given `available` and `total` memory for the tier. + pub(super) fn cap_bytes(self, available: u64, total: u64) -> u64 { + match self.0 { + MemoryLimit::Bytes(bytes) => bytes, + MemoryLimit::Reserve(reserve) => available.saturating_sub(reserve), + MemoryLimit::Fraction(fraction) => ((total as f64) * fraction).floor().max(0.0) as u64, + } + } +} + +impl FromStr for PoolMemoryLimit { + type Err = String; + + fn from_str(value: &str) -> Result { + MemoryLimit::parse_with(value, true).map(Self) + } +} + +impl fmt::Display for PoolMemoryLimit { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.0 { + MemoryLimit::Bytes(0) => f.write_str("0"), + MemoryLimit::Fraction(fraction) if fraction == 0.0 => f.write_str("0.0"), + other => write!(f, "{other}"), + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -161,4 +234,27 @@ mod tests { assert!(text.parse::().is_err(), "{text}"); } } + + #[test] + fn pool_memory_limits_allow_zero_and_compute_caps() { + for (text, expected) in [ + ("0", PoolMemoryLimit(MemoryLimit::Bytes(0))), + ("0G", PoolMemoryLimit(MemoryLimit::Bytes(0))), + ("0.0", PoolMemoryLimit(MemoryLimit::Fraction(0.0))), + ("12G", PoolMemoryLimit(MemoryLimit::Bytes(12 << 30))), + ("-8G", PoolMemoryLimit(MemoryLimit::Reserve(8 << 30))), + ] { + let parsed: PoolMemoryLimit = text.parse().unwrap(); + assert_eq!(parsed, expected); + assert_eq!(parsed.to_string().parse::().unwrap(), parsed); + assert!(parsed.validate().is_ok()); + } + assert_eq!(PoolMemoryLimit(MemoryLimit::Bytes(0)).cap_bytes(100, 200), 0); + assert_eq!(PoolMemoryLimit(MemoryLimit::Bytes(50)).cap_bytes(100, 200), 50); + assert_eq!(PoolMemoryLimit(MemoryLimit::Reserve(40)).cap_bytes(100, 200), 60); + assert_eq!(PoolMemoryLimit(MemoryLimit::Reserve(150)).cap_bytes(100, 200), 0); + assert_eq!(PoolMemoryLimit(MemoryLimit::Fraction(0.25)).cap_bytes(100, 200), 50); + assert!("-0.5".parse::().is_err()); + assert!("1.1".parse::().is_err()); + } } diff --git a/helios/src/runtime_core/memory.rs b/helios/src/runtime_core/memory.rs index 120c43509..abaf0b55c 100644 --- a/helios/src/runtime_core/memory.rs +++ b/helios/src/runtime_core/memory.rs @@ -22,6 +22,75 @@ use crate::{ // Graphs are uploaded before sizing caches; leave room for driver bookkeeping // and the execution streams and events created when the server starts. pub(super) const HEADROOM_BYTES: u64 = 64 << 20; +// Base per-rank device margin when `Execution.async_transfers` channels are present, +// covering Copy Engine/signal/replay streams, events, and driver bookkeeping beyond +// the 1/512 GPU page-table overhead of CUDA-registered pinned host pools. +const ASYNC_TRANSFER_DEVICE_MARGIN_BYTES: u64 = 256 << 20; + +/// Host memory budgets planned during cache sizing so post-sizing setup stages +/// never exceed the device page-table headroom reserved for them. +pub(super) struct PlannedHostBudgets { + pub offload_host: Option, + pub async_transfer_host_caps: Vec, +} + +/// Per-rank `(available, total)` host RAM for sizing pinned `AsyncTransfer` host pools. +fn async_transfer_host_ram(local_ranks: usize) -> (u64, u64) { + let local_ranks = local_ranks.max(1) as u64; + let (host_available, host_total) = + flare_selene::offload::host_pool_budget_and_total(0).unwrap_or((0, 0)); + (host_available / local_ranks, host_total / local_ranks) +} + +/// Compute `(device_reserve_bytes, planned_host_cap_bytes)` for one rank's declared +/// `Execution.async_transfers` channels. +/// +/// Registering pinned host memory with `cuMemHostRegister_v2` consumes 2 MiB of device +/// VRAM per GiB (`bytes / 512`) for GPU MMU page tables. Returning `planned_host_cap_bytes` +/// allows `prepare_async_transfers` to clamp its host-pool allocation to the exact ceiling +/// whose device page-table cost was reserved before sizing `DEVICE_POOL` and KV caches. +fn async_transfer_device_reserve( + core: &Core, + host_ram_available: u64, + host_ram_total: u64, + pool_ram_limit: Option, +) -> (u64, u64) { + let Some(channels) = core + .execution + .as_ref() + .map(|exec| exec.async_transfers.as_slice()) + .filter(|channels| !channels.is_empty()) + else { + return (0, 0); + }; + let cap = match pool_ram_limit { + Some(limit) => limit + .cap_bytes(host_ram_available, host_ram_total) + .min(host_ram_available), + None => host_ram_available, + }; + let mut remaining = cap; + let mut pinned = 0u64; + for channel in channels { + let host_pool = crate::async_transfer::resolve_pool_bytes( + remaining, + None, + channel.max_host_pool_bytes, + 2 << 20, + ); + remaining = remaining.saturating_sub(host_pool); + pinned = pinned + .saturating_add(host_pool) + .saturating_add(crate::async_transfer::worker::max_bounce_pool_bytes( + channel.alignment, + )); + } + let page_tables = pinned.div_ceil(512); + ( + page_tables.saturating_add(ASYNC_TRANSFER_DEVICE_MARGIN_BYTES), + cap, + ) +} // A GPU that allocates from system memory (GB10, GA10B) shares it with the operating system and // with the server's host allocations made after sizing: frontend workers, tokenizers and request // buffers took about 1.4 GiB on a DGX Spark. Caches leave room for both beyond the reserve. @@ -615,7 +684,7 @@ impl NativeModel { options: &LoadOptions, initial: &[MemorySnapshot], embedding_host_bytes: u64, - ) -> Result> { + ) -> Result { // Local host tiers register after cache backing; pool regions register before sizing. let reserve = headroom(&self.server_config)?; let page_tokens = self.server_config["page_tokens"] @@ -1031,6 +1100,103 @@ impl NativeModel { } } } + // Reserve per-rank device memory for `Prepare async transfers` (GPU MMU page tables for + // CUDA-registered pinned host and bounce pools plus Copy Engine/signal/replay stream + // headroom) before sizing `DEVICE_POOL` and KV caches so `Start server` cannot OOM. + let has_async_transfers = cores.iter().any(|core| { + core.execution + .as_ref() + .is_some_and(|exec| !exec.async_transfers.is_empty()) + }); + let async_transfer_host_caps = if has_async_transfers { + let (per_rank_avail, per_rank_total) = async_transfer_host_ram(self.ranks.len()); + let mut caps = Vec::with_capacity(cores.len()); + for (avail, core) in available.iter_mut().zip(cores.iter()) { + let (device_reserve, host_cap) = async_transfer_device_reserve( + core, + per_rank_avail, + per_rank_total, + options.pool_ram_limit, + ); + *avail = avail.saturating_sub(device_reserve); + caps.push(host_cap); + } + caps + } else { + vec![0; cores.len()] + }; + // Size and map any `Capacity::DEVICE_POOL` allocations before choosing KV page count, + // leaving room for execution state rows and minimum KV cache capacity. + let device_pool_names: Vec = cores[0] + .allocations + .iter() + .filter(|a| a.sizing.as_ref().is_some_and(|s| s.capacity == 2)) + .map(|a| a.name.clone()) + .collect(); + if !device_pool_names.is_empty() { + let execution_rows = 1 + active as u64 * width; + let mut min_kv_reserve = Vec::with_capacity(cores.len()); + for core in cores.iter() { + let req = bytes(core, 0, execution_rows)? + .checked_add(bytes(core, 1, minimum_pages)?) + .ok_or_else(|| invalid("minimum cache footprint overflow"))?; + min_kv_reserve.push(req); + } + for pool_name in &device_pool_names { + let mut agreed_bytes = u64::MAX; + for (idx, core) in cores.iter().enumerate() { + let alloc = core + .allocations + .iter() + .find(|a| a.name == *pool_name) + .ok_or_else(|| invalid("rank lacks matching device pool allocation"))?; + let sizing = alloc.sizing.as_ref().unwrap(); + let max_pool = sizing + .unit_bytes + .checked_mul(sizing.maximum) + .ok_or_else(|| invalid("device pool extent overflow"))?; + let avail_for_pool = available[idx].saturating_sub(min_kv_reserve[idx]); + let cap = options + .pool_vram_limit + .map(|limit| limit.cap_bytes(avail_for_pool, observations[idx].total)); + let chosen = crate::async_transfer::resolve_pool_bytes( + avail_for_pool, + cap, + max_pool, + alloc.alignment as u64, + ); + agreed_bytes = agreed_bytes.min(chosen); + } + if agreed_bytes == u64::MAX { + agreed_bytes = 0; + } + let mapped_usize = usize::try_from(agreed_bytes) + .map_err(|_| invalid("device pool size exceeds usize"))?; + for (idx, (rank, core)) in self.ranks.iter_mut().zip(cores.iter_mut()).enumerate() { + let alloc = core + .allocations + .iter_mut() + .find(|a| a.name == *pool_name) + .unwrap(); + alloc.nbytes = mapped_usize; + unsafe { + rank.map_device_pool(alloc, mapped_usize)?; + } + if let Some(exec) = core.execution.as_mut() { + for buf in &mut exec.buffers { + if buf + .reference + .as_ref() + .is_some_and(|r| r.allocation == *pool_name && r.offset == 0) + { + resize_device_pool_buffer(buf, agreed_bytes); + } + } + } + available[idx] = available[idx].saturating_sub(agreed_bytes); + } + } + } let capture_layout = capture.then(|| flare_selene::Layout::new(&geometry)).transpose()?; let host_growth = if capture { host_budget_for(host_future.saturating_add(pool_host_charge))? @@ -1139,7 +1305,10 @@ impl NativeModel { &limiting, )?; } - Ok(planned_offload_host) + Ok(PlannedHostBudgets { + offload_host: planned_offload_host, + async_transfer_host_caps, + }) } #[allow(clippy::too_many_arguments)] @@ -1221,6 +1390,9 @@ impl NativeModel { gpu_bytes += bytes(core, 0, rows - snapshots)? + bytes(core, 1, pages)?; for allocation in &mut core.allocations { if let Some(sizing) = allocation.sizing.as_ref() { + if sizing.capacity == 2 { + continue; + } let units = if sizing.capacity == 0 { rows } else { pages }; allocation.nbytes = (units * sizing.unit_bytes).div_ceil(allocation.alignment as u64) as usize @@ -1359,6 +1531,27 @@ fn codec_fields(core: &Core, layout: &CodecLayout) -> Option> { .collect() } +/// Update an execution buffer view whose backing allocation is a runtime-sized `DEVICE_POOL` +/// to match the agreed physical byte count while preserving trailing row dimensions. +fn resize_device_pool_buffer(buf: &mut super::protobuf::wire::Buffer, agreed_bytes: u64) { + let elem_bytes = match buf.dtype.as_str() { + "uint8" | "int8" | "bool" | "float8_e4m3fn" | "float8_e5m2" => 1u64, + "float16" | "bfloat16" | "int16" | "uint16" => 2u64, + "float32" | "int32" | "uint32" => 4u64, + "float64" | "int64" | "uint64" => 8u64, + _ => 1u64, + }; + let row_elems = buf.shape.get(1..).map_or(1u64, |tail| { + tail.iter().copied().fold(1u64, u64::saturating_mul) + }); + let row_bytes = row_elems.saturating_mul(elem_bytes).max(1); + let units = agreed_bytes / row_bytes; + buf.nbytes = units.saturating_mul(row_bytes); + if !buf.shape.is_empty() { + buf.shape[0] = units; + } +} + /// The row plane and page planes of one rank in name order, read before /// the sizing records are consumed. Peer allocations never carry sizing. pub(super) fn cache_geometry( @@ -1387,7 +1580,7 @@ pub(super) fn cache_geometry( "rank declares more than one continuation-row allocation", )); } - } else { + } else if sizing.capacity == 1 { planes.push(plane); } } @@ -1796,6 +1989,7 @@ mod tests { reservations: vec![], execution: None, context: Context::default(), + external_extents: vec![], allocations: [ ("state", 0, row_bytes, 4096), ("kv", 1, page_bytes, maximum_pages), @@ -2096,4 +2290,147 @@ mod tests { input_window + source_window ); } + + #[test] + fn cache_geometry_ignores_device_pool_and_resizes_2d_pool_buffer() { + let mut p = core(65536, 32768, 1024); + p.allocations.push(Allocation { + name: "runtime_device_pool".into(), + memory: Memory::Device, + address: Some(0x8900_0000_0000), + nbytes: 0, + alignment: 2 << 20, + file: None, + data_spans: vec![], + sources: vec![], + relocations: vec![], + sizing: Some(Sizing { + capacity: 2, + unit_bytes: 2_764_800, + maximum: 24576, + }), + }); + let geom = cache_geometry(&p, 64, 16, 1024, None).unwrap(); + assert!( + geom.planes.iter().all(|pl| pl.name != "runtime_device_pool"), + "DEVICE_POOL allocation must not be included in KV cache planes" + ); + assert_eq!(geom.planes.len(), 1); + + let mut buf_2d = super::super::protobuf::wire::Buffer { + name: "runtime_device_pool".into(), + nbytes: 128 * 2_764_800, + dtype: "uint8".into(), + shape: vec![128, 2_764_800], + strides: vec![2_764_800, 1], + reference: None, + }; + let agreed = 12u64 << 30; + resize_device_pool_buffer(&mut buf_2d, agreed); + let expected_slots = agreed / 2_764_800; + assert_eq!(buf_2d.shape, vec![expected_slots, 2_764_800]); + assert_eq!(buf_2d.nbytes, expected_slots * 2_764_800); + + let mut buf_1d = super::super::protobuf::wire::Buffer { + name: "flat_pool".into(), + nbytes: 4096, + dtype: "uint8".into(), + shape: vec![4096], + strides: vec![1], + reference: None, + }; + resize_device_pool_buffer(&mut buf_1d, 64 << 20); + assert_eq!(buf_1d.shape, vec![64 << 20]); + assert_eq!(buf_1d.nbytes, 64 << 20); + } + + #[test] + fn async_transfer_device_reserve_accounts_for_pinned_host_page_tables() { + use super::super::{ + MemoryLimit, PoolMemoryLimit, + protobuf::wire::{AsyncTransfer, Execution}, + }; + + let gib = 1u64 << 30; + let mib = 1u64 << 20; + let bounce = crate::async_transfer::worker::max_bounce_pool_bytes(4096); + let mut p = core(65536, 32768, 1024); + + // No async transfer channels -> zero device reserve and zero host cap. + assert_eq!(async_transfer_device_reserve(&p, 256 * gib, 512 * gib, None), (0, 0)); + + let channel = |name: &str, max_host: u64, alignment: u32| AsyncTransfer { + name: name.into(), + device_pool: "pool".into(), + completion_slots: 64, + ring_capacity: 64, + alignment, + max_host_pool_bytes: max_host, + ..Default::default() + }; + p.execution = Some(Execution { + async_transfers: vec![channel("extents", 160 * gib, 4096)], + ..Default::default() + }); + + // 160 GiB pinned host pool consumes 320 MiB of GPU MMU page tables plus bounce + base margin. + let (dev_160, cap_160) = async_transfer_device_reserve( + &p, + 200 * gib, + 256 * gib, + Some(PoolMemoryLimit(MemoryLimit::Bytes(160 * gib))), + ); + assert_eq!(cap_160, 160 * gib); + assert_eq!( + dev_160, + (160 * gib + bounce).div_ceil(512) + ASYNC_TRANSFER_DEVICE_MARGIN_BYTES + ); + assert!(dev_160 > 576 * mib); + + // Zero host pool still reserves bounce-pool page tables plus base stream margin. + let (dev_0, cap_0) = async_transfer_device_reserve( + &p, + 200 * gib, + 256 * gib, + Some(PoolMemoryLimit(MemoryLimit::Bytes(0))), + ); + assert_eq!(cap_0, 0); + assert_eq!( + dev_0, + bounce.div_ceil(512) + ASYNC_TRANSFER_DEVICE_MARGIN_BYTES + ); + + // Negative RAM reserve reduces the planned host cap without double-subtracting. + let (dev_res, cap_res) = async_transfer_device_reserve( + &p, + 100 * gib, + 256 * gib, + Some(PoolMemoryLimit(MemoryLimit::Reserve(20 * gib))), + ); + assert_eq!(cap_res, 80 * gib); + assert_eq!( + dev_res, + (80 * gib + bounce).div_ceil(512) + ASYNC_TRANSFER_DEVICE_MARGIN_BYTES + ); + + // Large alignment (> 32 MiB) disables bounce staging, so reserve charges zero bounce bytes. + p.execution.as_mut().unwrap().async_transfers[0].alignment = 64 << 20; + let (dev_big_align, _) = async_transfer_device_reserve( + &p, + 200 * gib, + 256 * gib, + Some(PoolMemoryLimit(MemoryLimit::Bytes(0))), + ); + assert_eq!(dev_big_align, ASYNC_TRANSFER_DEVICE_MARGIN_BYTES); + + // Large host (512 GiB channel on 1 TiB host) scales GPU page-table reserve linearly. + p.execution.as_mut().unwrap().async_transfers[0].alignment = 4096; + p.execution.as_mut().unwrap().async_transfers[0].max_host_pool_bytes = 512 * gib; + let (dev_512, cap_512) = async_transfer_device_reserve(&p, 700 * gib, 1024 * gib, None); + assert_eq!(cap_512, 700 * gib); + assert_eq!( + dev_512, + (512 * gib + bounce).div_ceil(512) + ASYNC_TRANSFER_DEVICE_MARGIN_BYTES + ); + } } diff --git a/helios/src/runtime_core/mod.rs b/helios/src/runtime_core/mod.rs index 31f18fe98..d7238044a 100644 --- a/helios/src/runtime_core/mod.rs +++ b/helios/src/runtime_core/mod.rs @@ -69,7 +69,7 @@ pub use archive::{ CoreFile, LegacyHeader, LegacyLayout, MAX_LEGACY_HEADER, MAX_LEGACY_INDEX, MAX_LEGACY_PAYLOAD, core_companions, is_snapshot_blob_name, read_legacy_header, validate_companion_filename, }; -pub use limits::{KvCacheLimit, MemoryLimit}; +pub use limits::{KvCacheLimit, MemoryLimit, PoolMemoryLimit}; pub use model::{ CacheAgreement, ClusterRank, NativeModel, RankNeeds, RoceSpec, core_cluster, rank_needs, rank_ranges, reserve_bytes, @@ -127,6 +127,7 @@ pub struct NativeResources { host_mappings: Vec<(u64, usize)>, green_partition: Option, persistent_worker: Option>, + async_transfers: Vec>, } // SAFETY: CUDA contexts may move between threads. Resource operations bind the @@ -425,6 +426,7 @@ impl NativeResources { host_mappings: Vec::new(), green_partition: None, persistent_worker: None, + async_transfers: Vec::new(), }; if !primary_context { let configured = (|| -> Result<()> { @@ -1426,6 +1428,226 @@ impl NativeResources { .map_or(self.context, |partition| partition.codec_context) } + /// Map physical VMM backing for one runtime-sized `Capacity::DEVICE_POOL` allocation + /// at its fixed reserved CUDA virtual address, grant access, and zero it. + pub(in crate::runtime_core) unsafe fn map_device_pool( + &mut self, + allocation: &format::Allocation, + nbytes: usize, + ) -> Result<()> { + if nbytes == 0 { + return Ok(()); + } + let address = allocation + .address + .ok_or_else(|| invalid("runtime-sized device pool requires a fixed virtual address"))?; + if nbytes % allocation.alignment != 0 || nbytes > allocation.extent() { + return Err(invalid( + "runtime-sized device pool size must be aligned and within its virtual extent", + )); + } + let driver = self.driver.clone(); + unsafe { + driver.check("cuCtxSetCurrent", (driver.context_set)(self.context))?; + let properties = AllocationProperties { + kind: 1, + handles: 0, + location: Location { + kind: 1, + device: self.device, + }, + windows: null_mut(), + flags: [0; 8], + }; + let mut physical = 0; + driver.check( + "cuMemCreate(device_pool)", + (driver.physical_create)(&mut physical, nbytes, &properties, 0), + )?; + let mapped = (driver.map)(address, nbytes, 0, physical, 0); + (driver.physical_release)(physical); + driver.check("cuMemMap(device_pool)", mapped)?; + if let Some(storage) = self.allocations.get_mut(&allocation.name) { + storage.nbytes = nbytes; + storage.mappings = vec![(address, nbytes)]; + } + self.grant_storage_access(&allocation.name)?; + driver.check("cuMemsetD8_v2(device_pool)", (driver.zero)(address, 0, nbytes))?; + driver.check("cuCtxSynchronize", (driver.context_sync)())?; + } + Ok(()) + } + + /// Resolve authenticated external extents, allocate pinned host pools, publish startup + /// control headers, and prepare every `Execution.async_transfers` channel on this rank. + pub(in crate::runtime_core) unsafe fn prepare_async_transfers( + &mut self, + files: &F, + core: &Core, + planned_host_cap: u64, + ) -> Result<()> { + let Some(execution) = core.execution.as_ref() else { + return Ok(()); + }; + if execution.async_transfers.is_empty() { + return Ok(()); + } + let mut remaining_host = planned_host_cap; + for channel in &execution.async_transfers { + let device_pool = self.allocation(&channel.device_pool)?; + let control_ref = channel.control.as_ref().ok_or_else(|| { + invalid(format!( + "async transfer channel {:?} lacks a control reference", + channel.name + )) + })?; + let control_alloc = self.allocation(&control_ref.allocation)?; + let control_offset = protobuf::size(control_ref.offset)?; + let control_bytes = protobuf::size(channel.control_bytes)?; + let device_completions_base = match channel.device_completions.as_ref() { + Some(comp_ref) => { + let comp_alloc = self.allocation(&comp_ref.allocation)?; + comp_alloc.address as u64 + comp_ref.offset + } + None => 0, + }; + + // Resolve authenticated extents from either payload-format `external_extents` or legacy `extents`. + let mut source_file_map: HashMap = HashMap::new(); + let mut opened_files: Vec = Vec::new(); + let mut open_source = |src_idx: usize| -> Result { + if let Some(&local_idx) = source_file_map.get(&src_idx) { + return Ok(local_idx); + } + let direct = files.direct_file(src_idx)?; + let cloned = direct + .try_clone() + .map_err(|e| invalid(format!("clone direct core file: {e}")))?; + let local_idx = u32::try_from(opened_files.len()) + .map_err(|_| invalid("too many external extent files"))?; + opened_files.push(cloned); + source_file_map.insert(src_idx, local_idx); + Ok(local_idx) + }; + + let extents = if let Some(table) = core + .external_extents + .iter() + .find(|t| t.channel == channel.name) + { + let dir_bytes = files.read(core, &table.directory)?; + let mut resolved_segments = Vec::with_capacity(table.segments.len()); + for seg_key in &table.segments { + let span = files.span(core, seg_key)?; + let src_idx = files.source_index(span)?; + let (_, abs_off) = files.source(span)?; + let local_file = open_source(src_idx)?; + resolved_segments.push((local_file, abs_off, span.nbytes)); + } + crate::async_transfer::decode_extent_directory( + &dir_bytes, + &resolved_segments, + channel.alignment, + ) + .map_err(invalid)? + } else { + let align_mask = u64::from(channel.alignment) - 1; + let mut entries = Vec::with_capacity(channel.extents.len()); + for (idx, span) in channel.extents.iter().enumerate() { + let src_idx = files.source_index(span)?; + let (_, abs_off) = files.source(span)?; + if span.nbytes == 0 + || (abs_off & align_mask) != 0 + || (span.nbytes & align_mask) != 0 + { + return Err(invalid(format!( + "async transfer extent {idx} violates {}-byte direct-I/O alignment", + channel.alignment + ))); + } + let local_file = open_source(src_idx)?; + entries.push(crate::async_transfer::ExtentEntry { + file_index: local_file, + offset: abs_off, + nbytes: span.nbytes, + }); + } + entries + }; + + let host_pool_bytes = crate::async_transfer::resolve_pool_bytes( + remaining_host, + None, + channel.max_host_pool_bytes, + 2 << 20, + ); + remaining_host = remaining_host.saturating_sub(host_pool_bytes); + + let io_backend = + crate::async_transfer::io_backend::from_direct_files(opened_files) + .map_err(|e| invalid(format!("create async transfer I/O backend: {e}")))?; + + let cfg = crate::async_transfer::ChannelConfig { + name: channel.name.clone(), + device_pool_base: device_pool.address as u64, + device_pool_bytes: device_pool.nbytes as u64, + host_pool_bytes, + control_address: control_alloc.address + control_offset, + control_bytes, + device_completions_base, + completion_slots: channel.completion_slots, + ring_capacity: channel.ring_capacity, + alignment: channel.alignment, + extents, + }; + let runtime = unsafe { + crate::async_transfer::AsyncTransferRuntime::new( + cfg, + self.driver.clone(), + self.context, + self.device, + io_backend, + )? + }; + self.async_transfers.push(runtime); + } + Ok(()) + } + + /// Start all prepared `AsyncTransfer` channel workers on this rank. + pub fn start_async_transfers(&self) -> Result<()> { + for channel in &self.async_transfers { + channel.start()?; + } + Ok(()) + } + + /// Stop and drain all prepared `AsyncTransfer` channel workers on this rank. + pub fn stop_async_transfers(&self) -> Result<()> { + let mut first_err = None; + for channel in self.async_transfers.iter().rev() { + if let Err(err) = channel.stop() { + first_err.get_or_insert(err); + } + } + match first_err { + Some(err) => Err(err), + None => Ok(()), + } + } + + /// Lock-free telemetry snapshots for all `AsyncTransfer` channels on this rank. + pub fn async_transfer_snapshots(&self) -> Vec { + self.async_transfers.iter().map(|c| c.snapshot()).collect() + } + + /// Shared handles to all `AsyncTransfer` channels owned by this rank for lock-free telemetry. + pub fn async_transfer_handles( + &self, + ) -> Vec> { + self.async_transfers.clone() + } + /// Launch the prepared persistent worker graph once on its green-context worker stream. /// No-op when the core declares no persistent worker or the worker is already running. pub fn start_persistent_worker(&self) -> Result<()> { @@ -1557,11 +1779,12 @@ impl NativeResources { if self.context.is_null() { return true; } - if self.stop_persistent_worker().is_err() { + if self.stop_persistent_worker().is_err() || self.stop_async_transfers().is_err() { std::mem::forget(self.driver.clone()); self.context = null_mut(); return false; } + self.async_transfers.clear(); unsafe { let mut previous = null_mut(); let had_previous = (self.driver.context_get)(&mut previous) == 0; diff --git a/helios/src/runtime_core/model.rs b/helios/src/runtime_core/model.rs index d223f3e30..b8a48cb44 100644 --- a/helios/src/runtime_core/model.rs +++ b/helios/src/runtime_core/model.rs @@ -926,7 +926,7 @@ impl NativeModel { }); } Files::release_page_cache(&files); - let planned_offload_host = model.allocate_caches( + let planned = model.allocate_caches( &mut cores, progress, active, @@ -935,11 +935,68 @@ impl NativeModel { &initial, embedding_host_bytes, )?; - model.prepare_offload(options, progress, active, planned_offload_host)?; + model.prepare_offload(options, progress, active, planned.offload_host)?; + model.prepare_async_transfers( + &files, + &cores, + &planned.async_transfer_host_caps, + progress, + )?; } Ok(model) } + /// Initialize and start any declared `Execution.async_transfers` channels across local ranks + /// so startup tuning graphs observe populated pool geometry and live copy channels. + unsafe fn prepare_async_transfers( + &mut self, + files: &F, + cores: &[Core], + planned_host_caps: &[u64], + progress: &StartupProgress, + ) -> Result<()> { + let total_channels: usize = cores + .iter() + .filter_map(|c| c.execution.as_ref()) + .map(|e| e.async_transfers.len()) + .sum(); + if total_channels == 0 { + return Ok(()); + } + let phase = progress.phase("Prepare async transfers", None); + for (idx, (rank, core)) in self.ranks.iter_mut().zip(cores.iter()).enumerate() { + let planned_cap = planned_host_caps.get(idx).copied().unwrap_or(0); + unsafe { + rank.prepare_async_transfers(files, core, planned_cap)?; + } + rank.start_async_transfers()?; + } + let (dev_total_mapped, host_total_mapped) = self + .ranks + .iter() + .flat_map(|r| r.async_transfer_snapshots()) + .fold((0u64, 0u64), |(dev, host), s| { + (dev + s.device_pool_bytes, host + s.host_pool_bytes) + }); + phase.finish(format!( + "{total_channels} channel{} · {:.2} GiB VRAM pool · {:.2} GiB RAM pool", + if total_channels == 1 { "" } else { "s" }, + dev_total_mapped as f64 / (1u64 << 30) as f64, + host_total_mapped as f64 / (1u64 << 30) as f64, + )); + Ok(()) + } + + /// Shared handles to all `AsyncTransfer` channels owned across local ranks for lock-free metrics. + pub fn async_transfer_handles( + &self, + ) -> Vec> { + self.ranks + .iter() + .flat_map(NativeResources::async_transfer_handles) + .collect() + } + /// Resolve the host prefix store configuration, map and register its /// pools, and scan its record directory. unsafe fn prepare_offload( @@ -1767,6 +1824,7 @@ mod identity_tests { ..Default::default() }), context: super::super::format::Context::default(), + external_extents: vec![], }; let plain_core = || Core { execution: Some(protobuf::wire::Execution::default()), diff --git a/helios/src/runtime_core/persistent_worker.rs b/helios/src/runtime_core/persistent_worker.rs index 3c6e5024a..9c3ba31c8 100644 --- a/helios/src/runtime_core/persistent_worker.rs +++ b/helios/src/runtime_core/persistent_worker.rs @@ -1607,6 +1607,7 @@ extern "C" __global__ void cluster_2cta(int* out) { let build_core = || Core { resources: HashMap::new(), architecture: [major, minor], + external_extents: vec![], allocations: vec![ Allocation { name: "worker_ctrl".into(), @@ -2082,6 +2083,7 @@ extern "C" __global__ void step_emit_completion( let core = Core { resources: HashMap::new(), architecture: [major, minor], + external_extents: vec![], allocations: vec![ Allocation { name: "worker_ctrl".into(), @@ -2371,6 +2373,7 @@ extern "C" __global__ void worker_ignore_stop( let core = Core { resources: HashMap::new(), architecture: [major, minor], + external_extents: vec![], allocations: vec![Allocation { name: "worker_ctrl".into(), nbytes: 2 << 20, @@ -2829,6 +2832,7 @@ extern "C" __global__ void coop_all_sms(int* state, int step) { }], ..Default::default() }), + external_extents: vec![], }; let phase = crate::startup::StartupProgress::silent().phase("Load 3-way test", None); diff --git a/helios/src/runtime_core/protobuf.rs b/helios/src/runtime_core/protobuf.rs index 691519645..078776041 100644 --- a/helios/src/runtime_core/protobuf.rs +++ b/helios/src/runtime_core/protobuf.rs @@ -388,6 +388,130 @@ pub(super) fn validate_persistent_workers(core: &Core, execution: &wire::Executi Ok(()) } +pub(super) fn validate_async_transfers(core: &Core, execution: &wire::Execution) -> Result<()> { + let mut names = std::collections::HashSet::with_capacity(execution.async_transfers.len()); + for channel in &execution.async_transfers { + if channel.name.is_empty() || !names.insert(channel.name.as_str()) { + return Err(invalid( + "async transfer channel names must be nonempty and unique", + )); + } + if !crate::async_transfer::validate_control_layout( + channel.control_bytes, + channel.ring_capacity, + channel.completion_slots, + channel.alignment, + ) { + return Err(invalid(format!( + "async transfer channel {:?} has invalid ring, completion, or alignment layout", + channel.name + ))); + } + let device_pool = core + .allocations + .iter() + .find(|a| a.name == channel.device_pool && matches!(a.memory, Memory::Device)) + .ok_or_else(|| { + invalid(format!( + "async transfer channel {:?} references unknown or non-device pool {:?}", + channel.name, channel.device_pool + )) + })?; + if device_pool + .sizing + .as_ref() + .is_some_and(|s| s.capacity != wire::Capacity::DevicePool as i32) + { + return Err(invalid(format!( + "async transfer channel {:?} device pool cannot use KV or state-row sizing", + channel.name + ))); + } + let control = channel.control.as_ref().ok_or_else(|| { + invalid(format!( + "async transfer channel {:?} requires a mapped-host control reference", + channel.name + )) + })?; + let control_alloc = core + .allocations + .iter() + .find(|a| { + a.name == control.allocation + && matches!(a.memory, Memory::MappedHost) + && a.sizing.is_none() + }) + .ok_or_else(|| { + invalid(format!( + "async transfer channel {:?} control must reside in a mapped host allocation", + channel.name + )) + })?; + let control_offset = size(control.offset)?; + let control_bytes = size(channel.control_bytes)?; + if control_offset % 64 != 0 + || control_offset + .checked_add(control_bytes) + .is_none_or(|end| end > control_alloc.nbytes) + { + return Err(invalid(format!( + "async transfer channel {:?} control range must be 64-byte aligned and in bounds", + channel.name + ))); + } + if let Some(dev_comp) = channel.device_completions.as_ref() { + let comp_alloc = core + .allocations + .iter() + .find(|a| { + a.name == dev_comp.allocation + && matches!(a.memory, Memory::Device) + && a.sizing.is_none() + }) + .ok_or_else(|| { + invalid(format!( + "async transfer channel {:?} device completions must reside in a fixed device allocation", + channel.name + )) + })?; + let comp_offset = size(dev_comp.offset)?; + let comp_bytes = (channel.completion_slots as usize) + .checked_mul(std::mem::size_of::()) + .ok_or_else(|| invalid("async transfer completion table size overflow"))?; + if comp_offset % 8 != 0 + || comp_offset + .checked_add(comp_bytes) + .is_none_or(|end| end > comp_alloc.nbytes) + { + return Err(invalid(format!( + "async transfer channel {:?} device completions must be 8-byte aligned and in bounds", + channel.name + ))); + } + } + if !channel.extents.is_empty() + && core + .external_extents + .iter() + .any(|t| t.channel == channel.name) + { + return Err(invalid(format!( + "async transfer channel {:?} cannot declare both inline extents and an external extent table", + channel.name + ))); + } + } + for table in &core.external_extents { + if !names.contains(table.channel.as_str()) { + return Err(invalid(format!( + "external extent table references unknown async transfer channel {:?}", + table.channel + ))); + } + } + Ok(()) +} + pub(super) fn decode(mut value: wire::BundleIndex) -> Result { normalize_execution(&mut value.execution)?; let context = required(value.context, "CUDA context")?; @@ -462,6 +586,7 @@ pub(super) fn decode(mut value: wire::BundleIndex) -> Result { }) })?, execution: value.execution, + external_extents: vec![], }; Ok(core) } @@ -1384,6 +1509,27 @@ pub(super) fn payload_rank( }) .collect::>>()?; + let mut external_extents = Vec::with_capacity(rank.external_extents.len()); + for (table_index, table) in rank.external_extents.iter().enumerate() { + let dir_use = table + .directory + .as_ref() + .ok_or_else(|| invalid("external extent table lacks a directory payload"))?; + let directory = span_for(format!("extents/{table_index}/directory"), dir_use)?; + let mut segments = Vec::with_capacity(table.segments.len()); + for (seg_index, seg_use) in table.segments.iter().enumerate() { + segments.push(span_for( + format!("extents/{table_index}/segment/{seg_index}"), + seg_use, + )?); + } + external_extents.push(ExternalExtentTable { + channel: table.channel.clone(), + segments, + directory, + }); + } + let context = rank .context .clone() @@ -1412,6 +1558,7 @@ pub(super) fn payload_rank( })?, }, events: rank.events.clone(), + external_extents, }; Ok(core) } @@ -1520,6 +1667,7 @@ mod payload_tests { roce: None, prepared_weights: None, compressed_prepared_weights: None, + external_extents: vec![], } } @@ -1713,6 +1861,7 @@ mod payload_tests { resources: HashMap::new(), events: vec![], architecture: [10, 3], + external_extents: vec![], allocations: vec![ Allocation { name: "device_buf".into(), diff --git a/helios/src/runtime_core/selection.rs b/helios/src/runtime_core/selection.rs index 2f43b1833..8edcc624c 100644 --- a/helios/src/runtime_core/selection.rs +++ b/helios/src/runtime_core/selection.rs @@ -17,6 +17,10 @@ use crate::{Result, execution::REQUEST_LANES}; pub struct LoadOptions { pub kv_cache_limit: super::KvCacheLimit, pub memory_limit: Option, + /// Optional per-device budget for runtime-sized `Capacity::DEVICE_POOL` allocations. + pub pool_vram_limit: Option, + /// Optional per-host budget for `AsyncTransfer` pinned host RAM pools (`0` disables host pool). + pub pool_ram_limit: Option, /// Auxiliary embedding-table storage; defaults to disk when absent. pub embedding_table_storage: Option, /// Per-host RAM bytes for disk-backed embedding rows; zero disables, absent selects by memory topology. @@ -88,6 +92,12 @@ impl LoadOptions { if let Some(limit) = self.memory_limit { limit.validate()?; } + if let Some(limit) = self.pool_vram_limit { + limit.validate()?; + } + if let Some(limit) = self.pool_ram_limit { + limit.validate()?; + } if let Some(workers) = self.embedding_table_workers { if !matches!(workers, 1 | 2 | 4 | 8) { return Err(invalid("embedding table workers must be 1, 2, 4, or 8")); @@ -571,6 +581,7 @@ mod tests { modules, execution: Some(execution), context: Context::default(), + external_extents: vec![], reservations: vec![], allocations: ["weights", "mtp-weights", "scratch"] .map(|name| Allocation { diff --git a/helios/src/server.rs b/helios/src/server.rs index 266ceba00..1a2da9c06 100644 --- a/helios/src/server.rs +++ b/helios/src/server.rs @@ -460,6 +460,14 @@ impl Server { pub fn persistent_worker_snapshot(&self) -> Option { self.model.persistent_worker_snapshot() } + /// Attach lock-free `AsyncTransfer` channel handles for Prometheus telemetry reporting. + #[cfg(feature = "runtime-core")] + pub fn attach_async_transfers( + &self, + channels: Vec>, + ) { + self.model.attach_async_transfers(channels); + } pub fn snapshot(&self) -> ServerSnapshot { let accepting = *self.state.accepting.lock().unwrap_or_else(|e| e.into_inner()); let healthy = self.healthy(); diff --git a/helios/src/server/metrics.rs b/helios/src/server/metrics.rs index 6410ccc93..b8fd9b513 100644 --- a/helios/src/server/metrics.rs +++ b/helios/src/server/metrics.rs @@ -217,6 +217,9 @@ pub(super) struct Metrics { decode_weight_bytes: u64, pub engram: Option>, pub persistent_worker: Option, + #[cfg(feature = "runtime-core")] + pub async_transfers: + std::sync::OnceLock>>, prefill_tokens: AtomicU64, generated_tokens: AtomicU64, accepted_drafts: AtomicU64, @@ -990,6 +993,12 @@ impl Metrics { if let Some(worker) = self.persistent_worker_snapshot() { render_persistent_worker_metrics(&mut text, &worker); } + #[cfg(feature = "runtime-core")] + if let Some(channels) = self.async_transfers.get() { + if !channels.is_empty() { + render_async_transfer_metrics(&mut text, channels); + } + } text.push_str("# HELP flare_sampling_graph_launches_total Successful native submissions by captured sampler mode; includes consumption-only prefill.\n# TYPE flare_sampling_graph_launches_total counter\n"); for (kind, count) in ["prefill", "decode", "resume", "speculative", "mixed"] .into_iter() @@ -1518,6 +1527,62 @@ fn render_persistent_worker_metrics( } } +#[cfg(feature = "runtime-core")] +fn render_async_transfer_metrics( + text: &mut String, + channels: &[std::sync::Arc], +) { + text.push_str( + "# HELP flare_async_transfer_device_pool_bytes Mapped device pool capacity in bytes.\n\ + # TYPE flare_async_transfer_device_pool_bytes gauge\n\ + # HELP flare_async_transfer_host_pool_bytes Mapped pinned host pool capacity in bytes.\n\ + # TYPE flare_async_transfer_host_pool_bytes gauge\n\ + # HELP flare_async_transfer_submitted_cmds_total Validated commands enqueued on the channel.\n\ + # TYPE flare_async_transfer_submitted_cmds_total counter\n\ + # HELP flare_async_transfer_completed_cmds_total Completed commands on the channel.\n\ + # TYPE flare_async_transfer_completed_cmds_total counter\n\ + # HELP flare_async_transfer_canceled_cmds_total Canceled commands on the channel.\n\ + # TYPE flare_async_transfer_canceled_cmds_total counter\n\ + # HELP flare_async_transfer_rejected_cmds_total Rejected commands on the channel.\n\ + # TYPE flare_async_transfer_rejected_cmds_total counter\n\ + # HELP flare_async_transfer_bytes_disk_to_host_total Total direct-IO bytes read from storage into host pool.\n\ + # TYPE flare_async_transfer_bytes_disk_to_host_total counter\n\ + # HELP flare_async_transfer_bytes_host_to_dev_total Total Copy Engine bytes copied from host pool into device pool.\n\ + # TYPE flare_async_transfer_bytes_host_to_dev_total counter\n\ + # HELP flare_async_transfer_bytes_disk_to_dev_total Total fused direct-IO plus Copy Engine bytes transferred to device pool.\n\ + # TYPE flare_async_transfer_bytes_disk_to_dev_total counter\n\ + # HELP flare_async_transfer_last_error Most recent non-zero async transfer error code (0 when error-free).\n\ + # TYPE flare_async_transfer_last_error gauge\n", + ); + for (rank, channel) in channels.iter().enumerate() { + let s = channel.snapshot(); + let label = escape_prometheus_label(&s.name); + let _ = writeln!( + text, + "flare_async_transfer_device_pool_bytes{{channel=\"{label}\",rank=\"{rank}\"}} {}\n\ + flare_async_transfer_host_pool_bytes{{channel=\"{label}\",rank=\"{rank}\"}} {}\n\ + flare_async_transfer_submitted_cmds_total{{channel=\"{label}\",rank=\"{rank}\"}} {}\n\ + flare_async_transfer_completed_cmds_total{{channel=\"{label}\",rank=\"{rank}\"}} {}\n\ + flare_async_transfer_canceled_cmds_total{{channel=\"{label}\",rank=\"{rank}\"}} {}\n\ + flare_async_transfer_rejected_cmds_total{{channel=\"{label}\",rank=\"{rank}\"}} {}\n\ + flare_async_transfer_bytes_disk_to_host_total{{channel=\"{label}\",rank=\"{rank}\"}} {}\n\ + flare_async_transfer_bytes_host_to_dev_total{{channel=\"{label}\",rank=\"{rank}\"}} {}\n\ + flare_async_transfer_bytes_disk_to_dev_total{{channel=\"{label}\",rank=\"{rank}\"}} {}\n\ + flare_async_transfer_last_error{{channel=\"{label}\",rank=\"{rank}\"}} {}", + s.device_pool_bytes, + s.host_pool_bytes, + s.submitted_cmds, + s.completed_cmds, + s.canceled_cmds, + s.rejected_cmds, + s.bytes_disk_to_host, + s.bytes_host_to_dev, + s.bytes_disk_to_dev, + s.last_error, + ); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index 28079d6c8..1e5cad1f1 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -991,6 +991,15 @@ impl ModelRuntime { pub fn persistent_worker_snapshot(&self) -> Option { self.metrics.persistent_worker_snapshot() } + #[cfg(feature = "runtime-core")] + pub fn attach_async_transfers( + &self, + channels: Vec>, + ) { + if !channels.is_empty() { + let _ = self.metrics.async_transfers.set(channels); + } + } pub fn wait(&self, timeout: std::time::Duration) -> bool { let finished = self.finished.0.lock().unwrap_or_else(|e| e.into_inner()); let _ = self diff --git a/helios/src/server/session.rs b/helios/src/server/session.rs index 20ac715e1..a54b75aa9 100644 --- a/helios/src/server/session.rs +++ b/helios/src/server/session.rs @@ -68,10 +68,15 @@ impl LoadedSession { ) }; match server { - Ok(server) => Ok(ServingSession { - server, - owner: Mutex::new(owner), - }), + Ok(server) => { + if let Some(model) = owner.value.as_ref() { + server.attach_async_transfers(model.async_transfer_handles()); + } + Ok(ServingSession { + server, + owner: Mutex::new(owner), + }) + } Err(failure) => { owner.drained = failure.drained; Err(failure) diff --git a/ignition/preparation/execution.py b/ignition/preparation/execution.py index af280a4b4..f31fa810f 100644 --- a/ignition/preparation/execution.py +++ b/ignition/preparation/execution.py @@ -153,6 +153,74 @@ def __post_init__(self): raise ValueError("persistent worker stop_flag_offset must be a nonnegative 4-byte-aligned integer") +def reject_in_process_async_transfers(channels) -> None: + """Reject in-process execution when async transfer channels require native core serving.""" + if channels: + raise ValueError( + "async transfer channels require native core serving (export a core and serve with flare run)" + ) + + +@dataclass(frozen=True) +class AsyncTransferChannel: + """Stateless async extent-copy channel driven by a mapped-host command ring.""" + + name: str + device_pool: str + control_buffer: str + control_offset: int = 0 + control_bytes: int = 0 + device_completions_buffer: str | None = None + device_completions_offset: int = 0 + completion_slots: int = 64 + ring_capacity: int = 64 + max_host_pool_bytes: int = 0 + alignment: int = 4096 + extent_directory: str = "" + extent_segments: tuple[str, ...] = () + + def __post_init__(self): + if not isinstance(self.name, str) or not self.name.strip(): + raise ValueError("async transfer channel requires a nonempty name") + if not isinstance(self.device_pool, str) or not self.device_pool.strip(): + raise ValueError("async transfer channel requires a nonempty device_pool name") + if not isinstance(self.control_buffer, str) or not self.control_buffer.strip(): + raise ValueError("async transfer channel requires a nonempty control_buffer name") + if type(self.control_offset) is not int or self.control_offset < 0 or self.control_offset % 64: + raise ValueError("async transfer control_offset must be nonnegative and 64-byte aligned") + if type(self.control_bytes) is not int or self.control_bytes < 0: + raise ValueError("async transfer control_bytes must be a nonnegative integer") + if self.device_completions_buffer is not None and ( + not isinstance(self.device_completions_buffer, str) or not self.device_completions_buffer.strip() + ): + raise ValueError("async transfer device_completions_buffer must be a nonempty name or None") + if ( + type(self.device_completions_offset) is not int + or self.device_completions_offset < 0 + or self.device_completions_offset % 8 + ): + raise ValueError("async transfer device_completions_offset must be nonnegative and 8-byte aligned") + if type(self.completion_slots) is not int or not 0 < self.completion_slots < (1 << 32): + raise ValueError("async transfer completion_slots must be a positive uint32") + if ( + type(self.ring_capacity) is not int + or not 16 <= self.ring_capacity <= 4096 + or (self.ring_capacity & (self.ring_capacity - 1)) != 0 + ): + raise ValueError("async transfer ring_capacity must be a power of two in [16, 4096]") + if type(self.max_host_pool_bytes) is not int or not 0 <= self.max_host_pool_bytes < (1 << 64): + raise ValueError("async transfer max_host_pool_bytes must be a uint64") + if ( + type(self.alignment) is not int + or self.alignment < 4096 + or self.alignment >= (1 << 32) + or (self.alignment & (self.alignment - 1)) != 0 + ): + raise ValueError("async transfer alignment must be a power of two >= 4096") + if bool(self.extent_directory) != bool(self.extent_segments): + raise ValueError("async transfer extent_directory and extent_segments must be set together") + + class PreparedExecution(PreparedGraphBundle): """Retain immutable graph ownership and export the matching native ABI. @@ -164,7 +232,8 @@ class PreparedExecution(PreparedGraphBundle): def __init__(self, *, signatures: Mapping[str, GraphSignature], max_active: int = 4, estimated_durations_ns=None, export_zero_ranges=(), export_events=None, - tuning_graphs=None, tuned_bindings=None, persistent_workers=(), **kwargs): + tuning_graphs=None, tuned_bindings=None, persistent_workers=(), + async_transfers=(), **kwargs): serving = dict(kwargs.pop("graphs")) tuners = dict(tuning_graphs or {}) if set(serving).intersection(tuners): @@ -193,6 +262,17 @@ def __init__(self, *, signatures: Mapping[str, GraphSignature], max_active: int self.serving_graphs = MappingProxyType(serving) self.tuning_graphs = MappingProxyType(tuners) self.persistent_workers = workers + if async_transfers is None: + channels = () + elif isinstance(async_transfers, AsyncTransferChannel): + raise TypeError("async_transfers must be a sequence of AsyncTransferChannel objects") + else: + channels = tuple(async_transfers) + if any(not isinstance(value, AsyncTransferChannel) for value in channels): + raise TypeError("async transfer channels must be AsyncTransferChannel objects") + if len({ch.name for ch in channels}) != len(channels): + raise ValueError("async transfer channel names must be unique") + self.async_transfers = channels bindings = {name: tuple(values) for name, values in (tuned_bindings or {}).items()} if not bindings.keys() <= serving.keys(): raise ValueError("tuned bindings must name serving graphs") @@ -241,6 +321,26 @@ def __init__(self, *, signatures: Mapping[str, GraphSignature], max_active: int stop_nbytes = stop_tensor.numel() * stop_tensor.element_size() if worker.stop_flag_offset + 4 > stop_nbytes: raise ValueError("persistent worker stop flag exceeds its registered buffer") + for ch in self.async_transfers: + if ch.control_buffer not in self.buffers: + raise ValueError("async transfer control_buffer must be a registered execution buffer") + if ch.control_buffer in uploads: + raise ValueError("async transfer control_buffer cannot receive host uploads") + ctrl_tensor = self.buffers[ch.control_buffer] + ctrl_buf_bytes = ctrl_tensor.numel() * ctrl_tensor.element_size() + min_ctrl = 256 + ch.ring_capacity * 64 + ch.completion_slots * 8 + ctrl_len = (ctrl_buf_bytes - ch.control_offset) if ch.control_bytes == 0 else ch.control_bytes + if ctrl_len < min_ctrl or ch.control_offset + ctrl_len > ctrl_buf_bytes: + raise ValueError("async transfer control region does not fit its registered buffer") + if ch.device_completions_buffer is not None: + if ch.device_completions_buffer not in self.buffers: + raise ValueError("async transfer device_completions_buffer must be a registered execution buffer") + if ch.device_completions_buffer in uploads: + raise ValueError("async transfer device_completions_buffer cannot receive host uploads") + comp_tensor = self.buffers[ch.device_completions_buffer] + comp_buf_bytes = comp_tensor.numel() * comp_tensor.element_size() + if ch.device_completions_offset + ch.completion_slots * 8 > comp_buf_bytes: + raise ValueError("async transfer device_completions exceeds its registered buffer") self.signatures = MappingProxyType(dict(signatures)) durations = dict.fromkeys(self.serving_graphs, 0) if estimated_durations_ns is None else dict(estimated_durations_ns) if durations.keys() != self.serving_graphs.keys() or any( @@ -326,6 +426,38 @@ def _manifest(self, *, all_variants, export_graphs) -> dict[str, Any]: }, } for worker in self.persistent_workers + ], + "async_transfers": [ + { + "name": ch.name, + "device_pool": ch.device_pool, + "control": { + "allocation": ch.control_buffer, + "offset": ch.control_offset, + }, + "control_bytes": ( + ch.control_bytes + if ch.control_bytes + else self.buffers[ch.control_buffer].numel() + * self.buffers[ch.control_buffer].element_size() + - ch.control_offset + ), + **( + {} + if ch.device_completions_buffer is None + else { + "device_completions": { + "allocation": ch.device_completions_buffer, + "offset": ch.device_completions_offset, + } + } + ), + "completion_slots": ch.completion_slots, + "ring_capacity": ch.ring_capacity, + "max_host_pool_bytes": ch.max_host_pool_bytes, + "alignment": ch.alignment, + } + for ch in self.async_transfers ]} def start_executor(self, *, peers=None): @@ -334,6 +466,7 @@ def start_executor(self, *, peers=None): raise ValueError( "persistent worker requires green-context runtime control (export a core and serve with flare run)" ) + reject_in_process_async_transfers(self.async_transfers) import flare_heliopause import torch @@ -353,6 +486,7 @@ def serve_rank(self, socket, *, rank, world): raise ValueError( "persistent worker requires green-context runtime control (export a core and serve with flare run)" ) + reject_in_process_async_transfers(self.async_transfers) import flare_heliopause import torch diff --git a/ignition/preparation/model.py b/ignition/preparation/model.py index fbf06b0ef..4ae9e0bfe 100644 --- a/ignition/preparation/model.py +++ b/ignition/preparation/model.py @@ -96,6 +96,9 @@ def start_server(self, *, bind: str = "127.0.0.1:8000", template_defaults=None, raise ValueError( "persistent worker requires green-context runtime control (export a core and serve with flare run)" ) + from .execution import reject_in_process_async_transfers + + reject_in_process_async_transfers(self.async_transfers) import flare_heliopause if not hasattr(flare_heliopause, "Server"): @@ -165,6 +168,7 @@ def _close_locked(self): self._graphs = MappingProxyType({}) self.serving_graphs = self.tuning_graphs = self.tuned_bindings = MappingProxyType({}) self.persistent_workers = () + self.async_transfers = () self.forwards = None self.benchmark_state = self.benchmark_pool = self.benchmark_requests = self.benchmark_rounds = None self.benchmark_prefills = None diff --git a/ignition/preparation/runtime_core.py b/ignition/preparation/runtime_core.py index b697235ed..a09e4b71a 100644 --- a/ignition/preparation/runtime_core.py +++ b/ignition/preparation/runtime_core.py @@ -428,6 +428,15 @@ def export_model(prepared, images, storage, path, *, options, progress=None, pub parameter_layouts=parameter_layouts, zero_ranges=zero_ranges, transports=transports, device_address_floor=storage.EXTERNAL_FLOOR if storage.integrated else 0, execution=prepared.export_manifest(), server=server, + external_extents=[ + { + "channel": ch.name, + "directory": str(ch.extent_directory), + "segments": [str(segment) for segment in ch.extent_segments], + } + for ch in getattr(prepared, "async_transfers", ()) + if ch.extent_directory + ], core_data=None if bundle_only or prepared.core_data is None else prepared.core_data.export_metadata(), rebuild_weights=None if getattr(prepared, "rebuild_weights", None) is None else rebuild_weights_metadata(prepared.rebuild_weights), diff --git a/ignition/preparation/runtime_core_pb2.py b/ignition/preparation/runtime_core_pb2.py index 14dbfe4eb..3bac9c05e 100644 --- a/ignition/preparation/runtime_core_pb2.py +++ b/ignition/preparation/runtime_core_pb2.py @@ -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\"\x99\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\"E\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\"\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\"\xc3\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\"=\n\x06Method\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nXOR_MODULO\x10\x01\x12\x12\n\x0e\x45OS_XOR_MODULO\x10\x02\"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\"\xb9\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\"\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*(\n\x08\x43\x61pacity\x12\x0e\n\nSTATE_ROWS\x10\x00\x12\x0c\n\x08KV_PAGES\x10\x01*-\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\"\x99\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\"E\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\"\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\"\xc3\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\"=\n\x06Method\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0e\n\nXOR_MODULO\x10\x01\x12\x12\n\x0e\x45OS_XOR_MODULO\x10\x02\"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') _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=16373 - _globals['_PREPARATIONPARAMETERSCOPE']._serialized_end=16623 - _globals['_HISTORYKIND']._serialized_start=16626 - _globals['_HISTORYKIND']._serialized_end=16768 - _globals['_VALUESOURCE']._serialized_start=16771 - _globals['_VALUESOURCE']._serialized_end=17738 - _globals['_INPUTINDEXING']._serialized_start=17740 - _globals['_INPUTINDEXING']._serialized_end=17864 - _globals['_STATEACCESSKIND']._serialized_start=17866 - _globals['_STATEACCESSKIND']._serialized_end=17950 - _globals['_GRAPHOPERATION']._serialized_start=17953 - _globals['_GRAPHOPERATION']._serialized_end=18220 - _globals['_TOOLPARSERKIND']._serialized_start=18223 - _globals['_TOOLPARSERKIND']._serialized_end=18401 - _globals['_REASONINGPARSERKIND']._serialized_start=18404 - _globals['_REASONINGPARSERKIND']._serialized_end=18570 - _globals['_IMAGEPREPARATIONKIND']._serialized_start=18573 - _globals['_IMAGEPREPARATIONKIND']._serialized_end=18945 - _globals['_IMAGELAYOUTKIND']._serialized_start=18948 - _globals['_IMAGELAYOUTKIND']._serialized_end=19258 - _globals['_PROMPTENCODER']._serialized_start=19260 - _globals['_PROMPTENCODER']._serialized_end=19340 - _globals['_TEMPLATEENCODING']._serialized_start=19342 - _globals['_TEMPLATEENCODING']._serialized_end=19408 - _globals['_MEMORY']._serialized_start=19410 - _globals['_MEMORY']._serialized_end=19457 - _globals['_CAPACITY']._serialized_start=19459 - _globals['_CAPACITY']._serialized_end=19499 - _globals['_RELOCATIONKIND']._serialized_start=19501 - _globals['_RELOCATIONKIND']._serialized_end=19546 - _globals['_DRAFTSOURCE']._serialized_start=19548 - _globals['_DRAFTSOURCE']._serialized_end=19600 + _globals['_PREPARATIONPARAMETERSCOPE']._serialized_start=16736 + _globals['_PREPARATIONPARAMETERSCOPE']._serialized_end=16986 + _globals['_HISTORYKIND']._serialized_start=16989 + _globals['_HISTORYKIND']._serialized_end=17131 + _globals['_VALUESOURCE']._serialized_start=17134 + _globals['_VALUESOURCE']._serialized_end=18101 + _globals['_INPUTINDEXING']._serialized_start=18103 + _globals['_INPUTINDEXING']._serialized_end=18227 + _globals['_STATEACCESSKIND']._serialized_start=18229 + _globals['_STATEACCESSKIND']._serialized_end=18313 + _globals['_GRAPHOPERATION']._serialized_start=18316 + _globals['_GRAPHOPERATION']._serialized_end=18583 + _globals['_TOOLPARSERKIND']._serialized_start=18586 + _globals['_TOOLPARSERKIND']._serialized_end=18764 + _globals['_REASONINGPARSERKIND']._serialized_start=18767 + _globals['_REASONINGPARSERKIND']._serialized_end=18933 + _globals['_IMAGEPREPARATIONKIND']._serialized_start=18936 + _globals['_IMAGEPREPARATIONKIND']._serialized_end=19308 + _globals['_IMAGELAYOUTKIND']._serialized_start=19311 + _globals['_IMAGELAYOUTKIND']._serialized_end=19621 + _globals['_PROMPTENCODER']._serialized_start=19623 + _globals['_PROMPTENCODER']._serialized_end=19703 + _globals['_TEMPLATEENCODING']._serialized_start=19705 + _globals['_TEMPLATEENCODING']._serialized_end=19771 + _globals['_MEMORY']._serialized_start=19773 + _globals['_MEMORY']._serialized_end=19820 + _globals['_CAPACITY']._serialized_start=19822 + _globals['_CAPACITY']._serialized_end=19879 + _globals['_RELOCATIONKIND']._serialized_start=19881 + _globals['_RELOCATIONKIND']._serialized_end=19926 + _globals['_DRAFTSOURCE']._serialized_start=19928 + _globals['_DRAFTSOURCE']._serialized_end=19980 _globals['_PROTECTEDINDEX']._serialized_start=38 _globals['_PROTECTEDINDEX']._serialized_end=191 _globals['_SIGNEDGROUP']._serialized_start=193 @@ -242,15 +242,17 @@ _globals['_EDGE']._serialized_start=15013 _globals['_EDGE']._serialized_end=15070 _globals['_EXECUTION']._serialized_start=15073 - _globals['_EXECUTION']._serialized_end=15386 - _globals['_PERSISTENTWORKER']._serialized_start=15389 - _globals['_PERSISTENTWORKER']._serialized_end=15558 - _globals['_TUNINGGRAPH']._serialized_start=15560 - _globals['_TUNINGGRAPH']._serialized_end=15627 - _globals['_BUFFER']._serialized_start=15630 - _globals['_BUFFER']._serialized_end=15760 - _globals['_EXECUTIONGRAPH']._serialized_start=15763 - _globals['_EXECUTIONGRAPH']._serialized_end=16296 - _globals['_INPUTBINDING']._serialized_start=16298 - _globals['_INPUTBINDING']._serialized_end=16370 + _globals['_EXECUTION']._serialized_end=15441 + _globals['_ASYNCTRANSFER']._serialized_start=15444 + _globals['_ASYNCTRANSFER']._serialized_end=15749 + _globals['_PERSISTENTWORKER']._serialized_start=15752 + _globals['_PERSISTENTWORKER']._serialized_end=15921 + _globals['_TUNINGGRAPH']._serialized_start=15923 + _globals['_TUNINGGRAPH']._serialized_end=15990 + _globals['_BUFFER']._serialized_start=15993 + _globals['_BUFFER']._serialized_end=16123 + _globals['_EXECUTIONGRAPH']._serialized_start=16126 + _globals['_EXECUTIONGRAPH']._serialized_end=16659 + _globals['_INPUTBINDING']._serialized_start=16661 + _globals['_INPUTBINDING']._serialized_end=16733 # @@protoc_insertion_point(module_scope) diff --git a/selene/src/offload.rs b/selene/src/offload.rs index ee1ebbbf2..835ab9563 100644 --- a/selene/src/offload.rs +++ b/selene/src/offload.rs @@ -974,11 +974,22 @@ pub fn host_pool_budget(future: u64) -> Result { host_pool_budget_with_reserve(future, true) } +/// Like [`host_pool_budget`], returning `(budget_bytes, total_host_ram_bytes)`. +pub fn host_pool_budget_and_total(future: u64) -> Result<(u64, u64)> { + let (available, total) = host_memory_bytes()?; + Ok((host_pool_budget_from(available, total, future, true), total)) +} + /// Like [`host_pool_budget`], allowing callers with an explicit unified-memory limit /// to omit the implicit service and system reserves. pub fn host_pool_budget_with_reserve(future: u64, apply_reserve: bool) -> Result { + let (available, total) = host_memory_bytes()?; + Ok(host_pool_budget_from(available, total, future, apply_reserve)) +} + +fn host_memory_bytes() -> Result<(u64, u64)> { #[cfg(unix)] - let (available, total) = { + { let info = std::fs::read_to_string("/proc/meminfo").map_err(|e| e.to_string())?; let total = info .lines() @@ -991,19 +1002,18 @@ pub fn host_pool_budget_with_reserve(future: u64, apply_reserve: bool) -> Result .ok_or_else(|| { crate::Error::new("Linux MemTotal is required to budget local intake memory") })?; - (available_memory(&info, usize::MAX)? as u64, total) - }; + Ok((available_memory(&info, usize::MAX)? as u64, total)) + } #[cfg(windows)] - let (available, total) = unsafe { + unsafe { use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; let mut memory: MEMORYSTATUSEX = std::mem::zeroed(); memory.dwLength = std::mem::size_of::() as u32; if GlobalMemoryStatusEx(&mut memory) == 0 { return Err(std::io::Error::last_os_error().to_string().into()); } - (memory.ullAvailPhys, memory.ullTotalPhys) - }; - Ok(host_pool_budget_from(available, total, future, apply_reserve)) + Ok((memory.ullAvailPhys, memory.ullTotalPhys)) + } } /// Resources retained from pre-sizing registration through the worker's store attachment. diff --git a/verification/helios-lifecycle/AsyncTransfer.cfg b/verification/helios-lifecycle/AsyncTransfer.cfg new file mode 100644 index 000000000..ce7f2a8c9 --- /dev/null +++ b/verification/helios-lifecycle/AsyncTransfer.cfg @@ -0,0 +1,20 @@ +CONSTANTS + MaxTotalIo = 2 + MaxBgIo = 1 + MaxTotalDma = 2 + MaxBgDma = 1 + BounceSlots = 1 + MaxEpoch = 2 + MaxQueue = 2 + +SPECIFICATION Spec + +INVARIANTS + TypeOK + NoUnmapWhileInflight + FailedDrainRetainsResources + StoppedHasZeroInflight + BoundedHardwareDepth + BounceSlotConservation + DrainingHasEmptyQueues + CanReleaseExact diff --git a/verification/helios-lifecycle/AsyncTransfer.tla b/verification/helios-lifecycle/AsyncTransfer.tla new file mode 100644 index 000000000..6d9bc3982 --- /dev/null +++ b/verification/helios-lifecycle/AsyncTransfer.tla @@ -0,0 +1,267 @@ +------------------------ MODULE AsyncTransfer ------------------------ +EXTENDS Naturals, Sequences, TLC + +CONSTANTS MaxTotalIo, MaxBgIo, MaxTotalDma, MaxBgDma, BounceSlots, MaxEpoch, MaxQueue +VARIABLE state + +Phases == 0..4 +IDLE == 0 +RUNNING == 1 +DRAINING == 2 +STOPPED == 3 +FAILED_DRAIN == 4 + +Initial == + [phase |-> IDLE, + activeEpoch |-> 0, + qIo |-> 0, + qDma |-> 0, + inDemIo |-> 0, + inBgIo |-> 0, + inDemDma |-> 0, + inBgDma |-> 0, + bInIo |-> 0, + bQDma |-> 0, + bInDma |-> 0, + freeBounce |-> BounceSlots, + canRelease |-> 1] + +Init == state = Initial + +CanReleaseFor(st) == + IF st.phase \in {IDLE, STOPPED} + /\ st.inDemIo = 0 /\ st.inBgIo = 0 + /\ st.inDemDma = 0 /\ st.inBgDma = 0 + THEN 1 ELSE 0 + +WithRelease(st) == [st EXCEPT !.canRelease = CanReleaseFor(st)] + +Start(before, after) == + /\ before.phase = IDLE + /\ after = WithRelease([before EXCEPT !.phase = RUNNING]) + +Enqueue(before, after) == + /\ before.phase = RUNNING + /\ before.qIo + before.qDma < MaxQueue + /\ \/ after = WithRelease([before EXCEPT !.qIo = @ + 1]) + \/ after = WithRelease([before EXCEPT !.qDma = @ + 1]) + \/ after = before + +CancelEpoch(before, after) == + /\ before.phase = RUNNING + /\ \E nextEp \in (before.activeEpoch + 1)..MaxEpoch, + dropIo \in 0..before.qIo, + dropDma \in 0..before.qDma : + \E retBounce \in 0..before.bQDma : + /\ retBounce <= dropDma + /\ (before.bQDma - retBounce) <= (before.qDma - dropDma) + /\ after = WithRelease([before EXCEPT + !.activeEpoch = nextEp, + !.qIo = @ - dropIo, + !.qDma = @ - dropDma, + !.bQDma = @ - retBounce, + !.freeBounce = @ + retBounce]) + +DispatchIo(before, after) == + /\ before.phase = RUNNING + /\ before.qIo > 0 + /\ before.inDemIo + before.inBgIo < MaxTotalIo + /\ \E isBg \in BOOLEAN, takeBounce \in 0..1 : + /\ (~isBg \/ before.inBgIo < MaxBgIo) + /\ takeBounce <= before.freeBounce + /\ after = WithRelease([before EXCEPT + !.qIo = @ - 1, + !.inDemIo = @ + IF isBg THEN 0 ELSE 1, + !.inBgIo = @ + IF isBg THEN 1 ELSE 0, + !.bInIo = @ + takeBounce, + !.freeBounce = @ - takeBounce]) + +DispatchDma(before, after) == + /\ before.phase = RUNNING + /\ before.qDma > 0 + /\ before.inDemDma + before.inBgDma < MaxTotalDma + /\ \E isBg \in BOOLEAN, hasBounce \in 0..1 : + /\ (~isBg \/ before.inBgDma < MaxBgDma) + /\ hasBounce <= before.bQDma + /\ (before.bQDma - hasBounce) <= (before.qDma - 1) + /\ after = WithRelease([before EXCEPT + !.qDma = @ - 1, + !.inDemDma = @ + IF isBg THEN 0 ELSE 1, + !.inBgDma = @ + IF isBg THEN 1 ELSE 0, + !.bQDma = @ - hasBounce, + !.bInDma = @ + hasBounce]) + +CompleteIo(before, after) == + /\ before.phase \in {RUNNING, DRAINING, FAILED_DRAIN} + /\ \E isBg \in BOOLEAN, promoteDma \in BOOLEAN, hasBounce \in 0..1 : + /\ IF isBg THEN before.inBgIo > 0 ELSE before.inDemIo > 0 + /\ hasBounce <= before.bInIo + /\ (before.bInIo - hasBounce) <= (before.inDemIo + before.inBgIo - 1) + /\ (promoteDma => before.phase = RUNNING /\ before.qDma < MaxQueue + MaxTotalIo) + /\ after = WithRelease([before EXCEPT + !.inDemIo = @ - IF isBg THEN 0 ELSE 1, + !.inBgIo = @ - IF isBg THEN 1 ELSE 0, + !.bInIo = @ - hasBounce, + !.qDma = @ + IF promoteDma THEN 1 ELSE 0, + !.bQDma = @ + IF promoteDma THEN hasBounce ELSE 0, + !.freeBounce = @ + IF promoteDma THEN 0 ELSE hasBounce]) + +CompleteDma(before, after) == + /\ before.phase \in {RUNNING, DRAINING, FAILED_DRAIN} + /\ \E isBg \in BOOLEAN, hasBounce \in 0..1 : + /\ IF isBg THEN before.inBgDma > 0 ELSE before.inDemDma > 0 + /\ hasBounce <= before.bInDma + /\ (before.bInDma - hasBounce) <= (before.inDemDma + before.inBgDma - 1) + /\ after = WithRelease([before EXCEPT + !.inDemDma = @ - IF isBg THEN 0 ELSE 1, + !.inBgDma = @ - IF isBg THEN 1 ELSE 0, + !.bInDma = @ - hasBounce, + !.freeBounce = @ + hasBounce]) + +BeginDrain(before, after) == + \/ /\ before.phase = IDLE + /\ after = WithRelease([before EXCEPT !.phase = STOPPED]) + \/ /\ before.phase = RUNNING + /\ after = WithRelease([before EXCEPT + !.phase = DRAINING, + !.qIo = 0, + !.qDma = 0, + !.bQDma = 0, + !.freeBounce = @ + before.bQDma]) + +FinishDrainOk(before, after) == + /\ before.phase = DRAINING + /\ before.inDemIo = 0 /\ before.inBgIo = 0 + /\ before.inDemDma = 0 /\ before.inBgDma = 0 + /\ before.freeBounce = BounceSlots + /\ after = WithRelease([before EXCEPT !.phase = STOPPED]) + +FinishDrainFail(before, after) == + /\ before.phase = DRAINING + /\ after = WithRelease([before EXCEPT !.phase = FAILED_DRAIN]) + +Step(before, after) == + \/ Start(before, after) + \/ Enqueue(before, after) + \/ CancelEpoch(before, after) + \/ DispatchIo(before, after) + \/ DispatchDma(before, after) + \/ CompleteIo(before, after) + \/ CompleteDma(before, after) + \/ BeginDrain(before, after) + \/ FinishDrainOk(before, after) + \/ FinishDrainFail(before, after) + +Next == Step(state, state') \/ UNCHANGED state + +WellTyped(st) == + /\ st.phase \in Phases + /\ st.activeEpoch \in 0..MaxEpoch + /\ st.qIo \in 0..(MaxQueue + MaxTotalIo) + /\ st.qDma \in 0..(MaxQueue + MaxTotalIo) + /\ st.inDemIo \in 0..MaxTotalIo + /\ st.inBgIo \in 0..MaxTotalIo + /\ st.inDemDma \in 0..MaxTotalDma + /\ st.inBgDma \in 0..MaxTotalDma + /\ st.bInIo \in 0..BounceSlots + /\ st.bQDma \in 0..BounceSlots + /\ st.bInDma \in 0..BounceSlots + /\ st.freeBounce \in 0..BounceSlots + /\ st.canRelease \in 0..1 + +NoUnmapWhileInflightAt(st) == + (st.inDemIo + st.inBgIo + st.inDemDma + st.inBgDma > 0) => st.canRelease = 0 + +FailedDrainRetainsResourcesAt(st) == + st.phase = FAILED_DRAIN => st.canRelease = 0 + +StoppedHasZeroInflightAt(st) == + st.phase = STOPPED => + /\ st.inDemIo = 0 /\ st.inBgIo = 0 + /\ st.inDemDma = 0 /\ st.inBgDma = 0 + /\ st.qIo = 0 /\ st.qDma = 0 + /\ st.freeBounce = BounceSlots + +BoundedHardwareDepthAt(st) == + /\ st.inBgIo <= MaxBgIo + /\ st.inBgDma <= MaxBgDma + /\ st.inDemIo + st.inBgIo <= MaxTotalIo + /\ st.inDemDma + st.inBgDma <= MaxTotalDma + +BounceSlotConservationAt(st) == + /\ st.freeBounce + st.bInIo + st.bQDma + st.bInDma = BounceSlots + /\ st.bInIo <= st.inDemIo + st.inBgIo + /\ st.bQDma <= st.qDma + /\ st.bInDma <= st.inDemDma + st.inBgDma + +DrainingHasEmptyQueuesAt(st) == + st.phase = DRAINING => (st.qIo = 0 /\ st.qDma = 0 /\ st.bQDma = 0) + +CanReleaseExactAt(st) == + st.canRelease = CanReleaseFor(st) + +ObservedSafe(st) == + /\ WellTyped(st) + /\ NoUnmapWhileInflightAt(st) + /\ FailedDrainRetainsResourcesAt(st) + /\ StoppedHasZeroInflightAt(st) + /\ BoundedHardwareDepthAt(st) + /\ BounceSlotConservationAt(st) + /\ DrainingHasEmptyQueuesAt(st) + /\ CanReleaseExactAt(st) + +TypeOK == WellTyped(state) +NoUnmapWhileInflight == NoUnmapWhileInflightAt(state) +FailedDrainRetainsResources == FailedDrainRetainsResourcesAt(state) +StoppedHasZeroInflight == StoppedHasZeroInflightAt(state) +BoundedHardwareDepth == BoundedHardwareDepthAt(state) +BounceSlotConservation == BounceSlotConservationAt(state) +DrainingHasEmptyQueues == DrainingHasEmptyQueuesAt(state) +CanReleaseExact == CanReleaseExactAt(state) + +Projection(st) == + <> + +Decode(v) == + [phase |-> v[1], + activeEpoch |-> v[2], + qIo |-> v[3], + qDma |-> v[4], + inDemIo |-> v[5], + inBgIo |-> v[6], + inDemDma |-> v[7], + inBgDma |-> v[8], + bInIo |-> v[9], + bQDma |-> v[10], + bInDma |-> v[11], + freeBounce |-> v[12], + canRelease |-> v[13]] + +ObservedState(v) == Decode(v) + +ActionMatches(before, kind, after) == + \/ /\ kind = 1 /\ Start(before, after) + \/ /\ kind = 2 /\ Enqueue(before, after) + \/ /\ kind = 3 /\ CancelEpoch(before, after) + \/ /\ kind = 4 /\ DispatchIo(before, after) + \/ /\ kind = 5 /\ DispatchDma(before, after) + \/ /\ kind = 6 /\ CompleteIo(before, after) + \/ /\ kind = 7 /\ CompleteDma(before, after) + \/ /\ kind = 8 /\ BeginDrain(before, after) + \/ /\ kind = 9 /\ FinishDrainOk(before, after) + \/ /\ kind = 10 /\ FinishDrainFail(before, after) + +AllowedEdge(edge) == + LET before == ObservedState(edge[1]) + kind == edge[2][1] + after == ObservedState(edge[3]) + IN /\ Projection(before) = edge[1] + /\ Projection(after) = edge[3] + /\ ObservedSafe(before) + /\ ObservedSafe(after) + /\ ActionMatches(before, kind, after) + +Spec == Init /\ [][Next]_state +============================================================================= diff --git a/verification/helios-lifecycle/README.md b/verification/helios-lifecycle/README.md index d726da3a6..699f6c3b9 100644 --- a/verification/helios-lifecycle/README.md +++ b/verification/helios-lifecycle/README.md @@ -7,7 +7,8 @@ Rank-control checks cover readiness and completion predicates guarding tensor-parallel submission and queue removal. Additional checks cover native response admission and buffered events, prefix-checkpoint ownership, speculative scheduling arithmetic, snapshot backing -aliases, and multi-rank offload reply aggregation. +aliases, multi-rank offload reply aggregation, and asynchronous extent-transfer +scheduling and drain ownership. ## Run the check @@ -345,6 +346,31 @@ rank count. Duplicate in-flight submission and empty polling are checked too. CUDA copies, physical slab ownership, worker channel lifetimes, shutdown drain, and scheduler cancellation require their separate contracts and execution tests. +## Asynchronous extent transfer scheduling + +`AsyncTransfer.tla` checks bounded asynchronous extent-transfer scheduling and +drain ownership across five phases (`IDLE`, `RUNNING`, `DRAINING`, `STOPPED`, +`FAILED_DRAIN`) with `MaxTotalIo = 2`, `MaxBgIo = 1`, `MaxTotalDma = 2`, +`MaxBgDma = 1`, `BounceSlots = 1`, `MaxEpoch = 2`, and `MaxQueue = 2`. +Invariants enforce no memory release while any storage I/O or Copy Engine DMA is +in flight (`NoUnmapWhileInflight`), permanent retention after failed drain +(`FailedDrainRetainsResources`), zero in-flight work when stopped +(`StoppedHasZeroInflight`), bounded total and background hardware concurrency +(`BoundedHardwareDepth`), exact conservation of internal bounce slots across +in-flight I/O, queued follow-on DMA, and in-flight DMA (`BounceSlotConservation`), +and drained queues once shutdown begins (`DrainingHasEmptyQueues`). + +`async_transfer::lifecycle_tests::async_transfer_scheduler_matches_lifecycle_model` +drives production `TransferScheduler` transitions (`start`, `enqueue`, +`cancel_epoch`, `dispatch_io`, `complete_io`, `dispatch_dma`, `complete_dma`, +`begin_drain`, `finish_drain`, `fail_drain`) across priority preemption, +epoch cancellation, fused bounce-staged transfers, and confirmed vs. failed +drain. Its 13-integer projection carries the phase, active epoch, queued I/O and +DMA counts, demand/background in-flight I/O and DMA counts, bounce-slot +partition, and release predicate. Linux `io_uring` submission, CUDA Copy Engine +ordering, `cuStreamWriteValue64` completion signaling, and pinned host memory +registration require their separate CUDA integration tests. + ## Assumptions and limits Scheduler methods are atomic relative to other scheduler calls because one @@ -401,8 +427,9 @@ Run the sequential validator proofs from the repository root: cargo kani --manifest-path helios/Cargo.toml --features runtime-core --lib ``` -The harnesses call production functions in `execution/transport.rs`, `model.rs`, -`model/contract.rs`, and `output/tagged.rs`. They compile only under `cfg(kani)` +The harnesses call production functions in `async_transfer/ring.rs`, +`execution/transport.rs`, `model.rs`, `model/contract.rs`, and +`output/tagged.rs`. They compile only under `cfg(kani)` and do not select a serving path. Kani 0.68.0 uses CBMC 6.11.0 and nightly-2026-08-21. Automatic safety and unwinding checks remain enabled. The completion harnesses use unwind bound 20, the 65-token mask-boundary harness @@ -449,6 +476,16 @@ both acceptance and rejection, including overflow and exact boundaries. Each vector allocates one element before selecting its empty/single-element length; allocation sites are independent of the geometry cases. +Four harnesses in `async_transfer/kani_proofs.rs` verify `async_transfer/ring.rs` +against independent `u128` arithmetic oracles over arbitrary inputs: +`control_layout_matches_u128_oracle` (`validate_control_layout`), +`extent_entry_matches_u128_oracle` (`validate_extent_entry`), +`resolve_pool_bytes_is_aligned_and_bounded` (`resolve_pool_bytes`, including +alignment maximality), and +`validate_command_guarantees_bounds_and_alignment_for_all_inputs` +(`validate_command` across all opcodes, priorities, completion slots, bounce +sentinels, and two-entry extent slices). + Run the accompanying manifest-lookup and diagnostic test: ```sh diff --git a/verification/helios-lifecycle/check.py b/verification/helios-lifecycle/check.py index 44f469b61..e6c43419d 100644 --- a/verification/helios-lifecycle/check.py +++ b/verification/helios-lifecycle/check.py @@ -31,7 +31,9 @@ ("ResponseLifecycle", "server::runtime::phase_tests::response_lifecycle_tests::native_responses_match_lifecycle_model", "RESPONSE_EDGE ", 28), ("CheckpointReservation", "scheduler::checkpoint_lifecycle_tests::", - "CHECKPOINT_RESERVATION_EDGE ", 16)] + "CHECKPOINT_RESERVATION_EDGE ", 16), + ("AsyncTransfer", "async_transfer::lifecycle_tests::async_transfer_scheduler_matches_lifecycle_model", + "ASYNC_TRANSFER_EDGE ", 13)] MODELS = [check[0] for check in CHECKS] + ["RankDispatch"] @@ -396,6 +398,26 @@ def run_aux(test): " ELSE /\\ request \\notin before.deferred", " /\\ IF row = 0 THEN after = before\n" " ELSE /\\ TRUE", "DeferredHasNoReadyCapture"), + ("AsyncTransfer", + "FinishDrainOk(before, after) ==\n" + " /\\ before.phase = DRAINING\n" + " /\\ before.inDemIo = 0 /\\ before.inBgIo = 0\n" + " /\\ before.inDemDma = 0 /\\ before.inBgDma = 0", + "FinishDrainOk(before, after) ==\n" + " /\\ before.phase = DRAINING", + "StoppedHasZeroInflight"), + ("AsyncTransfer", + " /\\ \\E isBg \\in BOOLEAN, hasBounce \\in 0..1 :\n" + " /\\ (~isBg \\/ before.inBgDma < MaxBgDma)", + " /\\ \\E isBg \\in BOOLEAN, hasBounce \\in 0..1 :\n" + " /\\ TRUE", + "BoundedHardwareDepth"), + ("AsyncTransfer", + " !.bQDma = 0,\n" + " !.freeBounce = @ + before.bQDma])", + " !.bQDma = 0,\n" + " !.freeBounce = @])", + "BounceSlotConservation"), ] with ThreadPoolExecutor(max_workers=min(args.jobs, len(model_mutations))) as pool: futures = [ @@ -683,6 +705,24 @@ def run_aux(test): "accounting.budgeted_anchor = None;", "multi-chunk prefill must retain budgeted-anchor prompt-end fallback"), ]) + check_mutations(cargo, ROOT / "helios/src/async_transfer/scheduler.rs", CHECKS[8][1], [ + ("unconfirmed async transfer drain", + "if stream_drained && self.inflight_io.is_empty() && self.inflight_dma.is_empty() {", + "if true {", + "unconfirmed drain must not complete into Stopped"), + ("exceeded background DMA cap", + "if prio.is_background() && bg_used >= self.max_bg_dma {", + "if false {", + "background DMA depth exceeded cap"), + ("leaked bounce slot on drain", + "if let Some(slot) = op.bounce_slot() {\n self.free_bounce_slots.push(slot);\n }", + "let _ = op.bounce_slot();", + "bounce slot conservation violated"), + ("failed drain allowed memory release", + "matches!(self.state, ChannelState::Idle | ChannelState::Stopped)", + "matches!(self.state, ChannelState::Idle | ChannelState::Stopped | ChannelState::FailedDrain)", + "failed drain must retain pinned memory"), + ]) restored_bin = build_test_binary(cargo) run_observed_checks(restored_bin, directory, args.java, jar, args.jobs)